问:
Collection of two objects and I want to store value of zero index and first index in two different variables Laravel 8
I have a collection of items of two objects. I want to store the zero index's date in a variable such as $starttime, and I want to store the first index's date in the variable such as $endtime. How can I do that?

```<code>#items: array:2 [▼
    0 => {#820 ▼
      +"id": 75
      +"code": ""8080"
      +"name": "Ahmed"
      +"date": "2021-12-01 08:57:40"
      +"created_at": "2022-02-09 11:45:30"
      +"updated_at": "2022-02-09 11:45:30"
    }
    1 => {#822 ▼
      +"id": 76
      +"code": ""8080"
      +"name": "Ahmed"
      +"date": "2021-12-01 18:14:13"
      +"created_at": "2022-02-09 11:45:30"
      +"updated_at": "2022-02-09 11:45:30"
    }
  ]
  #escapeWhenCastingToString: false
</code>```

Controller:

```<code>$data = DB::table('data')->orderBy('date', 'asc')->get();
foreach ($data as $datas) {
    $dates = date('y-m-d', strtotime($datas->date));
    $date = DB::table('data')->where('date', 'LIKE', '%'.$dates.'%')->get();
    $finddate = DB::table('data')->where('date', 'LIKE', '%'.$dates.'%')->where('code', $datas->code)->get();
    foreach ($finddate as $datefound) {
        $starttime = $datefound->date;
        $endtime = $datefound->date;
        dd($endtime);
    }
}
</code>```

I am trying to do this, but it only shows the first date, such as the following.

```<code>2021-12-01 08:57:40
</code>```

答:
You might want to add an expected result because your question is quite confusing.
If you want to store the first two rows of the result of the query into a variable, you can try this:</p>
```<code>$data =  DB::table('data')->orderBy('date')->get();
if (sizeof($data) >= 2) { // Making sure result has atleast 2 rows
    $starttime = $data[0];
    $endtime= $data[1];
}
</code>```

Body:
I have a collection of items of two objects. I want to store the zero index's date in a variable such as $starttime, and I want to store the first index's date in the variable such as $endtime. How can I do that?

#items: array:2 [▼
    0 => {#820 ▼
      +"id": 75
      +"code": ""8080"
      +"name": "Ahmed"
      +"date": "2021-12-01 08:57:40"
      +"created_at": "2022-02-09 11:45:30"
      +"updated_at": "2022-02-09 11:45:30"
    }
    1 => {#822 ▼
      +"id": 76
      +"code": ""8080"
      +"name": "Ahmed"
      +"date": "2021-12-01 18:14:13"
      +"created_at": "2022-02-09 11:45:30"
      +"updated_at": "2022-02-09 11:45:30"
    }
  ]
  #escapeWhenCastingToString: false

Controller:

$data = DB::table('data')->orderBy('date', 'asc')->get();
foreach ($data as $datas) {
    $dates = date('y-m-d', strtotime($datas->date));
    $date = DB::table('data')->where('date', 'LIKE', '%'.$dates.'%')->get();
    $finddate = DB::table('data')->where('date', 'LIKE', '%'.$dates.'%')->where('code', $datas->code)->get();
    foreach ($finddate as $datefound) {
        $starttime = $datefound->date;
        $endtime = $datefound->date;
        dd($endtime);
    }
}

I am trying to do this, but it only shows the first date, such as the following.

2021-12-01 08:57:40

Body:
You might want to add an expected result because your question is quite confusing.
If you want to store the first two rows of the result of the query into a variable, you can try this:

$data =  DB::table('data')->orderBy('date')->get();
if (sizeof($data) >= 2) { // Making sure result has atleast 2 rows
    $starttime = $data[0];
    $endtime= $data[1];
}


来源: stackexchange

问:
paypal refund order API return Authorization failed due to insufficient permissions
Currently i am redirecting order amount to merchant account that is working fine

but now when i perform refund operation getting persmission error

steps i followed :

gettting access token of merchant from his/her refresh token(stored in database) (using https://api-m.sandbox.paypal.com/v1/identity/openidconnect/tokenservice API)

now using above token(from step 1) for refund process in below API
https://api.sandbox.paypal.com/v2/payments/captures/{captureId}/refund where

captureId : got from order details

response of refund api :

```<code>{
    "name": "NOT_AUTHORIZED",
    "message": "Authorization failed due to insufficient permissions.",
    "debug_id": "60091a8e09195",
    "details": [
        {
            "issue": "PERMISSION_DENIED",
            "field": "capture_id",
            "value": "90Y75959CH863854A",
            "description": "You do not have permission to access or perform operations on this resource.",
            "location": "path"
        }
    ],
    "links": [
        {
            "href": "https://developer.paypal.com/docs/api/payments/v2/#error-PERMISSION_DENIED",
            "rel": "information_link"}
    ]}
</code>```

can someone help me to find what mistake am i doing ? and how can i resolve this issue ?

答:
To determine which scopes you should try asking for during authorization, do a normal access_token request using your own credentials and look at the scopes variable returned.

https://uri.paypal.com/services/payments/refund seems relevant.

ContentLicense: CC BY-SA 4.0

Body:
Currently i am redirecting order amount to merchant account that is working fine

but now when i perform refund operation getting persmission error

steps i followed :

gettting access token of merchant from his/her refresh token(stored in database) (using https://api-m.sandbox.paypal.com/v1/identity/openidconnect/tokenservice API)

now using above token(from step 1) for refund process in below API
https://api.sandbox.paypal.com/v2/payments/captures/{captureId}/refund where

captureId : got from order details

response of refund api :

{
    "name": "NOT_AUTHORIZED",
    "message": "Authorization failed due to insufficient permissions.",
    "debug_id": "60091a8e09195",
    "details": [
        {
            "issue": "PERMISSION_DENIED",
            "field": "capture_id",
            "value": "90Y75959CH863854A",
            "description": "You do not have permission to access or perform operations on this resource.",
            "location": "path"
        }
    ],
    "links": [
        {
            "href": "https://developer.paypal.com/docs/api/payments/v2/#error-PERMISSION_DENIED",
            "rel": "information_link"}
    ]}

can someone help me to find what mistake am i doing ? and how can i resolve this issue ?


问:
Qt SDK on Windows: how to use Assistant
After installing Qt SDK on Windows, I don't see any Help item in the Qt SDK menu. QtCreator\bin directory contains assistant.exe, and Documentation directory contains *.qch files. Is it possible to create a shortcut showing Qt Assistant with Qt SDK reference?</p>

答:
You can add these .qch files by going to the menu Edit > Preferences > Documentation > Add...

You should only need to do that once.

ContentLicense: CC BY-SA 3.0

Title: Qt SDK on Windows: how to use Assistant


问:
Cloud Run reports that a request is aborted with no available instance but seems to be automatically retried and successful
We have an endpoint hosted in Cloud Run which receives requests to print a receipt for the customer with no retry mechanism.

Earlier today, there was a single request to print a specific receipt which was met with the No available instance error and reported that the request was aborted. This is fine for us but the problem is that the request was replayed multiple times all with the same error response which is unexpected.

The kicker is that these request although reported as aborted were actually successful as we have the data written in our print queue and the printers ended up printing 100+ duplicates of the same thing.

Is there a way to prevent/fix this without having to do a central lock throttle?

Below is what we can see in our logs:

答:
It appears that your application made requests over and over again without implementing exponential backoff. I counted 20 requests with the same second timestamp.

Hammering a service with requests that is saying wait is not a good strategy.

I would implement a smarter strategy for errors. Since the HTTP error is 500 which means Cloud Run couldn't manage the rate of traffic, I would have delayed making any requests for 60 seconds and then retrying once and then again with a longer delay. If that fails, stop making requests and send a notification message (text, email, etc) so that a human can look into the problem.

Note: there is most likely an underlying problem or two. There might be a resource availability issue for the region. Your containers might be taking too long on startup. Review earlier logs to analyze what was happening when the errors started. Sometimes these errors are temporary, self-healing problems. The logs should help you determine that.

Implement different strategies based upon the error condition.

Exponential backoff

Troubleshoot Cloud Run issues

Also consider opening a Google Cloud support (paid) support ticket. Share the information that you collected with Google support. You might have a deployment that the team can learn from. If this is a Google problem, request a credit.


问:
Zookeeper API change from 3.4.6 to 3.5.5
I am working on Zookeeper upgrade from 3.4.6 to 3.5.5.
Since org.apache.zookeeper.data package is removed from 3.5.5 I am looking for alternative API.

mvn compilation is failing for below two classes

org.apache.zookeeper.data.ACL and org.apache.zookeeper.data.Stat

Thanks in advance!!

答:
Go into 'zookeeper-jute' project and run "maven generate-sources".
Assuming: Your on eclipse and opened project from parent folder.</p>


问:
How to make existing angular application "fully strict" step by step?
I have an existing Angular Application that started development at the time of Angular 4, now it's on Angular 12. But at the time of development, the strict mode was not enabled. Now after the application is stable and also deployed on production, what's the best way to enable strict mode stey by step i.e. in phases instead of turning every strict option on.

I have already read the answer here Angular 10 Stricter Settings --strict , which is for generally enabling strict mode.

My question is related to how to enable it in phases. As the application size/complexity is medium level, therefore it will be a major challenge to test all of the changes at once.
There are a few options I see in angular strict config such as, some of them can be configured manually as well some are turn on by strict:true:

noImplicitAny

strictInjectionParameters

strictTemplates

strictNullChecks

Enabling in tslint.json "no-any": true

What's the best way to enable these settings, step by step, in a specific order which is better? So that it can be tested and deployed to production in phases instead of one whole chunk which has changes of bug/issue going unnoticed. Any help would be appreciated especially by someone who has gone through updating an already existing project, in a bits by bits manner instead of one whole push.

答:
One good approach:

Begin by typing all your models - interfaces/types/classes - as this should be the source of truth for types. While doing this, avoid (where possible) to use the any type.

Type your functions - Although most times, the language service/compiler may infer what types come in and out of the function, adding types will ensure your compiler tells you when you're not using your functions correctly

Use Generics to your advantage - Angular has many functions that accept generic types that you can leverage to ensure you're getting the expected type. One good example is the HttpClient's functions: get, put, post, delete. Say, you're expecting a number type from an api call, then you'd add they type to the function invocation: this.http.get<number>(someAPIUrl). Most of the libraries have good documentation on their typings.

You can start turning on the tsconfig flags such as noImplicitAny - this will help narrow down the places where you need to add more typing that you may have overlooked. At this point, you can even turn on strict mode as well.

Turn on template type checking - The Angular docs are super helpful for this - I can't tell you enough how easy it is to click on an object's property in the template and it takes me straight to the class/interface/type definition.

Of course, it may take some time before you get to where you want and expect some things to break before you fix them. So working through it bit by bit my help.

Just to note, there's more work that the Angular Team is doing to improve typing such as Typed Forms.


问:
How to get minut sensor data every 15 minutes
I have hosted my website which uses C# onto the azure cloud, the website needs me to click on the button whenever I wanted to get the latest sensor update, I am wondering if I am able to get the sensor update every 15 minutes from Monday to Friday only without clicking a button?</p>

答: A lot of this will depend on exactly what/how you are interacting with elements.  But for something that is scheduled, especially on a frequency as you mention creating a WebJob that goes along with your web application and is set to a 15 minute interval is most likely the best option to get the scheduling with the least effort.</p>


问:
How to map through an array, which has an array of multiple objects?
I have called an api which gives me somewhat of a response like this,

```<code>manufacturers: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}]
0: {,…}
1: {,…}
2: {,…}
3: {,…}
4: {,…}
5: {,…}
6: {,…}
7: {,…}
8: {,…}
9: {,…}
</code>```

then I stored this in an array, which is like this (in console this gives me a single element array, which has an array of 10 elements ):

```<code>const arrOfProducts = [];

  axios
      .get(url)
      .then((response) => {
        arrOfProducts.push(response.data.result.manufacturers);
        console.log(arrOfProducts); //in console this gives me a single element array, which has an array of 10 elements
      })
      .catch((error) => {
        console.log(error);
      });
</code>```

Then I tried to map it in my React component Like this:

```<code><Box
      display='flex'
      flexDirection='row'
      alignItems='center'
      justifyContent='space-evenly'
    >
      {arrOfProducts.map((items,index)=>{
        return <Box key={index}>{items.city}</Box>  //it has multiple keys like city,name etc
      })}
    </Box>
</code>```

which doesn't render anything.
Please tell me what I am doing wrong. Also please can suggest a better approach than this to store an api.

答:
You are creating a wrapper array around the response unnecessarily, which is causing your confusion. The plain array of objects and nothing else is present in the response, so just use that.

Since you're in React, you should also be using a state setter. Something like:

```<code>const [products, setProducts] = useState([]);

useEffect(() => {
    axios
        .get(url)
        .then((response) => {
            setProducts(response.data.result.manufacturers);
        })
        .catch((error) => {
            console.log(error);
        });
}, []);
</code>```

You don't need to also .push the result to another array.

Body:
I have called an api which gives me somewhat of a response like this,

manufacturers: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}]
0: {,…}
1: {,…}
2: {,…}
3: {,…}
4: {,…}
5: {,…}
6: {,…}
7: {,…}
8: {,…}
9: {,…}

