问:
How to setstate in a loop?
i am getting error at this.setState({ Url: resp.data.Url }); in GETAPI
TypeError: Cannot read property 'setState' of undefined..
 Please suggest.
 The GETAPI is basically used to render the data from the API. My use-case is to store all the URLs in state and pass it to DownloadButton component. I need this URL to download the required data.

The hirerachy of code is invokeGetReport which will give all the reports in array. I have looped in and invoked invokeGetReportDetails method. Under invokeGetReportDetails , i am calling invokeImageURL which will contain the URL'of all the reports. I need to store all the URLs in state & passed it to next component

```<code>class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
   return (
      <div>
        <DownloadButton imageUrl={this.Url} />
      </div>
    );
  }
}

export default GetAPI;
</code>```

答:
This error is because this is not referrring to GetAPI component and that's because the way you have nested multiple functions inside componentDidMount function.

Write all those functions outside the componentDidMount function and use arrow functions.

Not related to the error but you are also not updating the state correctly. You are overwriting it instead of appending the new url to the existing list of urls.

Change

```<code>this.setState({ Url: resp.data.Url });
</code>```

to

```<code>this.setState({ Url: [...this.state.Url, resp.data.Url] });
</code>```

Here's the fixed code

```<code>class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {
    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        this.invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  invokeGetReportDetails = (accesstoken, reportID) => {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            this.invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  invokeImageURL = (accesstoken, expenseEntryId) => {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: [...this.state.Url, resp.data.Url] });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  invokeGetReport = (accesstoken) => {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
            console.log(resp);
            console.log("data id is " + resp.data.Items.length);

            //  debugger;
            for (let i = 0; i < resp.data.Items.length; i++) {
              let reportName = resp.data.Items[i].Name;
              let reportID = resp.data.Items[i].ID;
              console.log("id is : " + reportID + "Report Name : " + reportName);
              this.invokeGetReportDetails(accesstoken, reportID);
              reports.push(reportID);
            }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  render() {
   return (
      <div>
        <DownloadButton imageUrl={this.Url} />
      </div>
    );
  }
}

export default GetAPI;
</code>```

Title: How to setstate in a loop?

Body:
i am getting error at this.setState({ Url: resp.data.Url }); in GETAPI
TypeError: Cannot read property 'setState' of undefined..
 Please suggest.
 The GETAPI is basically used to render the data from the API. My use-case is to store all the URLs in state and pass it to DownloadButton component. I need this URL to download the required data.

The hirerachy of code is invokeGetReport which will give all the reports in array. I have looped in and invoked invokeGetReportDetails method. Under invokeGetReportDetails , i am calling invokeImageURL which will contain the URL'of all the reports. I need to store all the URLs in state & passed it to next component

class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
   return (

        <DownloadButton imageUrl={this.Url} />

    );
  }
}

export default GetAPI;

Body:
This error is because this is not referrring to GetAPI component and that's because the way you have nested multiple functions inside componentDidMount function.

Write all those functions outside the componentDidMount function and use arrow functions.

Not related to the error but you are also not updating the state correctly. You are overwriting it instead of appending the new url to the existing list of urls.

Change

this.setState({ Url: resp.data.Url });

to

this.setState({ Url: [...this.state.Url, resp.data.Url] });

Here's the fixed code

class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {
    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        this.invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  invokeGetReportDetails = (accesstoken, reportID) => {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            this.invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  invokeImageURL = (accesstoken, expenseEntryId) => {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: [...this.state.Url, resp.data.Url] });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  invokeGetReport = (accesstoken) => {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
            console.log(resp);
            console.log("data id is " + resp.data.Items.length);

            //  debugger;
            for (let i = 0; i < resp.data.Items.length; i++) {
              let reportName = resp.data.Items[i].Name;
              let reportID = resp.data.Items[i].ID;
              console.log("id is : " + reportID + "Report Name : " + reportName);
              this.invokeGetReportDetails(accesstoken, reportID);
              reports.push(reportID);
            }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
  }

  render() {
   return (
      <div>
        <DownloadButton imageUrl={this.Url} />
      </div>
    );
  }
}

export default GetAPI;


来源: stackexchange

问:
Writing Text to Word document
i need to create an application which writes text into a word document while typing on a TextBox.any one knows a interface to achieve this?</p>

答:
If you are talking about creating and/or filling a Word document completely from code, I recommend that you take a look at the (commercial) Aspose.Words library.

If you are talking about "remote-controlling" Word from your own application, I recommend that you take a look at Microsoft Office Automation.

ContentLicense: CC BY-SA 3.0

Title: Writing Text to Word document


问:
How can i use sizeof(pointer). So i get sizeof(array). Pointer is pointing to array
See the comment section in the code. There I explained what I want to understand and what I know.

How I can get 28 using ptr.
sizeof(arr) is giving me 28. (length of array elements) * sizeof(int)
But I can't figure out how to get this value using ptr.
I want this thing so I can get an array length using this method. In function own here.

```<code>int main (void)
{
    int arr[7] = {5, 8, 10, 50, 55, 98, 354};
    int result;

    /* ------- From here ---------*/

    int size = sizeof(arr) / sizeof(int);   // sizeof(arr) = 28, sizeof(int) = 4. So size = 28/4 = 7

    result = anyFunction (arr);

    return 0;
}

int anyFunction (int array[])
{
    int arraySize = sizeof(array) / sizeof(int);   // this line
}

</code>```

int *ptr = arr;
// Same as *ptr = &arr[0]

size = sizeof(ptr);
// 8 is the size of pointer.

size = sizeof(*ptr);
// size = 4.  4 is the size of arr[0]. Because its pointing to arr[0]. So its sizeof(arr[0]) or sizeof(5)

答:
If you use sizeof(array) when array is defined as int array[] I expect it to be the same as if it was defined as int *array since the size of the array isn't know.

The obvious solution is add a second parameter to anyFunction() with the array size.

ContentLicense: CC BY-SA 4.0

Body:
See the comment section in the code. There I explained what I want to understand and what I know.

How I can get 28 using ptr.
sizeof(arr) is giving me 28. (length of array elements) * sizeof(int)
But I can't figure out how to get this value using ptr.
I want this thing so I can get an array length using this method. In function own here.

int main (void)
{
    int arr[7] = {5, 8, 10, 50, 55, 98, 354};
    int result;

    /* ------- From here ---------*/

    int size = sizeof(arr) / sizeof(int);   // sizeof(arr) = 28, sizeof(int) = 4. So size = 28/4 = 7

    result = anyFunction (arr);

    return 0;
}

int anyFunction (int array[])
{
    int arraySize = sizeof(array) / sizeof(int);   // this line
}

int *ptr = arr;
// Same as *ptr = &arr[0]

size = sizeof(ptr);
// 8 is the size of pointer.

size = sizeof(*ptr);
// size = 4.  4 is the size of arr[0]. Because its pointing to arr[0]. So its sizeof(arr[0]) or sizeof(5)


问:
TextView hieght = wrap_content is not working
I have a LinearLayout which contains a single TextView :

```<code>            <LinearLayout
                android:id="@+id/addTaskDescriptionLLId"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp">
                <TextView
                    android:id="@+id/descriptionTextViewId"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:maxHeight="150dp"
                    android:hint="@string/abcd"
                    android:textColor="#A2A2A2"
                    android:ellipsize="end"
                    android:layout_margin="10dp"/>
            </LinearLayout>
</code>```

I've also added a condition in java file and the condition is if the TextView has some text during opening the activity then it will be visible otherwise I used descriptionTextView.setVisibility(View.GONE);

Then I put some text in this textView by opening a dialog and onConfirm (clicking positive button of dialog) I did the following:

    @Override
    public void onConfirm(String description) {
        this.description = description;    //the string that I write in dialog
        descriptionLL.removeAllViews();    //parent LineanLayout of TextView
        descriptionLL.addView(descriptionTextView);
        descriptionTextView.setText(description);
        descriptionTextView.setVisibility(View.VISIBLE);
    }