then I stored this in an array, which is like this (in console this gives me a single element array, which has an array of 10 elements ):

const arrOfProducts = [];

  axios
      .get(url)
      .then((response) => {
        arrOfProducts.push(response.data.result.manufacturers);
        console.log(arrOfProducts); //in console this gives me a single element array, which has an array of 10 elements
      })
      .catch((error) => {
        console.log(error);
      });

Then I tried to map it in my React component Like this:

<Box
      display='flex'
      flexDirection='row'
      alignItems='center'
      justifyContent='space-evenly'
    >
      {arrOfProducts.map((items,index)=>{
        return <Box key={index}>{items.city}</Box>  //it has multiple keys like city,name etc
      })}
    </Box>

which doesn't render anything.
Please tell me what I am doing wrong. Also please can suggest a better approach than this to store an api.

Body:
You are creating a wrapper array around the response unnecessarily, which is causing your confusion. The plain array of objects and nothing else is present in the response, so just use that.

Since you're in React, you should also be using a state setter. Something like:

const [products, setProducts] = useState([]);

useEffect(() => {
    axios
        .get(url)
        .then((response) => {
            setProducts(response.data.result.manufacturers);
        })
        .catch((error) => {
            console.log(error);
        });
}, []);

You don't need to also .push the result to another array.


问:
Clearing a selected item in dropdown after selecting item in other dropdown with vue-treeselect
I'm coding about auto select provinces in Thailand, When I choose province A in province dropdown the district dropdown will change to value in province A, and when I change to province B in province dropdown value in district dropdown has changed to district in province B already but the UI of district dropdown still shows district in province A.

I have researched treeselect docs and tried for several days now, and I really can't find a solution :-(

This is UI rightnow

```<code><treeselect
    id="province-selected"
    v-model="state.provinceSelected"
    :options="provinceArr"
    placeholder="กรุณาเลือกจังหวัด"
    noResultsText="ไม่พบข้อมูล"
    data-test="province-input"
    :class="{ errorselect: v$.provinceSelected.$errors.length }"
    :normalizer="normalizerProvince"
    @select="getDistrict"
    zIndex="20000"
    :clearable="false"
    :allowClearingDisabled="true"
/>
</code>```

答:
The official documentation of VueTreeselect mentions, the select event is Emitted after selecting an option. It has no dependency with the value update. I prefer you to use input event instead of select. Because the documentation states, the input event will be Emitted after value changes. So inside this method you will get the updated value for the first select.

Working Fiddle

Vue.component('treeselect', VueTreeselect.Treeselect)
new Vue({
    el: '#app',
    data: {
        provinceArr: [
            { id: 1, label: 'Province 1', districtArr: [
                { id: 10, label: 'District 01' },
                { id: 11, label: 'District 02' },
                { id: 12, label: 'District 03' },
                { id: 13, label: 'District 04' },
            ]},
            { id: 2, label: 'Province 2', districtArr: [
                { id: 20, label: 'District 21' },
                { id: 21, label: 'District 22' },
                { id: 22, label: 'District 23' },
                { id: 23, label: 'District 24' },
            ]},
            { id: 3, label: 'Province 3', districtArr: [
                { id: 30, label: 'District 31' },
                { id: 31, label: 'District 32' },
                { id: 32, label: 'District 33' },
                { id: 33, label: 'District 34' },
            ] },
            { id: 4, label: 'Province 4', districtArr: [
                { id: 40, label: 'District 41' },
                { id: 41, label: 'District 42' },
                { id: 42, label: 'District 43' },
                { id: 43, label: 'District 44' },
            ] },
            { id: 5, label: 'Province 5', districtArr: [
                { id: 50, label: 'District 51' },
                { id: 51, label: 'District 52' },
                { id: 52, label: 'District 53' },
                { id: 53, label: 'District 54' },
            ] },
            { id: 6, label: 'Province 6', districtArr: [
                { id: 60, label: 'District 61' },
                { id: 61, label: 'District 62' },
                { id: 72, label: 'District 73' },
                { id: 73, label: 'District 74' },
            ] },
        ],
        districtArr: [],
        state: {
            provinceSelected: null,
            districtSelected: null,
        },
    },
    methods: {
        getDistrict: function(node, instanceId) {
            console.log(this.state.provinceSelected, node, instanceId);
            // Some logic to populate districts
            this.districtArr = this.provinceArr.find(item => item.id === this.state.provinceSelected).districtArr;
        },
        onDistrictSelected: function(node, instanceId) {
            console.log(this.state.districtSelected)
        }
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- include Vue 2.x -->
<script src="https://cdn.jsdelivr.net/npm/vue@^2"></script>
<!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
<script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
<div id="app">
    <div>
        <p>Province</p>
        <treeselect
            id="province-selected"
            v-model="state.provinceSelected"
            :options="provinceArr"
            placeholder="กรุณาเลือกจังหวัด"
            noResultsText="ไม่พบข้อมูล"
            data-test="province-input"
            @input="getDistrict"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
    <div>
        <p>District</p>
        <treeselect
            id="district-selected"
            v-model="state.districtSelected"
            :options="districtArr"
            placeholder="กรุณาเลือกจังหวัด"
            noResultsText="ไม่พบข้อมูล"
            data-test="district-input"
            @input="onDistrictSelected"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
</div></code>```

Body:
I'm coding about auto select provinces in Thailand, When I choose province A in province dropdown the district dropdown will change to value in province A, and when I change to province B in province dropdown value in district dropdown has changed to district in province B already but the UI of district dropdown still shows district in province A.

I have researched treeselect docs and tried for several days now, and I really can't find a solution :-(

This is UI rightnow

<treeselect
    id="province-selected"
    v-model="state.provinceSelected"
    :options="provinceArr"
    placeholder="กรุณาเลือกจังหวัด"
    noResultsText="ไม่พบข้อมูล"
    data-test="province-input"
    :class="{ errorselect: v$.provinceSelected.$errors.length }"
    :normalizer="normalizerProvince"
    @select="getDistrict"
    zIndex="20000"
    :clearable="false"
    :allowClearingDisabled="true"
/>

Body:
The official documentation of VueTreeselect mentions, the select event is Emitted after selecting an option. It has no dependency with the value update. I prefer you to use input event instead of select. Because the documentation states, the input event will be Emitted after value changes. So inside this method you will get the updated value for the first select.

Working Fiddle

Vue.component('treeselect', VueTreeselect.Treeselect)
new Vue({
    el: '#app',
    data: {
        provinceArr: [
            { id: 1, label: 'Province 1', districtArr: [
                { id: 10, label: 'District 01' },
                { id: 11, label: 'District 02' },
                { id: 12, label: 'District 03' },
                { id: 13, label: 'District 04' },
            ]},
            { id: 2, label: 'Province 2', districtArr: [
                { id: 20, label: 'District 21' },
                { id: 21, label: 'District 22' },
                { id: 22, label: 'District 23' },
                { id: 23, label: 'District 24' },
            ]},
            { id: 3, label: 'Province 3', districtArr: [
                { id: 30, label: 'District 31' },
                { id: 31, label: 'District 32' },
                { id: 32, label: 'District 33' },
                { id: 33, label: 'District 34' },
            ] },
            { id: 4, label: 'Province 4', districtArr: [
                { id: 40, label: 'District 41' },
                { id: 41, label: 'District 42' },
                { id: 42, label: 'District 43' },
                { id: 43, label: 'District 44' },
            ] },
            { id: 5, label: 'Province 5', districtArr: [
                { id: 50, label: 'District 51' },
                { id: 51, label: 'District 52' },
                { id: 52, label: 'District 53' },
                { id: 53, label: 'District 54' },
            ] },
            { id: 6, label: 'Province 6', districtArr: [
                { id: 60, label: 'District 61' },
                { id: 61, label: 'District 62' },
                { id: 72, label: 'District 73' },
                { id: 73, label: 'District 74' },
            ] },
        ],
        districtArr: [],
        state: {
            provinceSelected: null,
            districtSelected: null,
        },
    },
    methods: {
        getDistrict: function(node, instanceId) {
            console.log(this.state.provinceSelected, node, instanceId);
            // Some logic to populate districts
            this.districtArr = this.provinceArr.find(item => item.id === this.state.provinceSelected).districtArr;
        },
        onDistrictSelected: function(node, instanceId) {
            console.log(this.state.districtSelected)
        }
    }
})

<!-- include Vue 2.x -->
<script src="https://cdn.jsdelivr.net/npm/vue@^2"></script>
<!-- include vue-treeselect & its styles. you can change the version tag to better suit your needs. -->
<script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
<div id="app">
    <div>
        <p>Province</p>
        <treeselect
            id="province-selected"
            v-model="state.provinceSelected"
            :options="provinceArr"
            placeholder="กรุณาเลือกจังหวัด"
            noResultsText="ไม่พบข้อมูล"
            data-test="province-input"
            @input="getDistrict"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
    <div>
        <p>District</p>
        <treeselect
            id="district-selected"
            v-model="state.districtSelected"
            :options="districtArr"
            placeholder="กรุณาเลือกจังหวัด"
            noResultsText="ไม่พบข้อมูล"
            data-test="district-input"
            @input="onDistrictSelected"
            zIndex="20000"
            :clearable="false"
            :allowClearingDisabled="true"
        />
    </div>
</div>


问:
How to make sure a line of code is run after another has completed?
I tried to make the last two lines of this code run after the ones before them but they have always run first! Please help.</p>
```<code>PostAPI.getPostById(postId: self.postId) { postResponse in
        let post = postResponse
        self.posts[indexPath.row] = post
        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
        self.postsTableView.reloadRows(at: [cellNumber], with: .none)
        likesButton?.tintColor = .systemPink
        likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
    }
</code>```

答:
Maybe try reloading the table view using CATransaction

1. Create a table view extension to add completion to rows reload

```<code>extension UITableView
{
    func reloadRows(at indexPaths: [IndexPath],
                    with animation: UITableView.RowAnimation,
                    completion: (() -> Void)?)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        reloadRows(at: indexPaths, with: animation)
        CATransaction.commit()
    }
}
</code>```

Then try adjusting your code to use it as follows

```<code>PostAPI.getPostById(postId: self.postId) { postResponse in
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)

    // Reload the table view with completion handler
    self.postsTableView.reloadRows(at: [cellNumber], with: .none) { [weak self] in

        // Reload complete, do your work
        self?.likesButton?.tintColor = .systemPink
        self?.likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)

    }
}
</code>```

Give this a go and see if this helps you

Body:
I tried to make the last two lines of this code run after the ones before them but they have always run first! Please help.

PostAPI.getPostById(postId: self.postId) { postResponse in
        let post = postResponse
        self.posts[indexPath.row] = post
        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
        self.postsTableView.reloadRows(at: [cellNumber], with: .none)
        likesButton?.tintColor = .systemPink
        likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
    }

Body:
Maybe try reloading the table view using CATransaction

1. Create a table view extension to add completion to rows reload

extension UITableView
{
    func reloadRows(at indexPaths: [IndexPath],
                    with animation: UITableView.RowAnimation,
                    completion: (() -> Void)?)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        reloadRows(at: indexPaths, with: animation)
        CATransaction.commit()
    }
}

Then try adjusting your code to use it as follows

PostAPI.getPostById(postId: self.postId) { postResponse in
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)

    // Reload the table view with completion handler
    self.postsTableView.reloadRows(at: [cellNumber], with: .none) { [weak self] in

        // Reload complete, do your work
        self?.likesButton?.tintColor = .systemPink
        self?.likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)

    }
}

Give this a go and see if this helps you


答:
You need to use state to rerender the component, just pushing to the array will not re-render

do it like this if you are using functional component

```<code>import React, { useState, useEffect } from 'react';