```

<p>But the TextView height doesn't remain wrap_content as I mentioned in xml file.
I've also tried :</p>

<pre class="lang-java prettyprint-override"><code>descriptionTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
</code>```

that also no working..Any solution?

答: I think the hint that you've specified in xml is causing the problem. Remove it, it might solve.

Body:
I have a LinearLayout which contains a single TextView :

            <LinearLayout
                android:id="@+id/addTaskDescriptionLLId"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp">
                <TextView
                    android:id="@+id/descriptionTextViewId"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:maxHeight="150dp"
                    android:hint="@string/abcd"
                    android:textColor="#A2A2A2"
                    android:ellipsize="end"
                    android:layout_margin="10dp"/>
            </LinearLayout>

I've also added a condition in java file and the condition is if the TextView has some text during opening the activity then it will be visible otherwise I used descriptionTextView.setVisibility(View.GONE);

Then I put some text in this textView by opening a dialog and onConfirm (clicking positive button of dialog) I did the following:

    @Override
    public void onConfirm(String description) {
        this.description = description;    //the string that I write in dialog
        descriptionLL.removeAllViews();    //parent LineanLayout of TextView
        descriptionLL.addView(descriptionTextView);
        descriptionTextView.setText(description);
        descriptionTextView.setVisibility(View.VISIBLE);
    }

But the TextView height doesn't remain wrap_content as I mentioned in xml file.
I've also tried :

descriptionTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

that also no working..Any solution?


问:
WPF- How to apply Style to Multiple controls within a Panel
I need to apply style to different controls within  a Stack Panel. They are all of different type i.e. TreeView,Listview,ComboBox etc.
Is there a way I can apply a style at StackPanel level to be applicable for these controls.
I don't want to apply style individually to these controls.
Is there any way to accomplish this?

Thanks..

答:
As Jean-Louis says, you can specify a Style within the StackPanel resource dictionary and it will only be applied to matching elements within that StackPanel.

In order to have a single Style match all of your controls, you will need to specify it with a TargetType of a common base class for all of those controls, such as Control

```<code><StackPanel>
  <StackPanel.Resources>
    <Style TargetType="Control">
      <!-- Setters etc here -->
    </Style>
  </StackPanel.Resources>

<!-- Controls here -->

</StackPanel>
</code>```

Body:
As Jean-Louis says, you can specify a Style within the StackPanel resource dictionary and it will only be applied to matching elements within that StackPanel.

In order to have a single Style match all of your controls, you will need to specify it with a TargetType of a common base class for all of those controls, such as Control

<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="Control">
      <!-- Setters etc here -->
    </Style>
  </StackPanel.Resources>

<!-- Controls here -->

</StackPanel>


问:
Stacked numpy arrays
I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose  has been shown below:

```<code>def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)
</code>```

The desired output is of the form :

```<code>[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
</code>```

But I get :

```<code>[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
</code>```

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.

答:
You are getting None because you are creating an empty array with dtype object:

```<code>h0 = np.empty(5,dtype=object)
</code>```

This line creates an array with None elements.

You can remove this line so that it works as you expect:

```<code>def fun1(i): # this function returns the array
  return array # This array is a function of i
arrays=[]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h = np.vstack(arrays)
print (h)
</code>```

Title: Stacked numpy arrays

Body:
I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose  has been shown below:

def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)

The desired output is of the form :

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

But I get :

[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.

Body:
You are getting None because you are creating an empty array with dtype object:

h0 = np.empty(5,dtype=object)

This line creates an array with None elements.

You can remove this line so that it works as you expect:

def fun1(i): # this function returns the array
  return array # This array is a function of i
arrays=[]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h = np.vstack(arrays)
print (h)


问:
Passing the same chain of parameters multiple times with currying
Given this expression:

```<code>// val fn1 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit
// val fn2 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit

type T =
  | A
  | B

// val t : T
// val a : 'a
// val b : 'b
// val c : 'c
// val d : 'd
// val e : 'e
// val f : 'f
// val g : 'g

match t with
| A -> fn1 a b c d e f g
| B -> fn2 a b c d e f g
</code>```

Is there a way to not repeat the same chain of parameters while calling a function that supports currying? so you could write some weird stuff like this

```<code>(a, b, c, d, e, f, g)
|||||||> (match t with A -> fn1 | B -> fn2)
</code>```

Would this be a case for an anonymous record? What are the common practices to achieve this?

答:
Both solutions by @Asti work fine. I would go one step further in simplifying the first one. I prefer to name things, so that I can remember what they mean, so I would write:

```<code>let funcToCall = match t with | A -> curried1 | B -> curried2
funcToCall 1 2 3 4
</code>```

However, I think there is a valid point in the comments that you have too many parameters. In this case, it makes much more sense to use a named record:

```<code>type FuncParams = { Doors:int; Windows:int; Walls:int; Chimneys:int; .... }

let arg = { Doors=1; Windows=2; Walls=3; Chimneys=4; ... }
match t with A -> curried1 arg | B -> curried2 arg
</code>```

Body:
Given this expression:

// val fn1 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit
// val fn2 : a:'a -> b:'b -> c:'c -> d:'d -> e:'e -> f:'f -> g:'g -> unit

type T =
  | A
  | B

// val t : T
// val a : 'a
// val b : 'b
// val c : 'c
// val d : 'd
// val e : 'e
// val f : 'f
// val g : 'g

match t with
| A -> fn1 a b c d e f g
| B -> fn2 a b c d e f g

Is there a way to not repeat the same chain of parameters while calling a function that supports currying? so you could write some weird stuff like this

(a, b, c, d, e, f, g)
|||||||> (match t with A -> fn1 | B -> fn2)

Would this be a case for an anonymous record? What are the common practices to achieve this?

Body:
Both solutions by @Asti work fine. I would go one step further in simplifying the first one. I prefer to name things, so that I can remember what they mean, so I would write:

let funcToCall = match t with | A -> curried1 | B -> curried2
funcToCall 1 2 3 4

However, I think there is a valid point in the comments that you have too many parameters. In this case, it makes much more sense to use a named record:

type FuncParams = { Doors:int; Windows:int; Walls:int; Chimneys:int; .... }

let arg = { Doors=1; Windows=2; Walls=3; Chimneys=4; ... }
match t with A -> curried1 arg | B -> curried2 arg


问:
ModuleNotFoundError: No module named 'pandas.io' for json_normalize
Please read carefully. In my Python script I have the following:

```<code>import json
import pandas
from pandas.io.json import json_normalize
</code>```

and it returns the following error:

from pandas.io.json import json_normalize  ModuleNotFoundError: No
  module named 'pandas.io'; 'pandas' is not a package

My steps:

I have uninstalled and installed Pandas

I have upgraded pip and pandas

I have installed io (pip install -U pandas.io)

I have installed data_reader and replaced the pandas.io.json part with that: from pandas_datareader import json_normalize

I have tried every solution I saw on stackoverflow and github and nothing worked. The only one I have not tried is installing Anaconda but it should work with what I tried before. Do you think it is a Windows setting things I must change?

PS: My Python version is 3.7.4

答: i had same problem and i solve it b uninstalling extra python versions install on my windows.now i have only one python installed by anaconda,and everything is working perfectly</p>

Body:
Please read carefully. In my Python script I have the following:

import json
import pandas
from pandas.io.json import json_normalize

and it returns the following error:

from pandas.io.json import json_normalize  ModuleNotFoundError: No
  module named 'pandas.io'; 'pandas' is not a package

My steps:

I have uninstalled and installed Pandas

I have upgraded pip and pandas

I have installed io (pip install -U pandas.io)

I have installed data_reader and replaced the pandas.io.json part with that: from pandas_datareader import json_normalize

I have tried every solution I saw on stackoverflow and github and nothing worked. The only one I have not tried is installing Anaconda but it should work with what I tried before. Do you think it is a Windows setting things I must change?

PS: My Python version is 3.7.4


问:
I want to Create a Crystal Report of Paid Sales Invoices
When a Sales invoice is paid it is matched against the receipt.
A Sales invoice can also be matched against a credit note but there is no distinguishing flag.
I want the final report to only show the Paid invoices.
I am currently Grouping by Customer, then Matching Letter, then document, so at this level you can see if the match is with a receipt or with credit notes.
I output the Group footer of the document giving me a list of documents, which for a customer payment will start with the Receipt, followed by one or more invoices totaling the value of the receipt:

GF4 Customer A  Match BC    REC101009798                    GBP240.00
GF4 Customer A  Match BC    INV101059389        ‘new field’ GBP120.00
GF4 Customer A  Match BC    INV101059390        ‘new field’ GBP120.00

If the matching is as a result of a customer payment, the Receipt will always be on the first line in the group output.

How do I create a ’new field’ on the Invoice lines that will say “Paid” , it doesn’t matter if the new field also appears on the Receipt line?

I have tried to use a formula on the group footer referencing the document type but of course when the document type changes, so does the result of the formula.
Having a success on the first line I have been concentrating on trying to copy the result on to the successive lines so thought a fresh pair of eyes might help.

Many thanks

答: Use Subreport. You can pass inv no or doc type to subreport and get status . Put subreport in invoice line. </p>


问:
Alexa Skill using S3 Select data
I have a JSON object in my S3 bucket and I want to query this JSON data using S3 select, retrieve the needed fields and then concatenate the results into a string and return it back to some other function where Alexa will speak out this string.

My JSON data in the S3 bucket looks like this.

```<code>{
    person = [
    {
            "Id": "valid",
            "Name": "Anshu",
            "Address": "Templestowe",
            "Car": "Jeep"
    },
    {
            "Id": "valid",
            "Name": "Ben Mostafa",
            "Address": "Las Vegas",
            "Car": "Mustang"
    },
    {
                    "Id": "not valid",
                    "Name": "Rohan Wood",
                    "Address": "Wooddon",
                    "Car": "VW"
    },
    {
                    "Id": "not valid",
                    "Name": "John Cena",
                    "Address": "Wooddon",
                    "Car": "VW"
    },
    {
                    "Id": "valid",
                    "Name": "Ray Hope",
                    "Address": "Wooddon",
                    "Car": "VW"
    }
    ]
}

</code>```

Now , I want to be able to query this data from my lambda function using S3 select.

I am using NODE JS for my Alexa skill.

I want names of all those people whose ID is "valid".

While Running the SQL query:

```<code>select s.name from s3object[*].person[*] s where s.name is not missing AND s.id = 'valid'
</code>```

I get that data in the form:

```<code>[
    {
        "name": "Anshu"
    },
    {
        "name": "Ben Mostafa"
    },
    {
        "name": "Ray Hope"
    }
]

</code>```

What I want to know is how do I accept the above result and then make a string as below using my lambda function?

```<code>str = "Anshu .Ben Mostafa. Ray Hope"
</code>```

So, for the above query I want my result to be a string variable str = "Anshu .Ben Mostafa. Ray Hope"

I read about using promises to get back the result form the query here but I am not sure how to proceed further.

link

Also, I read the AWS documentation but I am unable to handle the results. Can you help me with this please?

答:
I assume you can store the result in the variable:</p>

```<code>let result = [
    {
        "name": "Anshu"
    },
    {
        "name": "Ben Mostafa"
    },
    {
        "name": "Ray Hope"
    }
]

const str = result.map(r => r.name).join(". ").concat("."); // "Anshu. Ben Mostafa. Ray Hope."
</code>```

Title: Alexa Skill using S3 Select data

Body:
I have a JSON object in my S3 bucket and I want to query this JSON data using S3 select, retrieve the needed fields and then concatenate the results into a string and return it back to some other function where Alexa will speak out this string.

My JSON data in the S3 bucket looks like this.

{
    person = [
    {
            "Id": "valid",
            "Name": "Anshu",
            "Address": "Templestowe",
            "Car": "Jeep"
    },
    {
            "Id": "valid",
            "Name": "Ben Mostafa",
            "Address": "Las Vegas",
            "Car": "Mustang"
    },
    {
                    "Id": "not valid",
                    "Name": "Rohan Wood",
                    "Address": "Wooddon",
                    "Car": "VW"
    },
    {
                    "Id": "not valid",
                    "Name": "John Cena",
                    "Address": "Wooddon",
                    "Car": "VW"
    },
    {
                    "Id": "valid",
                    "Name": "Ray Hope",
                    "Address": "Wooddon",
                    "Car": "VW"
    }
    ]
}

Now , I want to be able to query this data from my lambda function using S3 select.

I am using NODE JS for my Alexa skill.

I want names of all those people whose ID is "valid".

While Running the SQL query:

select s.name from s3object[*].person[*] s where s.name is not missing AND s.id = 'valid'

I get that data in the form:

[
    {
        "name": "Anshu"
    },
    {
        "name": "Ben Mostafa"
    },
    {
        "name": "Ray Hope"
    }
]

What I want to know is how do I accept the above result and then make a string as below using my lambda function?

str = "Anshu .Ben Mostafa. Ray Hope"

So, for the above query I want my result to be a string variable str = "Anshu .Ben Mostafa. Ray Hope"

I read about using promises to get back the result form the query here but I am not sure how to proceed further.

link

Also, I read the AWS documentation but I am unable to handle the results. Can you help me with this please?

Body:
I assume you can store the result in the variable:

let result = [
    {
        "name": "Anshu"
    },
    {
        "name": "Ben Mostafa"
    },
    {
        "name": "Ray Hope"
    }
]

const str = result.map(r => r.name).join(". ").concat("."); // "Anshu. Ben Mostafa. Ray Hope."


问:
dynamically change document title and back
I am trying dynamically change the document title in my app. It's a simple timer app with countdown, so the idea is during countdown duplicate countdown in a document title (it is working), but I want when countdown is done show back app title in a document title. Now it is showing next timer session (and its ok, I wrote this logic for the timer). But for the title I want after timer is done reset title to the default (appTitle). How I can do it?

```<code>title = 'appTitle';

ngOnInit() {
this.timerService.time$.subscribe((time) => {
  this.titleTimer.setTitle(this.datePipe.transform(time, 'mm:ss'));
});
</code>```

}

答:
You can check if the time is equal to the BREAKING_TIME, and set the original title:

```<code>ngOnInit() {
    this.timerService.time$.subscribe((time) => {
        if (time == BREAKING_TIME)
            this.titleTimer.setTitle(this.title);
        else
            this.titleTimer.setTitle(this.datePipe.transform(time, 'mm:ss'));
    });
}
</code>```

Body:
I am trying dynamically change the document title in my app. It's a simple timer app with countdown, so the idea is during countdown duplicate countdown in a document title (it is working), but I want when countdown is done show back app title in a document title. Now it is showing next timer session (and its ok, I wrote this logic for the timer). But for the title I want after timer is done reset title to the default (appTitle). How I can do it?

title = 'appTitle';

ngOnInit() {
this.timerService.time$.subscribe((time) => {
  this.titleTimer.setTitle(this.datePipe.transform(time, 'mm:ss'));
});

}

Body:
You can check if the time is equal to the BREAKING_TIME, and set the original title:

ngOnInit() {
    this.timerService.time$.subscribe((time) => {
        if (time == BREAKING_TIME)
            this.titleTimer.setTitle(this.title);
        else
            this.titleTimer.setTitle(this.datePipe.transform(time, 'mm:ss'));
    });
}


问:
Memoize functional component using react-redux, reselect and React.memo()
I have built an app on ReactJS 16.8.5 and React-Redux 3.7.2. When the app loads the app mounts, initial store is set and database subscriptions are set up against a Firebase Realtime Database.
The app contains a header, Sidebar and content section.

I have implemented reselect along with React.memo to avoid rerendring when props change, but the Sidebar component is still re-rendering.
Using React profiler API and a areEqual comparison function in React.memo I can see that the Sidebar is being rendered several times although props are equal.

app.js