const [item, setItems] = useState([]);

// Wrap api request in useEffect to make sure it only run once
useEffect(() => {
    axios.get(url).then((response) => {
        setItems(existingItems => [...existingItems, response.data.result.manufacturers]);
    })
    .catch((error) => {
        console.log(error);
    });
}, []);

// Render
<Box
    display='flex'
    flexDirection='row'
    alignItems='center'
    justifyContent='space-evenly'
>
    {items.map((item,index)=>{
        return <Box key={index}>{item.city}</Box>
    })}
</Box>
</code>```

Title: How to map through an array, which has an array of multiple objects?

Body:
You need to use state to rerender the component, just pushing to the array will not re-render

do it like this if you are using functional component

import React, { useState, useEffect } from 'react';

const [item, setItems] = useState([]);

// Wrap api request in useEffect to make sure it only run once
useEffect(() => {
    axios.get(url).then((response) => {
        setItems(existingItems => [...existingItems, response.data.result.manufacturers]);
    })
    .catch((error) => {
        console.log(error);
    });
}, []);

// Render
<Box
    display='flex'
    flexDirection='row'
    alignItems='center'
    justifyContent='space-evenly'
>
    {items.map((item,index)=>{
        return <Box key={index}>{item.city}</Box>
    })}
</Box>


问:
Python Pandas DataFrame generating new column based on last n columns value
Original Dataframe:
enter image description here
Outcome Rules:
Only the following scenarios will be marked as True:
Scenario 1: A1: True, A2: True
Scenario 2: A1: False, A2: True, B1: True, B2: True
Scenario 3: A1: False, A2: True, B1: False, B2: True, C1: True, C2: True

Please help here!

答:
You can simply convert your logics like the following. Ofcourse you need to make sure all those columns are of boolean types.</p>
```<code>scen_1 = df['A1'] & df['A2']
scen_2 = ~df['A1'] & df['A2'] & df['B1'] & df['B2']
scen_3 = ~df['A1'] & df['A2'] & ~df['B1'] & df['C1'] & df['C2']

df['Outcome'] = scen_1 | scen_2 | scen_3
</code>```

Body:
You can simply convert your logics like the following. Ofcourse you need to make sure all those columns are of boolean types.

scen_1 = df['A1'] & df['A2']
scen_2 = ~df['A1'] & df['A2'] & df['B1'] & df['B2']
scen_3 = ~df['A1'] & df['A2'] & ~df['B1'] & df['C1'] & df['C2']

df['Outcome'] = scen_1 | scen_2 | scen_3


问:
How to pass two arguments in a url with (?P<pk>\d+)$'
In the code below referring to django's urls.py file, I'm passing the pk as an argument in the url:

```<code>url(r'^data/edit_item/(?P<pk>\d+)$', edit_data, name="edit_data")
</code>```

I want to know if there is a way to pass two arguments in this kind of regular expression. I've tried several ways like:

```<code>url(r'^data/edit_item/(?P<pk>\d+)$&header', edit_data, name="edit_data")
</code>```

but I'm having a lot of trouble getting the right format.

The url is being called directly in the html:

```<code>{% if header|lower == "specie" %}

    <a href="{% url 'edit_data' item.pk %}" role="button" aria-pressed="true" > Edit</a>

{% endif %}
</code>```

So I need to pass the argument header in the html as well:

```<code>{% if header|lower == "specie" %}

    <a href="{% url 'edit_data' item.pk header %}" role="button" aria-pressed="true" > Edit</a>

{% endif %}
</code>```

答:
Can you try using from django.urls import path:

path('data/edit_item/<slug:pk>/<slug:header>/', edit_data, name="edit_data")
```
<p>If you want to use url with regex, try this:</p>
<pre class="lang-py prettyprint-override"><code>url(r'^data/edit_item/(?P<pk>\S+)/(?P<header\S+)/', edit_data, name="edit_data")
</code>```

Body:
In the code below referring to django's urls.py file, I'm passing the pk as an argument in the url:

url(r'^data/edit_item/(?P<pk>\d+)$', edit_data, name="edit_data")

I want to know if there is a way to pass two arguments in this kind of regular expression. I've tried several ways like:

url(r'^data/edit_item/(?P<pk>\d+)$&header', edit_data, name="edit_data")

but I'm having a lot of trouble getting the right format.

The url is being called directly in the html:

{% if header|lower == "specie" %}

     Edit

{% endif %}

So I need to pass the argument header in the html as well:

{% if header|lower == "specie" %}

     Edit

{% endif %}

Body:
Can you try using from django.urls import path:

path('data/edit_item/<slug:pk>/<slug:header>/', edit_data, name="edit_data")

If you want to use url with regex, try this:

url(r'^data/edit_item/(?P<pk>\S+)/(?P<header\S+)/', edit_data, name="edit_data")


问:
Reorder Pandas Columns
How can I reorder using pandas, 40,41,42,43,44 next to 2 ??

Is there any fastest and simple way to do it?

 I dont want using type pd["sku_id","primary_category_code","primary_category_1","primary_category_2"...] to reorder...

 take so much effort to do that.

For example:

```<code>     #   Column                     Non-Null Count  Dtype
---  ------                     --------------  -----
 0   sku_id                     274 non-null    object
 1   primary_category_code      274 non-null    object
 2   primary_category_name_chi  274 non-null    object
 3   cat_codes                  274 non-null    object
 4   cat_names_chi              274 non-null    object
 5   name_chi                   274 non-null    object
 6   brand_name_chi             274 non-null    object
 7   summary_chi                274 non-null    object
 8   description_en             86 non-null     object
 9   description_chi            154 non-null    object
 10  image_urls                 274 non-null    object
 11  creation_time              274 non-null    object
 12  store_code                 274 non-null    object
 13  original_price             274 non-null    float64
 14  discount_price             271 non-null    float64
 15  stock_available            274 non-null    int64
 16  out_of_stock_since         2 non-null      object
 17  max_order_quantity         0 non-null      float64
 18  total_shipped_quantity     232 non-null    float64
 19  manu_country_chi           274 non-null    object
 20  height                     274 non-null    float64
 21  length                     274 non-null    float64
 22  width                      274 non-null    float64
 23  dimension_unit             274 non-null    object
 24  weight                     274 non-null    float64
 25  weight_unit                274 non-null    object
 26  colors                     140 non-null    object
 27  delivery_mode              274 non-null    object
 28  pickup_days                274 non-null    object
 29  num_days_to_be_ready       274 non-null    int64
 30  online_date                0 non-null      float64
 31  offline_date               155 non-null    object
 32  warranty_period            273 non-null    float64
 33  warranty_period_unit       270 non-null    object
 34  warranty_supplier_en       270 non-null    object
 35  warranty_supplier_chi      270 non-null    object
 36  virtual_store_code         0 non-null      float64
 37  virtual_store_name_en      0 non-null      float64
 38  virtual_store_name_chi     0 non-null      float64
 39  primary_store              274 non-null    object
 40  primary_category_1         274 non-null    object
 41  primary_category_2         274 non-null    object
 42  primary_category_3         274 non-null    object
 43  primary_category_4         274 non-null    object
 44  primary_category_5         274 non-null    object