```<code>//Imports etc...
const jsx = (
  <React.StrictMode>
    <Provider store={store}>
      <AppRouter />
    </Provider>
  </React.StrictMode>
)

let hasRendered = false
const renderApp = () => {
  if (!hasRendered) { //make sure app only renders one time
    ReactDOM.render(jsx, document.getElementById('app'))
    hasRendered = true
  }
}

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // Set initial store and db subscriptions
    renderApp()
  }
})
</code>```

AppRouter.js

```<code>//Imports etc...
const AppRouter = ({}) => {
  //...
  return (
    <React.Fragment>
      //uses Router instead of BrowserRouter to use our own history and not the built in one
      <Router history={history}>
        <div className="myApp">
          <Route path="">
            <Sidebar ...props />
          </Route>
          //More routes here...
        </div>
      </Router>
    </React.Fragment>
  )
}
//...
export default connect(mapStateToProps, mapDispatchToProps)(AppRouter)
</code>```

Sidebar.js

```<code>//Imports etc...
export const Sidebar = (props) => {
  const onRender = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
    if (id !== 'Sidebar') { return }
    console.log('onRender', phase, actualDuration)
  }
  return (
    <Profiler id="Sidebar" onRender={onRender}>
      <React.Fragment>
        {/* Contents of Sidebar */}
      </React.Fragment>
    </Profiler>
}

const getLang = state => (state.usersettings) ? state.usersettings.language : 'en'
const getMediaSize = state => (state.route) ? state.route.mediaSize : 'large'
const getNavigation = state => state.navigation
const getMyLang = createSelector(
  [getLang], (lang) => console.log('Sidebar lang val changed') || lang
)
const getMyMediaSize = createSelector(
  [getMediaSize], (mediaSize) => console.log('Sidebar mediaSize val changed') || mediaSize
)
const getMyNavigation = createSelector(
  [getNavigation], (navigation) => console.log('Sidebar navigation val changed') || navigation
)
const mapStateToPropsMemoized = (state) => {
  return {
    lang: getMyLang(state),
    mediaSize: getMyMediaSize(state),
    navigation: getMyNavigation(state)
  }
}

const areEqual = (prevProps, nextProps) => {
  const areStatesEqual = _.isEqual(prevProps, nextProps)
  console.log('Sidebar areStatesEqual', areStatesEqual)
  return areStatesEqual
}
export default React.memo(connect(mapStateToPropsMemoized, mapDispatchToProps)(Sidebar),areEqual)
</code>```

Initial render looks ok up until Sidebar navigation val changed - after that the component re-renders a whole bunch of times - why!?

Console output - initial render

```<code>onRender Sidebar mount 572
Sidebar mediaSize val changed
Profile Sidebar areEqual true
Sidebar navigation val changed
onRender Sidebar update 153
Sidebar navigation val changed
onRender Sidebar update 142
onRender Sidebar update 103
onRender Sidebar update 49
onRender Sidebar update 5
onRender Sidebar update 2
onRender Sidebar update 12
onRender Sidebar update 3
onRender Sidebar update 2
onRender Sidebar update 58
onRender Sidebar update 2
onRender Sidebar update 4
onRender Sidebar update 5
onRender Sidebar update 4
</code>```

The subsequent render does not affect any part of the store that is mapped to props (location), but component is still re-rendering.

Console output - subsequent render

```<code>Profile Sidebar areEqual true
onRender Sidebar update 76
onRender Sidebar update 4
</code>```

I expect Sidebar to be memoized and only render/re-render a few times during mount/update of store during initial load.

Why is the Sidebar component being rendered so many times?

Kind regards /K

答:
The React.memo is not needed because react-redux connect will return a pure component that will only re render if you change the props passed or after a dispatched action caused any changes in the state.

Your mapStateToPropsMemoized should work (see update) but probalby better to write it this way:

```<code>const mapStateToPropsMemoized = createSelector(
  getMyLang,
  getMyMediaSize,
  getMyNavigation,
  (lang, mediaSize, navigation) => ({
    lang,
    mediaSize,
    navigation,
  })
);
//using react.redux connect will return a pure component and passing that
//  to React.memo should cause an error because connect does not return a
//  functional component.
export default connect(
  mapStateToPropsMemoized,
  mapDispatchToProps
)(Sidebar);
</code>```

UPDATE

Your getState should work.

I cannot reproduce component re rendering with your code. The object returned from mapState is a new object every time but it's direct properties never change because the selectors always return memoized result. See example below

const { useRef, useEffect } = React;
const {
  Provider,
  useDispatch,
  connect,
  useSelector,
} = ReactRedux;
const { createStore } = Redux;
const { createSelector } = Reselect;
const state = { someValue: 2, unrelatedCounter: 0 };
//returning a new state every action someValue
//  never changes, only counter
const reducer = (state) => ({
  ...state,
  unrelatedCounter: state.unrelatedCounter + 1,
});
const store = createStore(
  reducer,
  { ...state },
  window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__()
);
//selectors
const selectSomeValue = (state) => state.someValue;
//selectors only return a new object if someValue changes
const selectA = createSelector(
  [selectSomeValue],
  () => ({ value: 'A' }) //returns new object if some value changes
);
const selectB = createSelector(
  [selectSomeValue],
  () => ({ vale: 'B' }) //returns new object if some value changes
);
const selectC = createSelector(
  [selectSomeValue],
  () => ({ vale: 'C' }) //returns new object if some value changes
);
const Counter = () => {
  const counter = useSelector(
    (state) => state.unrelatedCounter
  );
  return
Counter: {counter}
;
};
const AppComponent = (props) => {
  const dispatch = useDispatch();
  const r = useRef(0);
  //because state.someValue never changes this component
  //  never gets re rendered
  r.current++;
  useEffect(
    //dispatch an action every second, this will create a new
    //  state but state.someValue never changes
    () => {
      setInterval(() => dispatch({ type: 88 }), 1000);
    },
    [dispatch] //dispatch never changes but linting tools don't know that
  );
  return (

Rendered {r.current} times

      <Counter />
      ```{JSON.stringify(props, undefined, 2)}```

  );
};
const mapStateToProps = (state) => {
  return {
    A: selectA(state),
    B: selectB(state),
    C: selectC(state),
  };
};

const App = connect(mapStateToProps)(AppComponent);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>

<div id="root"></div></code>```

Body:
I have built an app on ReactJS 16.8.5 and React-Redux 3.7.2. When the app loads the app mounts, initial store is set and database subscriptions are set up against a Firebase Realtime Database.
The app contains a header, Sidebar and content section.

I have implemented reselect along with React.memo to avoid rerendring when props change, but the Sidebar component is still re-rendering.
Using React profiler API and a areEqual comparison function in React.memo I can see that the Sidebar is being rendered several times although props are equal.

app.js

//Imports etc...
const jsx = (
  <React.StrictMode>
    <Provider store={store}>
      <AppRouter />
    </Provider>
  </React.StrictMode>
)

let hasRendered = false
const renderApp = () => {
  if (!hasRendered) { //make sure app only renders one time
    ReactDOM.render(jsx, document.getElementById('app'))
    hasRendered = true
  }
}

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // Set initial store and db subscriptions
    renderApp()
  }
})

AppRouter.js

//Imports etc...
const AppRouter = ({}) => {
  //...
  return (
    <React.Fragment>
      //uses Router instead of BrowserRouter to use our own history and not the built in one
      <Router history={history}>

          <Route path="">
            <Sidebar ...props />
          </Route>
          //More routes here...

      </Router>
    </React.Fragment>
  )
}
//...
export default connect(mapStateToProps, mapDispatchToProps)(AppRouter)

Sidebar.js

//Imports etc...
export const Sidebar = (props) => {
  const onRender = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
    if (id !== 'Sidebar') { return }
    console.log('onRender', phase, actualDuration)
  }
  return (
    <Profiler id="Sidebar" onRender={onRender}>
      <React.Fragment>
        {/* Contents of Sidebar */}
      </React.Fragment>
    </Profiler>
}

const getLang = state => (state.usersettings) ? state.usersettings.language : 'en'
const getMediaSize = state => (state.route) ? state.route.mediaSize : 'large'
const getNavigation = state => state.navigation
const getMyLang = createSelector(
  [getLang], (lang) => console.log('Sidebar lang val changed') || lang
)
const getMyMediaSize = createSelector(
  [getMediaSize], (mediaSize) => console.log('Sidebar mediaSize val changed') || mediaSize
)
const getMyNavigation = createSelector(
  [getNavigation], (navigation) => console.log('Sidebar navigation val changed') || navigation
)
const mapStateToPropsMemoized = (state) => {
  return {
    lang: getMyLang(state),
    mediaSize: getMyMediaSize(state),
    navigation: getMyNavigation(state)
  }
}

const areEqual = (prevProps, nextProps) => {
  const areStatesEqual = _.isEqual(prevProps, nextProps)
  console.log('Sidebar areStatesEqual', areStatesEqual)
  return areStatesEqual
}
export default React.memo(connect(mapStateToPropsMemoized, mapDispatchToProps)(Sidebar),areEqual)

Initial render looks ok up until Sidebar navigation val changed - after that the component re-renders a whole bunch of times - why!?

Console output - initial render

onRender Sidebar mount 572
Sidebar mediaSize val changed
Profile Sidebar areEqual true
Sidebar navigation val changed
onRender Sidebar update 153
Sidebar navigation val changed
onRender Sidebar update 142
onRender Sidebar update 103
onRender Sidebar update 49
onRender Sidebar update 5
onRender Sidebar update 2
onRender Sidebar update 12
onRender Sidebar update 3
onRender Sidebar update 2
onRender Sidebar update 58
onRender Sidebar update 2
onRender Sidebar update 4
onRender Sidebar update 5
onRender Sidebar update 4

The subsequent render does not affect any part of the store that is mapped to props (location), but component is still re-rendering.

Console output - subsequent render

Profile Sidebar areEqual true
onRender Sidebar update 76
onRender Sidebar update 4

I expect Sidebar to be memoized and only render/re-render a few times during mount/update of store during initial load.

Why is the Sidebar component being rendered so many times?

Kind regards /K

Body:
The React.memo is not needed because react-redux connect will return a pure component that will only re render if you change the props passed or after a dispatched action caused any changes in the state.

Your mapStateToPropsMemoized should work (see update) but probalby better to write it this way:

const mapStateToPropsMemoized = createSelector(
  getMyLang,
  getMyMediaSize,
  getMyNavigation,
  (lang, mediaSize, navigation) => ({
    lang,
    mediaSize,
    navigation,
  })
);
//using react.redux connect will return a pure component and passing that
//  to React.memo should cause an error because connect does not return a
//  functional component.
export default connect(
  mapStateToPropsMemoized,
  mapDispatchToProps
)(Sidebar);

UPDATE

Your getState should work.

I cannot reproduce component re rendering with your code. The object returned from mapState is a new object every time but it's direct properties never change because the selectors always return memoized result. See example below

const { useRef, useEffect } = React;
const {
  Provider,
  useDispatch,
  connect,
  useSelector,
} = ReactRedux;
const { createStore } = Redux;
const { createSelector } = Reselect;
const state = { someValue: 2, unrelatedCounter: 0 };
//returning a new state every action someValue
//  never changes, only counter
const reducer = (state) => ({
  ...state,
  unrelatedCounter: state.unrelatedCounter + 1,
});
const store = createStore(
  reducer,
  { ...state },
  window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__()
);
//selectors
const selectSomeValue = (state) => state.someValue;
//selectors only return a new object if someValue changes
const selectA = createSelector(
  [selectSomeValue],
  () => ({ value: 'A' }) //returns new object if some value changes
);
const selectB = createSelector(
  [selectSomeValue],
  () => ({ vale: 'B' }) //returns new object if some value changes
);
const selectC = createSelector(
  [selectSomeValue],
  () => ({ vale: 'C' }) //returns new object if some value changes
);
const Counter = () => {
  const counter = useSelector(
    (state) => state.unrelatedCounter
  );
  return <h4>Counter: {counter}</h4>;
};
const AppComponent = (props) => {
  const dispatch = useDispatch();
  const r = useRef(0);
  //because state.someValue never changes this component
  //  never gets re rendered
  r.current++;
  useEffect(
    //dispatch an action every second, this will create a new
    //  state but state.someValue never changes
    () => {
      setInterval(() => dispatch({ type: 88 }), 1000);
    },
    [dispatch] //dispatch never changes but linting tools don't know that
  );
  return (
    <div>
      <h1>Rendered {r.current} times</h1>
      <Counter />
      <pre>{JSON.stringify(props, undefined, 2)}</pre>
    </div>
  );
};
const mapStateToProps = (state) => {
  return {
    A: selectA(state),
    B: selectB(state),
    C: selectC(state),
  };
};

const App = connect(mapStateToProps)(AppComponent);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>

<div id="root"></div>


问:
Determine the number of "clumps" in array of integers
A clump in an array is defined as a series of 2 or more adjacent elements of the same value. For example:

```<code>{3, 4, 5, 5, 5, 6, 2, 2}
</code>```

contains 2 clumps comprising 1 clump of 5's and one of 2's. (assume every array has at least 1 element)

I need to write a method to return the number of clumps in a given array:

```<code>public int countClumps(int[] nums) {
    int totalClumps = 0;
    for (int i = 0; i < nums.length; i++) {
        int a = 1;
        while (nums[i] == nums[i+a] && (i+a) < nums.length) {
            a++;
        }
        if (a != 1) {
            totalClumps++;
            i += (a - 1);
        }
        a = 1;
    }
}
</code>```

This is the closest I have gotten to solving.  What would I change so that it works?

答:
There are a few problems in your code:

i+=a. This increases i's value correctly, but then the for-loop increments it too. I'd recommend using a while loop, and incrementing i by a without any conditions (i.e., i+=a even when a is 1).

In the while loop, you need to check that i+a is within the range of the array.

Body:
A clump in an array is defined as a series of 2 or more adjacent elements of the same value. For example:

{3, 4, 5, 5, 5, 6, 2, 2}

contains 2 clumps comprising 1 clump of 5's and one of 2's. (assume every array has at least 1 element)

I need to write a method to return the number of clumps in a given array:

public int countClumps(int[] nums) {
    int totalClumps = 0;
    for (int i = 0; i < nums.length; i++) {
        int a = 1;
        while (nums[i] == nums[i+a] && (i+a) < nums.length) {
            a++;
        }
        if (a != 1) {
            totalClumps++;
            i += (a - 1);
        }
        a = 1;
    }
}

This is the closest I have gotten to solving.  What would I change so that it works?


问:
Does corda's notary save transaction inputstate or outputState specific information?
Does Notary only save output_index and transaction_id?
Will Notary keep detailed State information?</p>

答: No, it just stores a map of consumed states (identified by the transaction Id and output index like you mentioned).</p>


问:
Align navbar toggle button to the right
I'm having a play around with Bootstrap 4, more specifically the navbar menu. Is there is a way I can make the little navbar toggle button align to the right of the page rather than have it floating to the left next to the logo?

This is my current code.

@media (min-width: 992px) {
    .navbar-nav li a { line-height: 85px; }
}

@media (max-width: 991px) {
    .navbar-brand { float: none; }
}

.navbar-toggler{
    border:none;
    width:1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <nav class="navbar navbar-light bg-faded navbar-full">
          <img class="img-fluid" src="img/logoMedium.png" />
          <button class="navbar-toggler hidden-lg-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
          <div class="collapse navbar-toggleable-md" id="navbarResponsive">
              <ul class="nav navbar-nav">
                  <li class="nav-item active">
                      Home <span class="sr-only">(current)</span>
                  </li>
                  <li class="nav-item">
                      About Us
                  </li>
                  <li class="nav-item">
                      Solar Power
                  </li>
                  <li class="nav-item">
                      No Obligation Quote
                  </li>
                  <li class="nav-item">
                      Contact Us
                  </li>
              </ul>
          </div>
      </nav></code>```