</code>```

答:
Given some DataFrame that looks like this:

```<code>df = pd.DataFrame(columns=range(1, 11))
df

Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Index: []
</code>```

You can reorder the DataFrame's columns by index using iloc. I use np.r_ to make selection easy:

```<code>df.iloc[:, np.r_[0:2, 7:10, 2:8]]

Empty DataFrame
Columns: [1, 2, 8, 9, 10, 3, 4, 5, 6, 7, 8]
Index: []
</code>```

Title: Reorder Pandas Columns

Body:
How can I reorder using pandas, 40,41,42,43,44 next to 2 ??

Is there any fastest and simple way to do it?

 I dont want using type pd["sku_id","primary_category_code","primary_category_1","primary_category_2"...] to reorder...

 take so much effort to do that.

For example:

     #   Column                     Non-Null Count  Dtype
---  ------                     --------------  -----
 0   sku_id                     274 non-null    object
 1   primary_category_code      274 non-null    object
 2   primary_category_name_chi  274 non-null    object
 3   cat_codes                  274 non-null    object
 4   cat_names_chi              274 non-null    object
 5   name_chi                   274 non-null    object
 6   brand_name_chi             274 non-null    object
 7   summary_chi                274 non-null    object
 8   description_en             86 non-null     object
 9   description_chi            154 non-null    object
 10  image_urls                 274 non-null    object
 11  creation_time              274 non-null    object
 12  store_code                 274 non-null    object
 13  original_price             274 non-null    float64
 14  discount_price             271 non-null    float64
 15  stock_available            274 non-null    int64
 16  out_of_stock_since         2 non-null      object
 17  max_order_quantity         0 non-null      float64
 18  total_shipped_quantity     232 non-null    float64
 19  manu_country_chi           274 non-null    object
 20  height                     274 non-null    float64
 21  length                     274 non-null    float64
 22  width                      274 non-null    float64
 23  dimension_unit             274 non-null    object
 24  weight                     274 non-null    float64
 25  weight_unit                274 non-null    object
 26  colors                     140 non-null    object
 27  delivery_mode              274 non-null    object
 28  pickup_days                274 non-null    object
 29  num_days_to_be_ready       274 non-null    int64
 30  online_date                0 non-null      float64
 31  offline_date               155 non-null    object
 32  warranty_period            273 non-null    float64
 33  warranty_period_unit       270 non-null    object
 34  warranty_supplier_en       270 non-null    object
 35  warranty_supplier_chi      270 non-null    object
 36  virtual_store_code         0 non-null      float64
 37  virtual_store_name_en      0 non-null      float64
 38  virtual_store_name_chi     0 non-null      float64
 39  primary_store              274 non-null    object
 40  primary_category_1         274 non-null    object
 41  primary_category_2         274 non-null    object
 42  primary_category_3         274 non-null    object
 43  primary_category_4         274 non-null    object
 44  primary_category_5         274 non-null    object

Body:
Given some DataFrame that looks like this:

df = pd.DataFrame(columns=range(1, 11))
df

Empty DataFrame
Columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Index: []

You can reorder the DataFrame's columns by index using iloc. I use np.r_ to make selection easy:

df.iloc[:, np.r_[0:2, 7:10, 2:8]]

Empty DataFrame
Columns: [1, 2, 8, 9, 10, 3, 4, 5, 6, 7, 8]
Index: []


问:
Finding _and then clicking_ ListBox Items from another program built in VB6 (ThunderRT6ListBox)
wracking my brain on this one.

I have successfully utilized this link to successfully grab text of the items of a ListBox (ThunderRT6ListBox specifically) working with WinAPI functions.  What I want to accomplish is to select and then double-click the necessary item from this list.  I've successfully been able to find the WindowRect of the ListBox itself, but I cannot get the cursor position relative to this Box and desired item.

I have to submit a double-click on this as the author of the application I'm ScreenScraping set the double-click event of the item to open a child window where parameters are set relative to the selected item.

I'm only going to post the part where I'm having trouble - again - I've successfully found the data and have been able to get the WindowRect of the ListBox - I'm now trying to click and double-click the item needed.  I imagine I need to then set my mouse cursor position using another winAPI, but when attempting to get the WindowRect of the Item it fails and gives a 0 for both x,y coordinates.  I have also tried SendKeys and other variants of this with an attempt to "Select" the item by value. . . this also fails.

I am writing in VB.NET but do not mind answers posted with C#, as there are converters and these answers are more prevalent for everything anyway (which is also helping me to learn that language too).

 Public Function GetListBoxContents(ByVal listBoxHwnd As IntPtr) As List(Of String)
    Dim cnt As Integer = CInt(SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, Nothing))

    Dim listBoxContent As List(Of String) = New List(Of String)()

    For i As Integer = 0 To cnt - 1
      Dim sb As StringBuilder = New StringBuilder(256)
      Dim getTextLen As Integer = CInt(SendMessage(listBoxHwnd, LB_GETTEXTLEN, Nothing, Nothing))
      Dim getText As IntPtr = SendMessage(listBoxHwnd, LB_GETTEXT, CType(i, IntPtr), sb)
      Dim ComRect As RECT
      GetWindowRect(listBoxHwnd, ComRect)
      Debug.Print("Rect's x coordinate = " & ComRect.x) 'Produces valid X coord when looking
                                                         at listboxHwnd - if I look at "getText"
                                                         it fails - I assume because this really
                                                         is not
      Debug.Print("Rect's y coordinate = " & ComRect.y)
      Dim lparam As Integer = MakeLong(ComRect.x, ComRect.y)
      SetForegroundWindow(listBoxHwnd)
      If sb.ToString Like "*COM5*" Then
        Debug.Print("hWnd of ListBox item = ", getText)
        WindowsEnumerator.SendMessage(getText, WM_LBUTTONDOWN, &H1, lparam)
        WindowsEnumerator.SendMessage(getText, WM_LBUTTONUP, &H1, lparam)

        PostMessage(getText, WM_LBUTTONDBLCLK, &H1, lparam)

        PostMessage(getText, BM_CLICK, &H1, lparam)

        SendInputs.Mouse_Click()

        SendInputs.SendKey(Convert.ToChar(13))

        SendKeys.SendWait("{ENTER}")

      End If
      listBoxContent.Add(sb.ToString)
    Next

    Return listBoxContent
  End Function
```

答:
After losing some of my hair, I finally managed to figure out how to do what I need.

HUGE kudos to Unhnd_Exception on the Daniweb site for this neat, intuitive class.    (I'm linking to the post, but also posting the content of Unhnd_Exception's class here in case that site ever goes down.  If I have not attributed it enough to the user, please help me make a better approach to this without losing the code - this was a life-saver! (REF#1))

Also - I think ANYONE who dabbles in the API Realm who has struggled to find the ACTUAL values of the Constants will really appreciate this following link.  It saved my bacon on the remainder of the code. (REF#2)  Additionally, having the MSDN Page for List Box Messages was the other Key I needed as it contained the different methods to communicate with these objects! (REF#3)

Final Methodology used to accomplish my task:

  Public Const LB_GETCOUNT As Integer = &H18B ' Gets the count of items in ListBox
  Public Const LB_GETTEXTLEN As Integer = &H18A ' Gets Length of Text for given
                                                  Item based on hWnd
  Public Const LB_GETTEXT As Integer = &H189 ' Gets Text
  Public Const LB_GETITEMRECT As Integer = &H198 ' Gets ListBox Item RECT - NOTE:
                                                 ' This still failed for me and returned
                                                 ' "0" for all dimensions in this case!
  Public Const LB_SELECTSTRING As Integer = &H18C ' Hoped this was useful - not so much
  Public Const LB_SETCURSEL As Integer = &H186 ' THIS ONE - NICE Beauty!
              'LB_SETCURSEL will focus the selection on the object by index
              'It will also scroll the box if there are enough items.
  Public Const LB_SETSEL As Integer = &H185 ' Ultimately did not use this one.

  Public Function GetListBoxContents(ByVal listBoxHwnd As IntPtr) As List(Of String)
    Dim cnt As Integer = CInt(SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, Nothing))

    Dim listBoxContent As List(Of String) = New List(Of String)()

    For i As Integer = 0 To cnt - 1
      Dim sb As StringBuilder = New StringBuilder(256)
      Dim itmRect As RECT
      Dim getTextLen As Integer = CInt(SendMessage(listBoxHwnd, LB_GETTEXTLEN, Nothing, Nothing))
      Dim getText As IntPtr = SendMessage(listBoxHwnd, LB_GETTEXT, CType(i, IntPtr), sb)

      SendMessage(getText, LB_SETCURSEL, CType(i, IntPtr), Nothing)
      Dim ComRect As RECT
      GetWindowRect(listBoxHwnd, ComRect)
      Debug.Print("Rect's x coordinate = " & ComRect.x)
      Debug.Print("Rect's y coordinate = " & ComRect.y)
      Debug.Print("Rect's h coordinate = " & ComRect.h)
      Debug.Print("Rect's w coordinate = " & ComRect.w)
      SendMessageRect(getText, LB_GETITEMRECT, CType(i, IntPtr), itmRect)
      Debug.Print("itmRect's x coordinate = " & itmRect.x) 'All of these returned 0's
      Debug.Print("itmRect's y coordinate = " & itmRect.y) 'Perhaps I'm calling the routine
      Debug.Print("itmRect's h coordinate = " & itmRect.h) 'incorrectly???  Would love to know
      Debug.Print("itmRect's w coordinate = " & itmRect.w) 'why this fails.
      SetCursorPos(ComRect.x + 10, ComRect.h - 10) 'THIS ONE.  Moves my cursor in position
                                                   'to select the appropriate object.
                                                   'If I could make the GETITEMRECT
      SetForegroundWindow(listBoxHwnd)             'Method to work, this would be MOST ideal
                                                   'As it would always be concurrent
                                                   'with the given item and be less
      If sb.ToString Like "*COM5*" Then            'prone to failure. Moves selection to bottom.
        Debug.Print("hWnd of ListBox item = ", getText)
        SendMessage(listBoxHwnd, LB_SETCURSEL, CType(i, IntPtr), Nothing)
        SendInputs.Double_Click() ' Here is the clicker - worked like a champ

      End If
      listBoxContent.Add(sb.ToString)
    Next
    Return listBoxContent
  End Function

```
<p><strong><code>Sendinput</code></strong> that actually works (REF#1)</p>
<p>Value of the constants for the Windows 32-bit API (REF#2)</p>
<p>List Box Messages (REF#3)</p>
<p>Code used from <code>Unhnd_Exception</code> on Daniweb in entirety:</p>
<pre class="lang-vb.net prettyprint-override"><code>Imports System.Runtime.InteropServices

Public Class SendInputs

    Private Const KeyDown As Integer = &H0
    Private Const KeyUp As Integer = &H2

    <DllImport("user32.dll")> _
  Private Shared Function SendInput( _
        ByVal nInputs As Integer, _
        ByVal pInputs() As INPUT, _
        ByVal cbSize As Integer) As Integer
    End Function

    <StructLayout(LayoutKind.Explicit)> _
   Private Structure INPUT
        'Field offset 32 bit machine 4
        '64 bit machine 8
        <FieldOffset(0)> _
        Public type As Integer
        <FieldOffset(8)> _
        Public mi As MOUSEINPUT
        <FieldOffset(8)> _
        Public ki As KEYBDINPUT
        <FieldOffset(8)> _
        Public hi As HARDWAREINPUT
    End Structure

    Private Structure MOUSEINPUT
        Public dx As Integer
        Public dy As Integer
        Public mouseData As Integer
        Public dwFlags As Integer
        Public time As Integer
        Public dwExtraInfo As IntPtr
    End Structure

    Private Structure KEYBDINPUT
        Public wVk As Short
        Public wScan As Short
        Public dwFlags As Integer
        Public time As Integer
        Public dwExtraInfo As IntPtr
    End Structure

    Private Structure HARDWAREINPUT
        Public uMsg As Integer
        Public wParamL As Short
        Public wParamH As Short
    End Structure

      Public Shared Sub SendKey(ByVal key As Char)
        Dim Inpts(1) As INPUT

        'key down
        Inpts(0).type = 1
        Inpts(0).ki.wVk = Convert.ToInt16(CChar(key))
        Inpts(0).ki.dwFlags = KeyDown

        'key up
        Inpts(1).type = 1
        Inpts(1).ki.wVk = Convert.ToInt16(CChar(key))
        Inpts(1).ki.dwFlags = KeyUp

        SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT)))
    End Sub
End Class
</code>```

I modified his Button click Subroutine (full content shown below) to accomplish what I need (removed the binding to a button click within the program).  If you duplicate the final line SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT))) you essentially get 2 clicks in rapid succession.  In my implementation I added a "Mouse_Click" routine (as mentioned - no WinForm Control needed), and I also implemented a "Double_Click" routine which gives the result I need.)

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        'raises the key down and up events

        Dim Inpts(1) As INPUT

        'key down
        Inpts(0).type = 1
        Inpts(0).ki.wVk = Convert.ToInt16(CChar("J"))
        Inpts(0).ki.dwFlags = 0

        'key up
        Inpts(1).type = 1
        Inpts(1).ki.wVk = Convert.ToInt16(CChar("J"))
        Inpts(1).ki.dwFlags = 2

        SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT)))
    End Sub