Thanks for the help :)

答:
You have to align it just like another button tag, first wrap it inside a container to be able to move it later, after that create a div with .text-right class and then put your toggle button inside. See the example below.

```<code><div class='container'>
   <div class='text-right'>
      <button> Button1 </button>
   </div>
</div>
</code>```

or

```<code><div class='container text-right'>
   <button> Button1 </button>
</div>enter code here
</code>```

Both solutions work perfectly in Bootstrap 4.5

Title: Align navbar toggle button to the right

Body:
I'm having a play around with Bootstrap 4, more specifically the navbar menu. Is there is a way I can make the little navbar toggle button align to the right of the page rather than have it floating to the left next to the logo?

This is my current code.

@media (min-width: 992px) {
    .navbar-nav li a { line-height: 85px; }
}

@media (max-width: 991px) {
    .navbar-brand { float: none; }
}

.navbar-toggler{
    border:none;
    width:1em;
}

          <button class="navbar-toggler hidden-lg-up" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>

                      Home (current)

                      About Us

                      Solar Power

                      No Obligation Quote

                      Contact Us

Thanks for the help :)

Body:
You have to align it just like another button tag, first wrap it inside a container to be able to move it later, after that create a div with .text-right class and then put your toggle button inside. See the example below.

<div class='container'>
   <div class='text-right'>
      <button> Button1 </button>
   </div>
</div>

or

<div class='container text-right'>
   <button> Button1 </button>
</div>enter code here

Both solutions work perfectly in Bootstrap 4.5


问:
How to convert the file with multiple delimiter to dataframe
I have a text file as below

```<code>1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf
</code>```

I am expecting the output as

```<code>| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |
</code>```

I have created a custom schema

```<code> val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )
</code>```

I am trying to create a dataframe as

```<code>val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()
</code>```

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

```<code>String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");
</code>```

答:
Picking up from where you left.
You can skip the schema definition and mention only the column names. Rest of the explanation is inline with the code</p>

```<code>import org.apache.spark.sql.DataFrame

object ParseFileNameToInfo {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    val df : DataFrame = spark.read
      .format("csv")
      .option("delimiter", "_")
      .load("src/main/resources/sampleFileNames.txt")
      //You dont need schema definition as it alwyas simple and all columns are string
        .toDF("catg","sub_catg","doc_name","extraColumn")

    import spark.implicits._

    val output : DataFrame = df.rdd
      //Map the 4 columns to our output columns
      .map( row => {
      val extraColumn = row.getString(3)
      val fileInfo = extraColumn.substring(extraColumn.indexOf("-")+1).split("\\.")
      (row.getString(0),row.getString(1),row.getString(2).concat(row.getString(3)),fileInfo(0),fileInfo(1))
    })
      //Convert them to required output Dataframe
      .toDF("catg","sub_catg","doc_name","revision_label","extension")

    output.show()

  }

}

</code>```

Body:
I have a text file as below

1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf

I am expecting the output as

| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |

I have created a custom schema

 val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )

I am trying to create a dataframe as

val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");

Body:
Picking up from where you left.
You can skip the schema definition and mention only the column names. Rest of the explanation is inline with the code

import org.apache.spark.sql.DataFrame

object ParseFileNameToInfo {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    val df : DataFrame = spark.read
      .format("csv")
      .option("delimiter", "_")
      .load("src/main/resources/sampleFileNames.txt")
      //You dont need schema definition as it alwyas simple and all columns are string
        .toDF("catg","sub_catg","doc_name","extraColumn")

    import spark.implicits._

    val output : DataFrame = df.rdd
      //Map the 4 columns to our output columns
      .map( row => {
      val extraColumn = row.getString(3)
      val fileInfo = extraColumn.substring(extraColumn.indexOf("-")+1).split("\\.")
      (row.getString(0),row.getString(1),row.getString(2).concat(row.getString(3)),fileInfo(0),fileInfo(1))
    })
      //Convert them to required output Dataframe
      .toDF("catg","sub_catg","doc_name","revision_label","extension")

    output.show()

  }

}


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
As others have pointed out, as long as there's not an actual bug in the memory manager, classes that don't use unmanaged resources won't leak memory.

What you see in .NET is not memory leaks, but objects that never get disposed.  An object won't get disposed as long as the garbage collector can find it on the object graph.  So if any living object anywhere has a reference to the object, it won't get disposed.

Event registration is a good way to make this happen.  If an object registers for an event, whatever it registered with has a reference to it, and even if you eliminate every other reference to the object, until it unregisters (or the object it registered with becomes unreachable) it will stay alive.

So you have to watch out for objects that register for static events without your knowledge.  A nifty feature of the ToolStrip, for instance, is that if you change your display theme, it will automatically redisplay in the new theme.  It accomplishes this nifty feature by registering for the static SystemEvents.UserPreferenceChanged event.  When you change your Windows theme, the event gets raised, and all of the ToolStrip objects that are listening to the event get notified that there's a new theme.

Okay, so suppose you decide to throw away a ToolStrip on your form:

```<code>private void DiscardMyToolstrip()
{
    Controls.Remove("MyToolStrip");
}
</code>```

You now have a ToolStrip that will never die.  Even though it isn't on your form anymore, every time the user changes themes Windows will dutifully tell the otherwise-nonexistent ToolStrip about it.  Every time the garbage collector runs, it thinks "I can't throw that object away, the UserPreferenceChanged event is using it."

That's not a memory leak.  But it might as well be.

Things like this make a memory profiler invaluable.  Run a memory profiler, and you'll say "that's odd, there seem to be ten thousand ToolStrip objects on the heap, even though there's only one on my form.  How did this happen?"

Oh, and in case you're wondering why some people think property setters are evil:  to get a ToolStrip to unregister from the UserPreferenceChanged event, set its Visible property to false.

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

Body:
As others have pointed out, as long as there's not an actual bug in the memory manager, classes that don't use unmanaged resources won't leak memory.

What you see in .NET is not memory leaks, but objects that never get disposed.  An object won't get disposed as long as the garbage collector can find it on the object graph.  So if any living object anywhere has a reference to the object, it won't get disposed.

Event registration is a good way to make this happen.  If an object registers for an event, whatever it registered with has a reference to it, and even if you eliminate every other reference to the object, until it unregisters (or the object it registered with becomes unreachable) it will stay alive.

So you have to watch out for objects that register for static events without your knowledge.  A nifty feature of the ToolStrip, for instance, is that if you change your display theme, it will automatically redisplay in the new theme.  It accomplishes this nifty feature by registering for the static SystemEvents.UserPreferenceChanged event.  When you change your Windows theme, the event gets raised, and all of the ToolStrip objects that are listening to the event get notified that there's a new theme.

Okay, so suppose you decide to throw away a ToolStrip on your form:

private void DiscardMyToolstrip()
{
    Controls.Remove("MyToolStrip");
}

You now have a ToolStrip that will never die.  Even though it isn't on your form anymore, every time the user changes themes Windows will dutifully tell the otherwise-nonexistent ToolStrip about it.  Every time the garbage collector runs, it thinks "I can't throw that object away, the UserPreferenceChanged event is using it."

That's not a memory leak.  But it might as well be.

Things like this make a memory profiler invaluable.  Run a memory profiler, and you'll say "that's odd, there seem to be ten thousand ToolStrip objects on the heap, even though there's only one on my form.  How did this happen?"

Oh, and in case you're wondering why some people think property setters are evil:  to get a ToolStrip to unregister from the UserPreferenceChanged event, set its Visible property to false.

OwnerDisplayName: Robert Rossney


问:
Using class in another class easily with an example
I have a php class that tells time like this (Time.class.php):

```<code><?PHP
class Time {
    var $timestamp;
    function timestamp () {
    $this->timestamp = date('YmdHis');
    return $this->timestamp;
    }
}
?>
</code>```

What I want to do is to call this time in a different class such as (Test.class.php):