```

Body:
After losing some of my hair, I finally managed to figure out how to do what I need.

HUGE kudos to Unhnd_Exception on the Daniweb site for this neat, intuitive class.    (I'm linking to the post, but also posting the content of Unhnd_Exception's class here in case that site ever goes down.  If I have not attributed it enough to the user, please help me make a better approach to this without losing the code - this was a life-saver! (REF#1))

Also - I think ANYONE who dabbles in the API Realm who has struggled to find the ACTUAL values of the Constants will really appreciate this following link.  It saved my bacon on the remainder of the code. (REF#2)  Additionally, having the MSDN Page for List Box Messages was the other Key I needed as it contained the different methods to communicate with these objects! (REF#3)

Final Methodology used to accomplish my task:

  Public Const LB_GETCOUNT As Integer = &H18B ' Gets the count of items in ListBox
  Public Const LB_GETTEXTLEN As Integer = &H18A ' Gets Length of Text for given
                                                  Item based on hWnd
  Public Const LB_GETTEXT As Integer = &H189 ' Gets Text
  Public Const LB_GETITEMRECT As Integer = &H198 ' Gets ListBox Item RECT - NOTE:
                                                 ' This still failed for me and returned
                                                 ' "0" for all dimensions in this case!
  Public Const LB_SELECTSTRING As Integer = &H18C ' Hoped this was useful - not so much
  Public Const LB_SETCURSEL As Integer = &H186 ' THIS ONE - NICE Beauty!
              'LB_SETCURSEL will focus the selection on the object by index
              'It will also scroll the box if there are enough items.
  Public Const LB_SETSEL As Integer = &H185 ' Ultimately did not use this one.

  Public Function GetListBoxContents(ByVal listBoxHwnd As IntPtr) As List(Of String)
    Dim cnt As Integer = CInt(SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, Nothing))

    Dim listBoxContent As List(Of String) = New List(Of String)()

    For i As Integer = 0 To cnt - 1
      Dim sb As StringBuilder = New StringBuilder(256)
      Dim itmRect As RECT
      Dim getTextLen As Integer = CInt(SendMessage(listBoxHwnd, LB_GETTEXTLEN, Nothing, Nothing))
      Dim getText As IntPtr = SendMessage(listBoxHwnd, LB_GETTEXT, CType(i, IntPtr), sb)

      SendMessage(getText, LB_SETCURSEL, CType(i, IntPtr), Nothing)
      Dim ComRect As RECT
      GetWindowRect(listBoxHwnd, ComRect)
      Debug.Print("Rect's x coordinate = " & ComRect.x)
      Debug.Print("Rect's y coordinate = " & ComRect.y)
      Debug.Print("Rect's h coordinate = " & ComRect.h)
      Debug.Print("Rect's w coordinate = " & ComRect.w)
      SendMessageRect(getText, LB_GETITEMRECT, CType(i, IntPtr), itmRect)
      Debug.Print("itmRect's x coordinate = " & itmRect.x) 'All of these returned 0's
      Debug.Print("itmRect's y coordinate = " & itmRect.y) 'Perhaps I'm calling the routine
      Debug.Print("itmRect's h coordinate = " & itmRect.h) 'incorrectly???  Would love to know
      Debug.Print("itmRect's w coordinate = " & itmRect.w) 'why this fails.
      SetCursorPos(ComRect.x + 10, ComRect.h - 10) 'THIS ONE.  Moves my cursor in position
                                                   'to select the appropriate object.
                                                   'If I could make the GETITEMRECT
      SetForegroundWindow(listBoxHwnd)             'Method to work, this would be MOST ideal
                                                   'As it would always be concurrent
                                                   'with the given item and be less
      If sb.ToString Like "*COM5*" Then            'prone to failure. Moves selection to bottom.
        Debug.Print("hWnd of ListBox item = ", getText)
        SendMessage(listBoxHwnd, LB_SETCURSEL, CType(i, IntPtr), Nothing)
        SendInputs.Double_Click() ' Here is the clicker - worked like a champ

      End If
      listBoxContent.Add(sb.ToString)
    Next
    Return listBoxContent
  End Function

Sendinput that actually works (REF#1)

Value of the constants for the Windows 32-bit API (REF#2)

List Box Messages (REF#3)

Code used from Unhnd_Exception on Daniweb in entirety:

Imports System.Runtime.InteropServices

Public Class SendInputs

    Private Const KeyDown As Integer = &H0
    Private Const KeyUp As Integer = &H2

    <DllImport("user32.dll")> _
  Private Shared Function SendInput( _
        ByVal nInputs As Integer, _
        ByVal pInputs() As INPUT, _
        ByVal cbSize As Integer) As Integer
    End Function

    <StructLayout(LayoutKind.Explicit)> _
   Private Structure INPUT
        'Field offset 32 bit machine 4
        '64 bit machine 8
        <FieldOffset(0)> _
        Public type As Integer
        <FieldOffset(8)> _
        Public mi As MOUSEINPUT
        <FieldOffset(8)> _
        Public ki As KEYBDINPUT
        <FieldOffset(8)> _
        Public hi As HARDWAREINPUT
    End Structure

    Private Structure MOUSEINPUT
        Public dx As Integer
        Public dy As Integer
        Public mouseData As Integer
        Public dwFlags As Integer
        Public time As Integer
        Public dwExtraInfo As IntPtr
    End Structure

    Private Structure KEYBDINPUT
        Public wVk As Short
        Public wScan As Short
        Public dwFlags As Integer
        Public time As Integer
        Public dwExtraInfo As IntPtr
    End Structure

    Private Structure HARDWAREINPUT
        Public uMsg As Integer
        Public wParamL As Short
        Public wParamH As Short
    End Structure

      Public Shared Sub SendKey(ByVal key As Char)
        Dim Inpts(1) As INPUT

        'key down
        Inpts(0).type = 1
        Inpts(0).ki.wVk = Convert.ToInt16(CChar(key))
        Inpts(0).ki.dwFlags = KeyDown

        'key up
        Inpts(1).type = 1
        Inpts(1).ki.wVk = Convert.ToInt16(CChar(key))
        Inpts(1).ki.dwFlags = KeyUp

        SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT)))
    End Sub
End Class

I modified his Button click Subroutine (full content shown below) to accomplish what I need (removed the binding to a button click within the program).  If you duplicate the final line SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT))) you essentially get 2 clicks in rapid succession.  In my implementation I added a "Mouse_Click" routine (as mentioned - no WinForm Control needed), and I also implemented a "Double_Click" routine which gives the result I need.)

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        'raises the key down and up events

        Dim Inpts(1) As INPUT

        'key down
        Inpts(0).type = 1
        Inpts(0).ki.wVk = Convert.ToInt16(CChar("J"))
        Inpts(0).ki.dwFlags = 0

        'key up
        Inpts(1).type = 1
        Inpts(1).ki.wVk = Convert.ToInt16(CChar("J"))
        Inpts(1).ki.dwFlags = 2

        SendInput(2, Inpts, Marshal.SizeOf(GetType(INPUT)))
    End Sub


问:
mysql bulk table script execution
I have 120 tables in my project.

Now I have to migrate MSSQL to MySQL.

So I did all Queries to create those tables that are already worked.

Now my problem is when I execute this script in MSSQL it completes within a second.

But MySQL takes around 4 min to complete its execution.

I want to improve my performance in MySQL. But I don't know how to do that if anyone knows please help me.

Thank you

Here is my sample table Script

MySQL

```<code>CREATE TABLE `rb_tbl_bak` (
  `BakPathId` int NOT NULL AUTO_INCREMENT,
  `BakPath` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `BakDate` datetime(3) DEFAULT NULL,
  PRIMARY KEY (`BakPathId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
</code>```

MSSQL

```<code>--Create table and its columns
CREATE TABLE [dbo].[RB_Tbl_Bak] (
    [BakPathId] [int] NOT NULL IDENTITY (1, 1),
    [BakPath] [nvarchar](500) NULL,
    [BakDate] [datetime] NULL);
GO
</code>```

like this way, I have to complete for 120+ tables

答:
Oh well, In this case, MySQL databases take time.

You can turn on profiling to get an idea of what takes so long. An example is given using Mysql's CLI:-

```<code>SET profiling = 1;
CREATE TABLE rb_tbl_back (id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
SET profiling = 1;
</code>```

You should get a response like this:-

```<code>mysql> SHOW PROFILES;
| Query_ID | Duration   | Query |
+----------+------------+-------------------------------------------------------------+
|        1 | 0.00913800 | CREATE TABLE rb_tbl_back (id BIGINT UNSIGNED NOT NULL PRIMARY KEY) |
+----------+------------+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW PROFILE FOR QUERY 1;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000071 |
| checking permissions | 0.000007 |
| Opening tables       | 0.001698 |
| System lock          | 0.000043 |
| creating table       | 0.007260 |
| After create         | 0.000004 |
| query end            | 0.000004 |
| closing tables       | 0.000015 |
| freeing items        | 0.000031 |
| logging slow query   | 0.000002 |
| cleaning up          | 0.000003 |
+----------------------+----------+
11 rows in set (0.00 sec)
</code>```

If you read the profiling documentation, there are other flags for showing the profile of the query CPU, BLOCK IO, etc that might help you on the 'creating table' stage.

I got this answer from here

Title: mysql bulk table script execution

Body:
I have 120 tables in my project.

Now I have to migrate MSSQL to MySQL.

So I did all Queries to create those tables that are already worked.

Now my problem is when I execute this script in MSSQL it completes within a second.

But MySQL takes around 4 min to complete its execution.

I want to improve my performance in MySQL. But I don't know how to do that if anyone knows please help me.

Thank you

Here is my sample table Script

MySQL

CREATE TABLE `rb_tbl_bak` (
  `BakPathId` int NOT NULL AUTO_INCREMENT,
  `BakPath` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `BakDate` datetime(3) DEFAULT NULL,
  PRIMARY KEY (`BakPathId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

MSSQL

--Create table and its columns
CREATE TABLE [dbo].[RB_Tbl_Bak] (
    [BakPathId] [int] NOT NULL IDENTITY (1, 1),
    [BakPath] [nvarchar](500) NULL,
    [BakDate] [datetime] NULL);
GO

like this way, I have to complete for 120+ tables

Body:
Oh well, In this case, MySQL databases take time.

You can turn on profiling to get an idea of what takes so long. An example is given using Mysql's CLI:-

SET profiling = 1;
CREATE TABLE rb_tbl_back (id BIGINT UNSIGNED NOT NULL PRIMARY KEY);
SET profiling = 1;

You should get a response like this:-

mysql> SHOW PROFILES;
| Query_ID | Duration   | Query |
+----------+------------+-------------------------------------------------------------+
|        1 | 0.00913800 | CREATE TABLE rb_tbl_back (id BIGINT UNSIGNED NOT NULL PRIMARY KEY) |
+----------+------------+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW PROFILE FOR QUERY 1;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000071 |
| checking permissions | 0.000007 |
| Opening tables       | 0.001698 |
| System lock          | 0.000043 |
| creating table       | 0.007260 |
| After create         | 0.000004 |
| query end            | 0.000004 |
| closing tables       | 0.000015 |
| freeing items        | 0.000031 |
| logging slow query   | 0.000002 |
| cleaning up          | 0.000003 |
+----------------------+----------+
11 rows in set (0.00 sec)

If you read the profiling documentation, there are other flags for showing the profile of the query CPU, BLOCK IO, etc that might help you on the 'creating table' stage.

I got this answer from here


答:
Use react useState / setState for this

function ProductList() {
  const [arrOfProducts, setArrOfProducts] = useState([]);

  useEffect(() => {
    axios.get("products").then(list => {
        setArrOfProducts([...arrOfProducts, ...list]);
    })
  })
}```


问:
"Web Server" doesn't appear on the "connected devices" when configuring Flutter for web-development
I want to setup Flutter to web-development and so I followed these instructions (Link to Flutter web setup):

```<code>$ flutter channel beta
$ flutter upgrade
$ flutter config --enable-web
$ flutter devices
</code>```

The output should be the following:

```<code>2 connected device:

Web Server • web-server • web-javascript • Flutter Tools
Chrome     • chrome     • web-javascript • Google Chrome 81.0.4044.129
</code>```

The problem is that my output doesn't contain the web-server:

```<code>2 connected devices:

Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150
Edge (web)   • edge   • web-javascript • Microsoft Edge 88.0.705.68
</code>```

Can you help?

答: While web-server is not listed in flutter devices it's still available. We don't list it any more because it's always available, so there's no need to check for its existence. This is unlike a phone that needs to be connected via USB and configured to accept debug connections, or emulator/simulator that needs to be started outside the Flutter tool.

Body:
I want to setup Flutter to web-development and so I followed these instructions (Link to Flutter web setup):

$ flutter channel beta
$ flutter upgrade
$ flutter config --enable-web
$ flutter devices

The output should be the following:

2 connected device:

Web Server • web-server • web-javascript • Flutter Tools
Chrome     • chrome     • web-javascript • Google Chrome 81.0.4044.129

The problem is that my output doesn't contain the web-server:

2 connected devices:

Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150
Edge (web)   • edge   • web-javascript • Microsoft Edge 88.0.705.68

Can you help?


问:
boto3: how to start instance with elastic gpu?
AWS docs States:

"You can launch an instance and associate it with an elastic GPU
  during launch.".

But I can't find if it's possible to do with boto3?

答:
```<code>Host:
 Type: AWS::EC2::Instance
 Properties:
   ...

   ElasticGpuSpecifications:
      - Type: "eg1.xlarge"
   ...
</code>```


问:
C++ GetAsyncKeyState() with private overridden attributes
I am trying to figure out how to use GetAsyncKeyState with private attributes forward and backwards from a base class. I need to be able to reset GetAsyncKeyState to other keypresses. Any idea?
Maybe overriding forward and backwards with other keypresses?

```<code>#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>
using namespace std;
bool reset_defaults = false;

class Base {
protected: // OR private
    int forward = VK_UP, backwards = VK_DOWN;
public: //...
}
////////////
class Move : public Base {
public:
    Base def;
    int move() {
        while (true) {
            if (GetAsyncKeyState(forward) < 0){
                cout << ("forward >>>\n");
                if (GetAsyncKeyState(forward) == 0){
                    cout << ("Stopped\n");
                }
             }
             if (GetAsyncKeyState(VK_SPACE) < 0){break;}
         }
}
int main() {
Move move;
move.move();
}
</code>```

Sorry, but I don't think I understand the whole logic of this yet.

PS UPDATE:

How can I override baseKeys values:

```<code>class MovementKeys {
protected:
    int baseKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right){
        default_key_forward = VK_UP;
        default_key_backward = VK_DOWN;
        default_key_left = VK_LEFT;
        default_key_right = VK_RIGHT;
    }
public:
    int definedCommand(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
        while (reset_defaults == false)
        {
            cout << ("HERE 1 \n");
            if (GetAsyncKeyState(default_key_forward) < 0)
            {
                cout << ("forward\n");
            }
            if (GetAsyncKeyState(default_key_backward) < 0)
            {
                court << ("backwards\n");
            }
            if (GetAsyncKeyState(default_key_left) < 0)
            {
                cout << ("left\n");
            }
            if (GetAsyncKeyState(default_key_right) < 0)
            {
                cout << ("right\n");
            }
            if (GetAsyncKeyState(VK_SPACE) < 0) { break; }

        }
        return 0;
    }
    int derived_newKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
        return baseKeys(default_key_forward, default_key_backward, default_key_left, default_key_right);
    }
</code>```

答:
You probably want to use member variables to store the keys. Instead of deriving the class with new keys, you set the variables in constructors (to default or to changed values) and can also change the key assignment later on.

You probably want to create a separate class, which reacts on the events.

```<code>#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

class World {
    public:
        void forward() { y--; };
        void backward() { y++; };
        void left() { x--; };
        void right() { x++; };

    private:
        int x = 0;
        int y = 0;
};

class MovementKeys {
// member variables
private:
    // keep reference to world instead of copy; main() has to make sure World object outlives MovementKeys object
    World& world;

    int key_forward;
    int key_backward;
    int key_left;
    int key_right;

public:
    // constructor, which only sets world, but keeps the keys at their default settings
    //
    // world has to be initialized before the constructor function body
    // as references have no default value
    // put initialization in member initialization list

    MovementKeys(World& w) : world(w)
    {
        key_forward = VK_UP;
        key_backward = VK_DOWN;
        key_left = VK_LEFT;
        key_right = VK_RIGHT;
    }

    // constructor which modifies keys
    MovementKeys(World& w, int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : world(w)
    {
        changeKeys(change_key_forward, change_key_backward, change_key_left, change_key_right);
    }

    // command loop controlled by keys
    int definedCommand()
    {
        while (true)
        {
            cout << ("HERE 1 \n");
            if (GetAsyncKeyState(key_forward) < 0)
            {
                cout << ("forward\n");
                world.forward();
            }
            if (GetAsyncKeyState(key_backward) < 0)
            {
                cout << ("backwards\n");
                world.backward();
            }
            if (GetAsyncKeyState(key_left) < 0)
            {
                cout << ("left\n");
                world.left();
            }
            if (GetAsyncKeyState(key_right) < 0)
            {
                cout << ("right\n");
                world.right();
            }
            // optionally change keys from within while loop
            if (GetAsyncKeyState(VK_BACK) < 0)
            {
                key_forward = VK_RETURN;
            }
            if (GetAsyncKeyState(VK_SPACE) < 0)
            {
                break;
            }
        }
        return 0;
    }

    // function for changing the keys stored in the member variables
    // can be called by constructor or externally
    void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
    {
        key_forward = change_key_forward;
        key_backward = change_key_backward;
        key_left = change_key_left;
        key_right = change_key_right;
    }
};

int main()
{
    World earth;

    // use default keys, declares local variable and constructs MovementKeys object called move
    MovementKeys move(earth);
    move.definedCommand();

    // use custom keys, share same world, declares local variable and constructs MovementKeys object called move2
    // static_cast<int>() with a letter in a literal char parameter works, because the VK_ values of letter keys are the actual ASCII values (on purpose by Microsoft, I would assume)
    MovementKeys move2(earth, static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));
    move2.definedCommand();

    // change keys in move2
    move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
    move2.definedCommand();

    // run first one again for the fun of it
    move.definedCommand();
}
</code>```

Alternatively passing World& only, where it is used in definedCommand (and at the same time be able to use several worlds):

```<code>class World {
    // ...
};

class MovementKeys {
// member variables without world, we can also put default value here
private:
    int key_forward = VK_UP;
    int key_backward = VK_DOWN;
    int key_left = VK_LEFT;
    int key_right = VK_RIGHT;

public:
    // default constructor with no parameters, delegate to other constructor
    // delegating not necessary, as the default values are set above anyway; just demonstrating various techniques for initializing member variables
    MovementKeys() : MovementKeys(VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT) {};

    // constructor which modifies keys, put everything in member initialization list
    MovementKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : key_forward(change_key_forward), key_backward(change_key_backward), key_left(change_key_left), key_right(change_key_right) {};

    // command loop controlled by keys, pass World& here as parameter
    int definedCommand(World& world)
    {
        while (true)
        {
           // ...
        }
        return 0;
    }

    void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
    {
        // ...
    }
};

int main()
{
    // use default keys, declares local variable and constructs MovementKeys object called move
    MovementKeys move;

    // use custom keys, declares local variable and constructs MovementKeys object called move2
    MovementKeys move2(static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));

    MovementKeys defaultMenuKeys;

    World earth;
    World moon;
    World menu; // between moving in worlds, we want to control some settings in a menu

    move.definedCommand(earth);
    move2.definedCommand(earth);
    move2.definedCommand(moon);

    // change keys in move2
    move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
    move2.definedCommand(earth);

    defaultMenuKeys.definedCommand(menu);

    // run first one again for the fun of it
    move.definedCommand(moon);
}
</code>```

You can introduce a (class) enum with a list of the states, why definedCommand() returns:

```<code>// outside or can be put into MovementKeys and henceforth used as MovementKeys::ReturnReason
class enum ReturnReason { EXIT, NEWKEYS, SHOWMENU, SWITCHWORLD };

// in class MovementKeys
ReturnReason definedCommand() {
    // ...
    return NEWKEYS;
    // ...
    return EXIT;
    // ...
    return SHOWMENU;
    // ...
}

// in main()
ReturnReason r = definedCommand();
if (r == NEWKEYS)
    move2.changeKeys(...);
else if (r == EXIT)
    return 0;
</code>```

If you use that 'trick' to also control the menu, it could make sense to use virtual inheritance now for World. As the normal World and the menu World probably react quite differently. (The base class (ancestor) would be World, which is recognized by MovementKeys. Your actual Worlds are objects of derived (children) classes, with more specific behaviour.

definedCommand then can be called and run with any derived class of the base class World.

Body:
I am trying to figure out how to use GetAsyncKeyState with private attributes forward and backwards from a base class. I need to be able to reset GetAsyncKeyState to other keypresses. Any idea?
Maybe overriding forward and backwards with other keypresses?

#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>
using namespace std;
bool reset_defaults = false;

class Base {
protected: // OR private
    int forward = VK_UP, backwards = VK_DOWN;
public: //...
}
////////////
class Move : public Base {
public:
    Base def;
    int move() {
        while (true) {
            if (GetAsyncKeyState(forward) < 0){
                cout << ("forward >>>\n");
                if (GetAsyncKeyState(forward) == 0){
                    cout << ("Stopped\n");
                }
             }
             if (GetAsyncKeyState(VK_SPACE) < 0){break;}
         }
}
int main() {
Move move;
move.move();
}

Sorry, but I don't think I understand the whole logic of this yet.

PS UPDATE:

How can I override baseKeys values:

class MovementKeys {
protected:
    int baseKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right){
        default_key_forward = VK_UP;
        default_key_backward = VK_DOWN;
        default_key_left = VK_LEFT;
        default_key_right = VK_RIGHT;
    }
public:
    int definedCommand(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
        while (reset_defaults == false)
        {
            cout << ("HERE 1 \n");
            if (GetAsyncKeyState(default_key_forward) < 0)
            {
                cout << ("forward\n");
            }
            if (GetAsyncKeyState(default_key_backward) < 0)
            {
                court << ("backwards\n");
            }
            if (GetAsyncKeyState(default_key_left) < 0)
            {
                cout << ("left\n");
            }
            if (GetAsyncKeyState(default_key_right) < 0)
            {
                cout << ("right\n");
            }
            if (GetAsyncKeyState(VK_SPACE) < 0) { break; }

        }
        return 0;
    }
    int derived_newKeys(int default_key_forward, int default_key_backward, int default_key_left, int default_key_right) {
        return baseKeys(default_key_forward, default_key_backward, default_key_left, default_key_right);
    }

Body:
You probably want to use member variables to store the keys. Instead of deriving the class with new keys, you set the variables in constructors (to default or to changed values) and can also change the key assignment later on.

You probably want to create a separate class, which reacts on the events.

#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

class World {
    public:
        void forward() { y--; };
        void backward() { y++; };
        void left() { x--; };
        void right() { x++; };

    private:
        int x = 0;
        int y = 0;
};

class MovementKeys {
// member variables
private:
    // keep reference to world instead of copy; main() has to make sure World object outlives MovementKeys object
    World& world;

    int key_forward;
    int key_backward;
    int key_left;
    int key_right;

public:
    // constructor, which only sets world, but keeps the keys at their default settings
    //
    // world has to be initialized before the constructor function body
    // as references have no default value
    // put initialization in member initialization list

    MovementKeys(World& w) : world(w)
    {
        key_forward = VK_UP;
        key_backward = VK_DOWN;
        key_left = VK_LEFT;
        key_right = VK_RIGHT;
    }

    // constructor which modifies keys
    MovementKeys(World& w, int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : world(w)
    {
        changeKeys(change_key_forward, change_key_backward, change_key_left, change_key_right);
    }

    // command loop controlled by keys
    int definedCommand()
    {
        while (true)
        {
            cout << ("HERE 1 \n");
            if (GetAsyncKeyState(key_forward) < 0)
            {
                cout << ("forward\n");
                world.forward();
            }
            if (GetAsyncKeyState(key_backward) < 0)
            {
                cout << ("backwards\n");
                world.backward();
            }
            if (GetAsyncKeyState(key_left) < 0)
            {
                cout << ("left\n");
                world.left();
            }
            if (GetAsyncKeyState(key_right) < 0)
            {
                cout << ("right\n");
                world.right();
            }
            // optionally change keys from within while loop
            if (GetAsyncKeyState(VK_BACK) < 0)
            {
                key_forward = VK_RETURN;
            }
            if (GetAsyncKeyState(VK_SPACE) < 0)
            {
                break;
            }
        }
        return 0;
    }

    // function for changing the keys stored in the member variables
    // can be called by constructor or externally
    void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
    {
        key_forward = change_key_forward;
        key_backward = change_key_backward;
        key_left = change_key_left;
        key_right = change_key_right;
    }
};

int main()
{
    World earth;

    // use default keys, declares local variable and constructs MovementKeys object called move
    MovementKeys move(earth);
    move.definedCommand();

    // use custom keys, share same world, declares local variable and constructs MovementKeys object called move2
    // static_cast<int>() with a letter in a literal char parameter works, because the VK_ values of letter keys are the actual ASCII values (on purpose by Microsoft, I would assume)
    MovementKeys move2(earth, static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));
    move2.definedCommand();

    // change keys in move2
    move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
    move2.definedCommand();

    // run first one again for the fun of it
    move.definedCommand();
}

Alternatively passing World& only, where it is used in definedCommand (and at the same time be able to use several worlds):

class World {
    // ...
};

class MovementKeys {
// member variables without world, we can also put default value here
private:
    int key_forward = VK_UP;
    int key_backward = VK_DOWN;
    int key_left = VK_LEFT;
    int key_right = VK_RIGHT;

public:
    // default constructor with no parameters, delegate to other constructor
    // delegating not necessary, as the default values are set above anyway; just demonstrating various techniques for initializing member variables
    MovementKeys() : MovementKeys(VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT) {};

    // constructor which modifies keys, put everything in member initialization list
    MovementKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right) : key_forward(change_key_forward), key_backward(change_key_backward), key_left(change_key_left), key_right(change_key_right) {};

    // command loop controlled by keys, pass World& here as parameter
    int definedCommand(World& world)
    {
        while (true)
        {
           // ...
        }
        return 0;
    }

    void changeKeys(int change_key_forward, int change_key_backward, int change_key_left, int change_key_right)
    {
        // ...
    }
};

int main()
{
    // use default keys, declares local variable and constructs MovementKeys object called move
    MovementKeys move;

    // use custom keys, declares local variable and constructs MovementKeys object called move2
    MovementKeys move2(static_cast<int>('W'), static_cast<int>('S'), static_cast<int>('A'), static_cast<int>('D'));

    MovementKeys defaultMenuKeys;

    World earth;
    World moon;
    World menu; // between moving in worlds, we want to control some settings in a menu

    move.definedCommand(earth);
    move2.definedCommand(earth);
    move2.definedCommand(moon);

    // change keys in move2
    move2.changeKeys(VK_LBUTTON, VK_RBUTTON, VK_CONTROL, VK_SHIFT);
    move2.definedCommand(earth);

    defaultMenuKeys.definedCommand(menu);

    // run first one again for the fun of it
    move.definedCommand(moon);
}

You can introduce a (class) enum with a list of the states, why definedCommand() returns:

// outside or can be put into MovementKeys and henceforth used as MovementKeys::ReturnReason
class enum ReturnReason { EXIT, NEWKEYS, SHOWMENU, SWITCHWORLD };

// in class MovementKeys
ReturnReason definedCommand() {
    // ...
    return NEWKEYS;
    // ...
    return EXIT;
    // ...
    return SHOWMENU;
    // ...
}

// in main()
ReturnReason r = definedCommand();
if (r == NEWKEYS)
    move2.changeKeys(...);
else if (r == EXIT)
    return 0;

If you use that 'trick' to also control the menu, it could make sense to use virtual inheritance now for World. As the normal World and the menu World probably react quite differently. (The base class (ancestor) would be World, which is recognized by MovementKeys. Your actual Worlds are objects of derived (children) classes, with more specific behaviour.

definedCommand then can be called and run with any derived class of the base class World.


问:
Dealing with object return from axios
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

```<code>async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},
</code>```

My componnent data is:

```<code>data() {
    return {
        posts: {}
    }
},
</code>```

My v-for is:

```<code><article v-for="(post, index) in posts" :key="index">
</code>```

And the error I'm getting is:

```<code>[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"
</code>```

If I fill my componnent data with the json as object manually works fine, example:

```<code>data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},
</code>```

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.

答:
After read a lot of similar situations here and on social networks, have found this one:

Object assignment in Vue.js method

Then I have tried make the default values for component data like docs sayed to do:

https://v2.vuejs.org/v2/guide/reactivity.html?redirect=true#Declaring-Reactive-Properties

Other errors come out.

After some tries debugging (removing items from object one by one), have found in the original component there a lot of v-for and nuxt-link.

Inside v-for will drop errors on some situations.

Inside nuxt-link will not accept null (empty default object) or blank values.

Conclusion:

Seems I will need validate the entire object / array always and in the end force an Object.assign. Since I haven't made the API yet, solution will be hardcode an json file to read local.

Title: Dealing with object return from axios

Body:
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},

My componnent data is:

data() {
    return {
        posts: {}
    }
},

My v-for is:

And the error I'm getting is:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"

If I fill my componnent data with the json as object manually works fine, example:

data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.


问:
How to use neovim lsp keybindings?
I have neovim 0.6.1 configured with some LSPs and using the default configurations found here: https://github.com/neovim/nvim-lspconfig#suggested-configuration. Some of the key bindings such as vim.api.nvim_buf_set_keymap(bufnr, 'n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) are not working.

The vim.lsp.buf.rename() command works correctly if I call it manually like :lua vim.lsp.buf.rename().

If I do :noremap <space>rn :lua vim.lsp.buf.rename()<CR> during a session the rename keybinding works correctly.

答: The default config from nvim-cmp was also calling setup{} which effectively cleared the on_attach callback required to enable the lsp keybindings.</p>

Title: How to use neovim lsp keybindings?


问:
How to read data from the downloaded excel file content from Google drive api in Dart/Flutter?
I am using google drive API to download an excel file in my Flutter app but I want to store the downloaded file content response in a File and then do some update operations using excel dart package, below is the given code from reading an xlsx file from a path location.

```<code>    var file = "Path_to_pre_existing_Excel_File/excel_file.xlsx";  //here I want to store the response from drive api
    var bytes = File(file).readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);

    //Do some logic here
    for (var table in excel.tables.keys) {
      print(table); //sheet Name
      print(excel.tables[table].maxCols);
      print(excel.tables[table].maxRows);
      for (var row in excel.tables[table].rows) {
        print("$row");
      }
    }

    //then saving the excel file

    // updating the excel sheet to Drive
     updateToDrive(excel,fileId);
</code>```

I have created all the required auth functions, drive scopes and my download function looks like this :

```<code>Future<void> downloadFile() async{

  String fileId = '1TOa4VKfZBHZe######WLA4M95nOWp';
  final response = await driveApi.files.get(
      fileId,
      downloadOptions: drive.DownloadOptions.fullMedia
  );
  print(response);

}
</code>```

This function is executing correctely and giving Media type response, but I could not able to read this response so that I could store it in a file.
Any help would be truly appreciated, Thanks

答:
I changed my download function to this, as drive.files.get() was returning a Future Object so I changed it to return Future<Media?> by type casting.

```<code>String fileId = "19jF3lOVW563LU6m########jXVLNQ7poXY1Z";
  drive.Media? response = (await driveApi.files.get(
      fileId,
      downloadOptions: drive.DownloadOptions.fullMedia
  )) as drive.Media?;
</code>```

Now response is a Media on which we can listen to the sream to store the response in  a file.
To do that first we need to get the app directory by path_provider

```<code>final String path = (await getApplicationSupportDirectory()).path;
final String fileName = '$path/Output.xlsx';
File file = File(fileName);
</code>```

Now we want to write the stream of response Stream<List> into our file object which I found from this link

```<code>List<int> dataStore = [];
  await response!.stream.listen((data) {
    print("DataReceived: ${data.length}");
    dataStore.insertAll(dataStore.length, data);
  }, onDone: () {
    print("Task Done");
    file.writeAsBytes(dataStore);
    OpenFile.open(file.path);
    print("File saved at ${file.path}");
  }, onError: (error) {
    print("Some Error");
  });
</code>```

Now we can do whatever we want to make changes through excel package.

Body:
I am using google drive API to download an excel file in my Flutter app but I want to store the downloaded file content response in a File and then do some update operations using excel dart package, below is the given code from reading an xlsx file from a path location.

    var file = "Path_to_pre_existing_Excel_File/excel_file.xlsx";  //here I want to store the response from drive api
    var bytes = File(file).readAsBytesSync();
    var excel = Excel.decodeBytes(bytes);

    //Do some logic here
    for (var table in excel.tables.keys) {
      print(table); //sheet Name
      print(excel.tables[table].maxCols);
      print(excel.tables[table].maxRows);
      for (var row in excel.tables[table].rows) {
        print("$row");
      }
    }

    //then saving the excel file

    // updating the excel sheet to Drive
     updateToDrive(excel,fileId);

I have created all the required auth functions, drive scopes and my download function looks like this :

Future<void> downloadFile() async{

  String fileId = '1TOa4VKfZBHZe######WLA4M95nOWp';
  final response = await driveApi.files.get(
      fileId,
      downloadOptions: drive.DownloadOptions.fullMedia
  );
  print(response);

}

This function is executing correctely and giving Media type response, but I could not able to read this response so that I could store it in a file.
Any help would be truly appreciated, Thanks

Body:
I changed my download function to this, as drive.files.get() was returning a Future Object so I changed it to return Future<Media?> by type casting.

String fileId = "19jF3lOVW563LU6m########jXVLNQ7poXY1Z";
  drive.Media? response = (await driveApi.files.get(
      fileId,
      downloadOptions: drive.DownloadOptions.fullMedia
  )) as drive.Media?;

Now response is a Media on which we can listen to the sream to store the response in  a file.
To do that first we need to get the app directory by path_provider

final String path = (await getApplicationSupportDirectory()).path;
final String fileName = '$path/Output.xlsx';
File file = File(fileName);

Now we want to write the stream of response Stream<List> into our file object which I found from this link

List<int> dataStore = [];
  await response!.stream.listen((data) {
    print("DataReceived: ${data.length}");
    dataStore.insertAll(dataStore.length, data);
  }, onDone: () {
    print("Task Done");
    file.writeAsBytes(dataStore);
    OpenFile.open(file.path);
    print("File saved at ${file.path}");
  }, onError: (error) {
    print("Some Error");
  });

Now we can do whatever we want to make changes through excel package.


问:
Is the C# static constructor thread safe?
In other words, is this Singleton implementation thread safe:</p>

```<code>public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}
</code>```

答:
Using a static constructor actually is threadsafe.  The static constructor is guaranteed to be executed only once.

From the C# language specification:

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

An instance of the class is created.

Any of the static members of the class are referenced.

So yes, you can trust that your singleton will be correctly instantiated.

Zooba made an excellent point (and 15 seconds before me, too!) that the static constructor will not guarantee thread-safe shared access to the singleton.  That will need to be handled in another manner.

ContentLicense: CC BY-SA 2.5

Body:
In other words, is this Singleton implementation thread safe:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}

LastEditorDisplayName: Derek Park


问:
Help in creating Zip files from .Net and reading them from Java
I'm trying to create a Zip file from .Net that can be read from Java code.

I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.

Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see http://community.sharpdevelop.net/forums/t/8272.aspx for info) but with no result.

Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?

Regards
Massimo

答: Can't help with SharpZipLib, but you can try to create zip file using ZipPackage class System.IO.Packaging without using 3rd part libraries (requires .NET 3+).</p>

OwnerDisplayName: massimogentilini

OwnerDisplayName: aku


问:
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?

We already have a WAMP stack setup on a Windows Server 2003 box to support some internal PHP applications, and I want to also setup CI Factory on that box which will try to configure IIS to support it's ASP.NET based dashboard.  I want to make sure that there isn't a big chance of fubarring the WAMP stack that is already there.  Will it be smart enough to handle *.PHP through Apache and *.aspx through IIS ?

Edit: Is there a way to get this to work on the same port?

答: It's certainly possible. I have IIS+ASP+MSSQL and XAMPP (apache+PHP+MySQL) installed on my development machine and both of them don't interrupt work of another another. Atleast while different ports are used</p>

OwnerDisplayName: aaronls

LastEditorDisplayName: aaronls

OwnerDisplayName: Sergej Andrejev