```<code><?PHP
class Test {
    function test (){
    $timestamp = ' '; // <--- the timestamp from the other class
    $hourago = $timestamp - 10000;
    return $hourago;
    }
}
?>
</code>```

I'm new to PHP classes so I didn't understand what I've read on this subject. From what I've read this can be done with global scope (if its called a scope)?? If you could only show me how to use globals or how to solve a problem like this easily I would appreciate it...

答:
You must use DEPENDENCI INJECTION.

You can pass any references objects in the costructor like this:

```<code>   function test ($yourTimeStamp){
       $timestamp = $yourTimeStamp
       [...]
   }
</code>```

Body:
I have a php class that tells time like this (Time.class.php):

<?PHP
class Time {
    var $timestamp;
    function timestamp () {
    $this->timestamp = date('YmdHis');
    return $this->timestamp;
    }
}
?>

What I want to do is to call this time in a different class such as (Test.class.php):

<?PHP
class Test {
    function test (){
    $timestamp = ' '; // <--- the timestamp from the other class
    $hourago = $timestamp - 10000;
    return $hourago;
    }
}
?>

I'm new to PHP classes so I didn't understand what I've read on this subject. From what I've read this can be done with global scope (if its called a scope)?? If you could only show me how to use globals or how to solve a problem like this easily I would appreciate it...

Body:
You must use DEPENDENCI INJECTION.

You can pass any references objects in the costructor like this:

   function test ($yourTimeStamp){
       $timestamp = $yourTimeStamp
       [...]
   }


问:
How to paste python-code chunk to HTML page
Let say I have below python code placed in one of my IDE

```<code>import math
import pandas as pd
import numpy as np
.....
some other python code
</code>```

Now, I have a web-page with HTML, CSS etc, and I want to place above code-chunk in that web-page. Manually, I was just copy-paste above code and then manually apply appropriate styling using CSS. For big code-chunk, it is really cumbersome. Moreover, with that approach, few important stuffs like indentation would get garbled, so when site-viewer would copy-paste that code-chunk from my web-page in his python-workplace, it might not work properly.

I am looking for suggestion if there is any easier way to achieve the same, i.e. I can just take the code-chunk from my IDE and place within appropriate div of page's source code.

Any pointer will be highly appreciated.

答:
you can paste your code in the <code>```<code></code> tags , you can always play out with the CSS</p>

```<code>```
<code style="display:block; white-space:pre-wrap;background: hsl(220, 80%, 90%); ">

 <!--- paste your code from IDE here ---->
</code>
```
</code>```

Body:
Let say I have below python code placed in one of my IDE

import math
import pandas as pd
import numpy as np
.....
some other python code

Now, I have a web-page with HTML, CSS etc, and I want to place above code-chunk in that web-page. Manually, I was just copy-paste above code and then manually apply appropriate styling using CSS. For big code-chunk, it is really cumbersome. Moreover, with that approach, few important stuffs like indentation would get garbled, so when site-viewer would copy-paste that code-chunk from my web-page in his python-workplace, it might not work properly.

I am looking for suggestion if there is any easier way to achieve the same, i.e. I can just take the code-chunk from my IDE and place within appropriate div of page's source code.

Any pointer will be highly appreciated.

Body:
you can paste your code in the <pre><code> tags , you can always play out with the CSS

<pre>
<code style="display:block; white-space:pre-wrap;background: hsl(220, 80%, 90%); ">

 <!--- paste your code from IDE here ---->
</code>
</pre>


问:
How can I save data when closing in Java
I make somekind video player. I want to save minut of users watching to database when closing the program. How can I do that? How can I write operations on exiting?</p>

答:
The way to do this is using method Runtime.getRuntime().addShutdownHook(Thread hook). It will register a new virtual-machine shutdown hook where you can save data. When the JVM shuts down, the hook will be called and your code will be executed.

Here's a simple demo

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}));
```


答:
```<code>if np.where(~a.any(axis=1))[0]:
    #do nothing
else:
    #print as you like
</code>```

Title: Stacked numpy arrays

Body:
I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose  has been shown below:

def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)

The desired output is of the form :

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

But I get :

[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.


问:
Is it a bad practice to catch the Throwable?
Is it a bad practice to catch Throwable?For example my code  something like this.But in sonar its showing as bug .How can we resolve this

code

```<code>try {
            return restTemplate.getForObject(urlSearchID, AccessIDSearchResponse.class);

        } catch (HttpServerErrorException hse) {
            AccesIdExceptionUtility.recoverFromHttpServerExc(hse);
        } catch (HttpClientErrorException hce) {
            AccesIdExceptionUtility.recoverFromHttpClientExc(hce);
        } catch (ClientException ce) {
            AccesIdExceptionUtility.recoverFromClientExc(ce);
        } catch (Exception e) {
            AccesIdExceptionUtility.recoverFromException(e);
        }
        catch (Throwable ex) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, ex.getMessage(), agentSearchUrl);
        }
        return null;
</code>```

答:
Yes it's a bad practise. In Java Throwable is a base class for Error and Exception.
You are already familiar with Exceptions, they can be checked or unchecked, so you can catch them and handle, log or rethrow.

Errors are more complicated, they are JVM eroror like OutOfMemoryException which is a VirtualMachineError. How are you gonna handle this in your code? Answer is: you simply can't.

If you google for "Recoverable and Irrecoverable Situations" Exceptions are Recoverable Situations, because you can handle NullPointerException and Irrecoverable Situations are Errors.

If you want check Baeldung, it's really good blog about Java, Spring etc.
https://www.baeldung.com/java-catch-throwable-bad-practice

Body:
Is it a bad practice to catch Throwable?For example my code  something like this.But in sonar its showing as bug .How can we resolve this

code

try {
            return restTemplate.getForObject(urlSearchID, AccessIDSearchResponse.class);

        } catch (HttpServerErrorException hse) {
            AccesIdExceptionUtility.recoverFromHttpServerExc(hse);
        } catch (HttpClientErrorException hce) {
            AccesIdExceptionUtility.recoverFromHttpClientExc(hce);
        } catch (ClientException ce) {
            AccesIdExceptionUtility.recoverFromClientExc(ce);
        } catch (Exception e) {
            AccesIdExceptionUtility.recoverFromException(e);
        }
        catch (Throwable ex) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, ex.getMessage(), agentSearchUrl);
        }
        return null;


问:
How to move directories using jdk7
Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's say Foo

```<code>Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

After executing that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.

Am I doing this wrong?

NOTE

I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.

EDIT

In addition to the accepted answer, here's another solution

```<code>Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
    source,
    target.resolve(source.getFileName()),
    StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答: In the javadoc for the Files.move method you will find an example where it moves a file into a directory, keeping the same file name. This seems to be what you were looking for.</p>

Title: How to move directories using jdk7

Body:
Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's say Foo

Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

After executing that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.

Am I doing this wrong?

NOTE

I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.

EDIT

In addition to the accepted answer, here's another solution

Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
    source,
    target.resolve(source.getFileName()),
    StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}


问:
Google Sheets - Autoreplace a value when a new row is created
I use Zapier to create a new row in a Google Sheet doc for each new registration on our website. However, I want to autoreplace a value of a cell when the row is created or, if it's not possible, using a script with onOpen, or any time-based trigger.

Here is an example of the data that needs to be changed in two specific columns (say, A and C)...

```<code>/*Job - Column A - English to French*/
 'Management':'Gestion',
 'Social work':'Travail social',
 'Reception':'Accueil',
 'Art Therapy':'Art-thérapie',
 'Volunteer work':'Bénévole',

/*Workplace - Column C - English to French*/
'Starting Community':'Communauté en démarrage',
'CLAN Program' : 'Programme FER',
'Other (specify)' : 'Autre affiliation',
'University (specify)' : 'Université',

</code>```

How can I do that? I managed to use an onEdit trigger, but since it can't be activated by Zapier, it's useless.

Thanks!

答:
You cannot achieve this behavior with an Edit trigger in Apps Script.

Zapier will edit the Spreadsheet via API call and this is actually one of the trigger limitations:

Script executions and API requests do not cause triggers to run. For example, calling Range.setValue() to edit a cell does not cause the spreadsheet's onEdit trigger to run.

You should probably craft this auto-replace feature in the Zapier environment directly.

Refer to this documentation for additional Apps Script triggers limitations.

Body:
I use Zapier to create a new row in a Google Sheet doc for each new registration on our website. However, I want to autoreplace a value of a cell when the row is created or, if it's not possible, using a script with onOpen, or any time-based trigger.

Here is an example of the data that needs to be changed in two specific columns (say, A and C)...

/*Job - Column A - English to French*/
 'Management':'Gestion',
 'Social work':'Travail social',
 'Reception':'Accueil',
 'Art Therapy':'Art-thérapie',
 'Volunteer work':'Bénévole',

/*Workplace - Column C - English to French*/
'Starting Community':'Communauté en démarrage',
'CLAN Program' : 'Programme FER',
'Other (specify)' : 'Autre affiliation',
'University (specify)' : 'Université',

How can I do that? I managed to use an onEdit trigger, but since it can't be activated by Zapier, it's useless.

Thanks!


问:
How do I specify local .gem files in my Gemfile?
I have a couple of gem files which I install via gem install xx.gem.  Can I tell Bundler to use them?  Or do I have to specify the source path?

答:
You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

```<code>bundle install
</code>```

(Installs required gems and makes Gemfile.lock)

```<code>bundle package
</code>```

(Caches the gems in vendor/cache)

On the server:

```<code>bundle install --local
</code>```

(--local means "use the gems from vendor/cache")

Body:
You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

bundle install

(Installs required gems and makes Gemfile.lock)

bundle package

(Caches the gems in vendor/cache)

On the server:

bundle install --local

(--local means "use the gems from vendor/cache")


问:
Eliding of text when multiple lines in qml
I have a text which is displayed in multiple lines and I need elide to happen for a line when the width of the text is exceeded.
Please find the code below that I have now.

Code:

```<code>Text {
    width: 500
    maximumLineCount: 3
    horizontalAlignment: "AlignHCenter"
    wrapMode: Text.WordWrap//"WordWrap"
    elide:Text.ElideRight
</code>```

text:"Firstline\nstart_kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk_end"
        color: "red"
      }

Now for me on line 1: "First line" appears and on 2nd line the remaining text appears without any eliding effect(i.e complete text is shown).
It appears the following way:
                           "Firstline
start_kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk_end"
I want eliding to happen at 2nd line as it exceeds the width.

Thanks in advance

答:
According to documentation:

If this property is set to Text.ElideRight, it can be used with
  wrapped text. The text will only elide if maximumLineCount, or height
  has been set. If both maximumLineCount and height are set,
  maximumLineCount will apply unless the lines do not fit in the height
  allowed.

So the text will elide either if you add second line before, like:

```<code>text: "First line \nSecond line \nkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
</code>```

or

if maximumLineCount will be set to 2 lines:

```<code>maximumLineCount: 2
</code>```

Body:
I have a text which is displayed in multiple lines and I need elide to happen for a line when the width of the text is exceeded.
Please find the code below that I have now.

Code:

Text {
    width: 500
    maximumLineCount: 3
    horizontalAlignment: "AlignHCenter"
    wrapMode: Text.WordWrap//"WordWrap"
    elide:Text.ElideRight

text:"Firstline\nstart_kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk_end"
        color: "red"
      }

Now for me on line 1: "First line" appears and on 2nd line the remaining text appears without any eliding effect(i.e complete text is shown).
It appears the following way:
                           "Firstline
start_kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk_end"
I want eliding to happen at 2nd line as it exceeds the width.

Thanks in advance

Body:
According to documentation:

If this property is set to Text.ElideRight, it can be used with
  wrapped text. The text will only elide if maximumLineCount, or height
  has been set. If both maximumLineCount and height are set,
  maximumLineCount will apply unless the lines do not fit in the height
  allowed.

So the text will elide either if you add second line before, like:

text: "First line \nSecond line \nkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"

or

if maximumLineCount will be set to 2 lines:

maximumLineCount: 2


问:
Vote only once in Django to posts and comments
I have two models called Post and Comment and a User that can upvote or downvote that post or comment. I want to restrict each user however to be able to to vote only once to a certain Post or Comment.

I could do something on the model level to Post and Comment and instead tally up total votes for the specific post or comment. However, I think it's a bit more scalable to create a separate Vote model where:

total votes can be tallied with one query (SELECT count(*) FROM votes where user_id=, etc...)

voting once per user can be enforced with unique_together

Currently I have figured out something like this:

```<code>import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models

# Create your models here.

class Post(models.Model):
    LINK = "link"
    VIDEO = "video"
    IMAGE = "image"
    POST_TYPE_CHOICES = ((LINK, "Link"), (VIDEO, "Video"), (IMAGE, "Image"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=300)
    url = models.URLField(max_length=300)
    category = models.CharField(max_length=50)
    score = models.DecimalField(default=0, max_digits=20, decimal_places=2)
    votes = models.IntegerField(default=0)
    views = models.IntegerField(default=0)
    post_type = models.CharField(max_length=5, choices=POST_TYPE_CHOICES, default=LINK)
    text = models.CharField(max_length=40000)
    owner = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-created"]

class PostVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='post_votes', on_delete=models.CASCADE)

class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=10000)
    post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
    owner = models.ForeignKey('users.User', related_name='comments', on_delete=models.CASCADE)

    class Meta:
        ordering = ["-created"]

class CommentVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='comment_votes', on_delete=models.CASCADE)

    def __str__(self):
        return self.score

    class Meta:
        ordering = ["-created"]
</code>```

I just know this is a bad model of separating the votes to PostVote and CommentVote and instead would want a more generic Vote model where I could specify the vote to be towards a Post or a Comment.

What I don't want is having a Vote model that has both the post_id and comment_id which would make it so that either one is always null, since one vote is always either for a Comment or a Post.

Any help?

答: This can be solved better by using Generic Relations. This https://simpleisbetterthancomplex.com/tutorial/2016/10/13/how-to-use-generic-relations.html is a great article to understand the concept and the example here is something similar to your requirement.

Body:
I have two models called Post and Comment and a User that can upvote or downvote that post or comment. I want to restrict each user however to be able to to vote only once to a certain Post or Comment.

I could do something on the model level to Post and Comment and instead tally up total votes for the specific post or comment. However, I think it's a bit more scalable to create a separate Vote model where:

total votes can be tallied with one query (SELECT count(*) FROM votes where user_id=, etc...)

voting once per user can be enforced with unique_together

Currently I have figured out something like this:

import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models

# Create your models here.

class Post(models.Model):
    LINK = "link"
    VIDEO = "video"
    IMAGE = "image"
    POST_TYPE_CHOICES = ((LINK, "Link"), (VIDEO, "Video"), (IMAGE, "Image"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=300)
    url = models.URLField(max_length=300)
    category = models.CharField(max_length=50)
    score = models.DecimalField(default=0, max_digits=20, decimal_places=2)
    votes = models.IntegerField(default=0)
    views = models.IntegerField(default=0)
    post_type = models.CharField(max_length=5, choices=POST_TYPE_CHOICES, default=LINK)
    text = models.CharField(max_length=40000)
    owner = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-created"]

class PostVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='post_votes', on_delete=models.CASCADE)

class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=10000)
    post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
    owner = models.ForeignKey('users.User', related_name='comments', on_delete=models.CASCADE)

    class Meta:
        ordering = ["-created"]

class CommentVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='comment_votes', on_delete=models.CASCADE)

    def __str__(self):
        return self.score

    class Meta:
        ordering = ["-created"]

I just know this is a bad model of separating the votes to PostVote and CommentVote and instead would want a more generic Vote model where I could specify the vote to be towards a Post or a Comment.

What I don't want is having a Vote model that has both the post_id and comment_id which would make it so that either one is always null, since one vote is always either for a Comment or a Post.

Any help?