问:
React Native Error - TypeError: undefined is not an object (evaluating 'item.key')
I am trying to use APIs from this website for my React Native App: https://api.spacexdata.com/v2/launches

I tried to follow the APIs from the JSON formatter closely, but receive the following error and do not know how to resolve it:

```<code>TypeError: undefined is not an object (evaluating 'item.key')

This error is located at:
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at App.js:42)
    in App
    in ExpoRoot (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in DevAppContainer (at AppContainer.js:115)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)

defaultProps.keyExtractor
    VirtualizedList.js:467:15
_pushCells
    VirtualizedList.js:761:31
_pushCells
    VirtualizedList.js:759:13
render
    VirtualizedList.js:871:8
renderRoot
    [native code]:0
runRootCallback
    [native code]:0
Component.prototype.setState
    react.development.js:325:31
tryCallOne
    core.js:37:14
setImmediate$argument_0
    core.js:123:25
callImmediates
    [native code]:0
flushedQueue
    [native code]:0
invokeCallbackAndReturnFlushedQueue
    [native code]:0
</code>```

my code in App.js is as below..

```<code> import React from 'react'; import { ActivityIndicator, FlatList,
 Image, StyleSheet, Text, View } from 'react-native'; import { Card,
 CardItem, Item } from 'native-base'

 export default class App extends React.Component {

   constructor(propos) {
     super(propos);
     this.state = {
       isLoading: true,
       dataSource: []
     };   }

   getUserFromAPI = () => {
     return fetch('https://api.spacexdata.com/v2/launches')
       .then(response => response.json())
       .then(responseJson => {
         this.setState({
           isLoading: false,
           dataSource: this.state.dataSource.concat(responseJson.array)
         });
       })
       .catch(error => console.log(error));   };   _keyExtractor = (datasource, index) => datasource.id;   componentDidMount() {
     this.getUserFromAPI();   }

   render() {
     if (this.state.isLoading) {
       return (
         <View style={styles.progress}>
           <ActivityIndicator size="large" color="#01CBC6" />
         </View>

       );
     }

     return (
       <FlatList
         data={this.state.dataSource}
         _keyExtractor={this._keyExtractor}
         renderItem={({ item }) => (
           <Card>
             <CardItem>
               <View style={styles.container}>
                 <Image style={styles.profilepic}
                   source={{
                     uri: item.links.mission_patch
                     // from API docs
                   }}
                 />
               </View>
               <View style={styles.userinfo}>
                 <Text>
                   Flight Number: {item.flight_number} {", Mission Name: "} {item.mission_name}
                 </Text>
                 <Text>
                   Launch date (UTC): {item.mission_id.launch_date_utc}
                 </Text>
                 <Text>
                   {item.rocket.rocket_name}
                 </Text>
                 <Text>
                   Launch Site: {item.launch_site.site_name_long}
                 </Text>
                 <Text>
                   Details: {item.details}
                   Crew: {item.crew}
                 </Text>
               </View>
             </CardItem>
           </Card>
         )}
       />
     );   } }
</code>```

My code for styling is as below:

```<code> const styles = StyleSheet.create({   container: {
     flex: 1,
     backgroundColor: '#fff',
     alignItems: 'center',
     justifyContent: 'center'   },   profilepic: {
     flex: 2,
     height: 100,
     width: 100   },   userinfo: {
     flex: 5,
     flexDirection: 'column',
     marginStart: 50   },   progress: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center'   }

 });
</code>```

Thanks very much.

答:
You need to make two changes

change _keyExtractor={this._keyExtractor} to keyExtractor={this._keyExtractor}

in keyExtaractor function use flightNumber key instead of item.key like this _keyExtractor=(item)=>item.flightNumber;

Body:
I am trying to use APIs from this website for my React Native App: https://api.spacexdata.com/v2/launches

I tried to follow the APIs from the JSON formatter closely, but receive the following error and do not know how to resolve it:

TypeError: undefined is not an object (evaluating 'item.key')

This error is located at:
    in VirtualizedList (at FlatList.js:676)
    in FlatList (at App.js:42)
    in App
    in ExpoRoot (at renderApplication.js:40)
    in RCTView (at AppContainer.js:101)
    in DevAppContainer (at AppContainer.js:115)
    in RCTView (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:39)

defaultProps.keyExtractor
    VirtualizedList.js:467:15
_pushCells
    VirtualizedList.js:761:31
_pushCells
    VirtualizedList.js:759:13
render
    VirtualizedList.js:871:8
renderRoot
    [native code]:0
runRootCallback
    [native code]:0
Component.prototype.setState
    react.development.js:325:31
tryCallOne
    core.js:37:14
setImmediate$argument_0
    core.js:123:25
callImmediates
    [native code]:0
flushedQueue
    [native code]:0
invokeCallbackAndReturnFlushedQueue
    [native code]:0

my code in App.js is as below..

 import React from 'react'; import { ActivityIndicator, FlatList,
 Image, StyleSheet, Text, View } from 'react-native'; import { Card,
 CardItem, Item } from 'native-base'

 export default class App extends React.Component {

   constructor(propos) {
     super(propos);
     this.state = {
       isLoading: true,
       dataSource: []
     };   }

   getUserFromAPI = () => {
     return fetch('https://api.spacexdata.com/v2/launches')
       .then(response => response.json())
       .then(responseJson => {
         this.setState({
           isLoading: false,
           dataSource: this.state.dataSource.concat(responseJson.array)
         });
       })
       .catch(error => console.log(error));   };   _keyExtractor = (datasource, index) => datasource.id;   componentDidMount() {
     this.getUserFromAPI();   }

   render() {
     if (this.state.isLoading) {
       return (
         <View style={styles.progress}>
           <ActivityIndicator size="large" color="#01CBC6" />
         </View>

       );
     }

     return (
       <FlatList
         data={this.state.dataSource}
         _keyExtractor={this._keyExtractor}
         renderItem={({ item }) => (
           <Card>
             <CardItem>
               <View style={styles.container}>
                 <Image style={styles.profilepic}
                   source={{
                     uri: item.links.mission_patch
                     // from API docs
                   }}
                 />
               </View>
               <View style={styles.userinfo}>
                 <Text>
                   Flight Number: {item.flight_number} {", Mission Name: "} {item.mission_name}
                 </Text>
                 <Text>
                   Launch date (UTC): {item.mission_id.launch_date_utc}
                 </Text>
                 <Text>
                   {item.rocket.rocket_name}
                 </Text>
                 <Text>
                   Launch Site: {item.launch_site.site_name_long}
                 </Text>
                 <Text>
                   Details: {item.details}
                   Crew: {item.crew}
                 </Text>
               </View>
             </CardItem>
           </Card>
         )}
       />
     );   } }

My code for styling is as below:

 const styles = StyleSheet.create({   container: {
     flex: 1,
     backgroundColor: '#fff',
     alignItems: 'center',
     justifyContent: 'center'   },   profilepic: {
     flex: 2,
     height: 100,
     width: 100   },   userinfo: {
     flex: 5,
     flexDirection: 'column',
     marginStart: 50   },   progress: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center'   }

 });

Thanks very much.


来源: stackexchange

问:
Firebase functions not working with axios
```<code>const functions = require('firebase-functions')
const axios = require('axios')

exports.getTown = functions.https.onCall((data, context) => {

    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${data.lat},${data.lng}&result_type=locality&key=**********`)
    .then(town => {
        return town
    }).catch(err => {
        return err
    })

})
</code>```

When I call this in the front end I just get an error in the console:

```<code>POST https://europe-west2-heretic-hearts.cloudfunctions.net/getTown 500
Uncaught (in promise) Error: INTERNAL
</code>```

I've tested to make sure the incoming data is being received properly and it is, so the problem must be in the function itself. But I can't see what could possibly be going wrong here...?

答:
You can't invoke an onCall type function with a simple POST request.  Callable functions have a specific protocol that they use on top of HTTP.  If you can't reproduce that protocol, the function will fail every time.

If you want to write a simple HTTP function endpoint, then follow the instruction for writing an HTTP trigger instead using onRequest.  It works very differently.

Also, I'm noticing that you're not handling promises correctly in your function.  Please read the documentation thoroughly to understand what you need to do with promises in order to get your function to execute correctly, no matter what type of function you write.

ContentLicense: CC BY-SA 4.0

Body:
const functions = require('firebase-functions')
const axios = require('axios')

exports.getTown = functions.https.onCall((data, context) => {

    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${data.lat},${data.lng}&result_type=locality&key=**********`)
    .then(town => {
        return town
    }).catch(err => {
        return err
    })

})

When I call this in the front end I just get an error in the console:

POST https://europe-west2-heretic-hearts.cloudfunctions.net/getTown 500
Uncaught (in promise) Error: INTERNAL

I've tested to make sure the incoming data is being received properly and it is, so the problem must be in the function itself. But I can't see what could possibly be going wrong here...?


问:
The Image uploading functionality is not working properly for me
I am using this code with the help of one tutorial, but still i am unable to upload the image, i mean the image is not appearing, please someone help me on this

This is the code I have used:-

```<code><div class="col-md-6">
    <div class="form-group">
        @Html.LabelFor(model => model.ImgPath, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <img src="@Url.Content(Model.ImgPath)" style="margin:10px" height="200" width="200" id="imagePreview" />
            <input type="file" name="ImageUpload" accept="image/jpeg, image/png" onchange="ShowImagePreview(this, document.getElementById('imagePreview')" />
        </div>
    </div>
</div>
</code>```

答:
If your image is not uploading, i think you should check you form tag and make it something like this

```<code><form method="post" enctype="multipart/form-data">
//your image upload
<input type="file" name="ImageUpload" accept="image/jpeg, image/png" />
</form>
</code>```

then you can use the
Request.Files
and access all the files sent or if you want it strongly embedded use

```<code>//this for Asp.Net Core
public IActionResult(IFormFile ImageUpload)
{
   //Everything here
}

//Or this for Asp.Net
public ActionResult(HttpPostedFileBase ImageUpload)
{
   //Everything else here
}
</code>```

Read this stackoverflow post to understand about it

Body:
I am using this code with the help of one tutorial, but still i am unable to upload the image, i mean the image is not appearing, please someone help me on this

This is the code I have used:-

        @Html.LabelFor(model => model.ImgPath, htmlAttributes: new { @class = "control-label col-md-2" })

            <input type="file" name="ImageUpload" accept="image/jpeg, image/png" onchange="ShowImagePreview(this, document.getElementById('imagePreview')" />

Body:
If your image is not uploading, i think you should check you form tag and make it something like this

<form method="post" enctype="multipart/form-data">
//your image upload
<input type="file" name="ImageUpload" accept="image/jpeg, image/png" />
</form>

then you can use the
Request.Files
and access all the files sent or if you want it strongly embedded use

//this for Asp.Net Core
public IActionResult(IFormFile ImageUpload)
{
   //Everything here
}

//Or this for Asp.Net
public ActionResult(HttpPostedFileBase ImageUpload)
{
   //Everything else here
}

Read this stackoverflow post to understand about it


问:
How to assign a new value for class variable from class methods?
```<code>x = int(input("enter x:"))
class hello:
    var = x

h = hello()

print(hello.var)
</code>```

Test run:

```<code>enter x:15
15
</code>```

How to access the static variable from the methods of the class? I'm stuck at this one

答:
You can define a class method to set class variables</p>

```<code>x = int(input("enter x:"))

class hello:
    var = x

    @classmethod
    def set_var(cls, value):
        cls.var = value

h = hello()
print(hello.var, h.var)
h.set_var('I am new var')
print(hello.var, h.var)
</code>```

Body:
x = int(input("enter x:"))
class hello:
    var = x

h = hello()

print(hello.var)

Test run:

enter x:15
15

How to access the static variable from the methods of the class? I'm stuck at this one

Body:
You can define a class method to set class variables

x = int(input("enter x:"))

class hello:
    var = x

    @classmethod
    def set_var(cls, value):
        cls.var = value

h = hello()
print(hello.var, h.var)
h.set_var('I am new var')
print(hello.var, h.var)


问:
How matplotlib calculate the value of lower and upper extreme in boxplot?
I tried to understand how matplotlib draws a graph. This is the code that I write.

```<code>import matplotlib.pyplot as plt
import pandas as pd

age=[20,22,22,23,23,23,23,24,24,24,24,26,26,30]
df=pd.DataFrame(age, columns=['age'])
df['age'].describe()
</code>```

This is the data printed out

```<code>count    14.000000
mean     23.857143
std       2.348720
min      20.000000
25%      23.000000
50%      23.500000
75%      24.000000
max      30.000000
Name: age, dtype: float64
</code>```

I calculated the value IQR, L, U

```<code>IQR = Q3 - Q1= 24 – 23 = 1
L = Q1 – 1.5 * IQR = 23 – 1.5 * 1 = 21.5
U = Q3 + 1.5 * IQR = 24 + 1.5 * 1 = 25.5
</code>```

However, the graph generated by matplotlib is different from what I calculate:

```<code>df.boxplot(column = ['age'])
</code>```

The value of L and U extreme is 22 and 24 (not 21.5 and 25.5)

What is the formula for L and U (lower and upper extreme) that matplotlib uses?

Thanks a lot for pointing out my mistakes?

答:
The values you calculated are the bounds, and not L and U.

L and U are the mimimum/maximum points from the data that are within 1.5 IQR from Q1/Q3.

You calculate 21.5 as the lower bound, but the smallest point in your data that is greater than or equal that bound is 22.

Similarly, the upper bound you calculated is 25.5, but the largest point in your data that is less than or equal that bound is 24

Body:
I tried to understand how matplotlib draws a graph. This is the code that I write.

import matplotlib.pyplot as plt
import pandas as pd

age=[20,22,22,23,23,23,23,24,24,24,24,26,26,30]
df=pd.DataFrame(age, columns=['age'])
df['age'].describe()

This is the data printed out

count    14.000000
mean     23.857143
std       2.348720
min      20.000000
25%      23.000000
50%      23.500000
75%      24.000000
max      30.000000
Name: age, dtype: float64

I calculated the value IQR, L, U

IQR = Q3 - Q1= 24 – 23 = 1
L = Q1 – 1.5 * IQR = 23 – 1.5 * 1 = 21.5
U = Q3 + 1.5 * IQR = 24 + 1.5 * 1 = 25.5

However, the graph generated by matplotlib is different from what I calculate:

df.boxplot(column = ['age'])

The value of L and U extreme is 22 and 24 (not 21.5 and 25.5)

What is the formula for L and U (lower and upper extreme) that matplotlib uses?

Thanks a lot for pointing out my mistakes?


问:
Bind Control to DependancyProperty of container control
I have created a UserControl in Silverlight and added some dependency properties to it to expose selected options in the control to any other controls that use my control, how do I bind properties of something like a ListBox used in my control to the dependency properties of my control? I am currently using ElementBinding but I'm not too fond of ElementBinding in general... I was hoping there is some sort of relative binding but relative binding doesn't seem to provide the options I am looking for (but I don't think I actually understand relative binding very well)</p>

答:
So you have a UserControl tha contains a ListBox, and you wish to expose your ListBox selected items from your UserControl?

I can think of a few options ...

Set the DataContext of the 'LayoutRoot' of your UserControl to itself, as in this example, you can then bind the ListBox.SelectedItem to your corresponding property on your UserControl.

Use a ReltiveSource FindAncestor binding to navigate up the visual tree from your ListBox to your UserControl.

Use an ElementName binding, by giving your UserControl a name and referencing that in your ListBox binding.

Personally I favour (1), typically there will be more that one property you want to expose, making this the simplest solution.

ContentLicense: CC BY-SA 3.0


问:
How to run Ansible playbook conditionally?
how do i run some playbooks based on condition. I will explain my current scenario -
I have a main yml - main.yml which is importing 4 playbooks with conditions as below -

```<code>---
- import_playbook: current-deployment-status.yml

- import_playbook: current-config-status.yml

- import_playbook: full-deployment.yml
  when: target_release_version != current_release

- import_playbook: only-config-change.yml
  #when: config_var.changed  == true and target_release_version == current_release
</code>```

The 1st playbook current-deployment-status.yml gets the current release version deployed and register a variable current_release.
Likewise the 2nd playbook do some configuration checks and registers into a variable config_var.

Now based on these 2 variables, I have to execute my further playbooks. If target_release_version == current_release then I don't want to do the deployment so only execute full-deployment.yml when condition meets as above.

Likewise, if there is only configuration change required and no deployment : config_var.changed  == true and target_release_version == current_release, then execute only-config-change.yml

Is there a way to execute the playbook only when condition meets otherwise skip it and proceed further.

Please let me know if someone can guide me in the right direction

答:
Yes you can achieve it using set_facts ansible module.

main.yml

```<code>---
- import_playbook: current-deployment-status.yml

- import_playbook: current-config-status.yml

- import_playbook: full-deployment.yml
  when: target_release_version != current_release

- import_playbook: only-config-change.yml
  when: config_var.changed  == true and target_release_version == current_release
</code>```

current-deployment-status.yml

```<code>- name : Playbook current-deployment-status
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "current-deployment-status.yml"

    - set_fact:
        current_release: "2"
</code>```

current-config-status.yml

```<code>- name : Playbook current-config-status.yml
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "current-config-status.yml"

    - name: task2
      shell: echo "another task"
      register: config_var

    - debug: msg="{{config_var.changed}}"
</code>```

full-deployment.yml

```<code>- name : Playbook
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "full_deployment.yml"
</code>```

only-config-change.yml

```<code>- name : Playbook only-config-change.yml
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "only-config-change.yml"
</code>```

ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=2"

```<code>ubuntu@ip-172-31-38-43:~/ansible_test$ ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=2"
PLAY [Playbook current-deployment-status] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-deployment-status.yml\"", "delta": "0:00:00.002429", "end": "2020-05-31 16:46:29.900240", "rc": 0, "start": "2020-05-31 16:46:29.897811", "stderr": "", "stderr_lines": [], "stdout": "current-deployment-status.yml", "stdout_lines": ["current-deployment-status.yml"]}

TASK [set_fact] *************************************************************************************************************************
ok: [172.31.6.248] => {"ansible_facts": {"current_release": "2"}, "changed": false}

PLAY [Playbook current-config-status.yml] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-config-status.yml\"", "delta": "0:00:00.002484", "end": "2020-05-31 16:46:30.776486", "rc": 0, "start": "2020-05-31 16:46:30.774002", "stderr": "", "stderr_lines": [], "stdout": "current-config-status.yml", "stdout_lines": ["current-config-status.yml"]}

TASK [task2] ****************************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"another task\"", "delta": "0:00:00.002473", "end": "2020-05-31 16:46:31.048677", "rc": 0, "start": "2020-05-31 16:46:31.046204", "stderr": "", "stderr_lines": [], "stdout": "another task", "stdout_lines": ["another task"]}

TASK [debug] ****************************************************************************************************************************
ok: [172.31.6.248] => {
    "msg": true
}

PLAY [Playbook full_deployment.yml] *****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

TASK [echo playbook name] ***************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

PLAY [Playbook only-config-change.yml] **************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"only-config-change.yml\"", "delta": "0:00:00.002585", "end": "2020-05-31 16:46:32.017156", "rc": 0, "start": "2020-05-31 16:46:32.014571", "stderr": "", "stderr_lines": [], "stdout": "only-config-change.yml", "stdout_lines": ["only-config-change.yml"]}

PLAY RECAP ******************************************************************************************************************************
172.31.6.248               : ok=9    changed=4    unreachable=0    failed=0
</code>```

ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=3"

```<code>PLAY [Playbook current-deployment-status] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-deployment-status.yml\"", "delta": "0:00:00.002490", "end": "2020-05-31 16:48:28.611482", "rc": 0, "start": "2020-05-31 16:48:28.608992", "stderr": "", "stderr_lines": [], "stdout": "current-deployment-status.yml", "stdout_lines": ["current-deployment-status.yml"]}

TASK [set_fact] *************************************************************************************************************************
ok: [172.31.6.248] => {"ansible_facts": {"current_release": "2"}, "changed": false}

PLAY [Playbook current-config-status.yml] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-config-status.yml\"", "delta": "0:00:00.002565", "end": "2020-05-31 16:48:29.440319", "rc": 0, "start": "2020-05-31 16:48:29.437754", "stderr": "", "stderr_lines": [], "stdout": "current-config-status.yml", "stdout_lines": ["current-config-status.yml"]}

TASK [task2] ****************************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"another task\"", "delta": "0:00:00.002459", "end": "2020-05-31 16:48:29.703006", "rc": 0, "start": "2020-05-31 16:48:29.700547", "stderr": "", "stderr_lines": [], "stdout": "another task", "stdout_lines": ["another task"]}

TASK [debug] ****************************************************************************************************************************
ok: [172.31.6.248] => {
    "msg": true
}

PLAY [Playbook full_deployment.yml] *****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"full_deployment.yml\"", "delta": "0:00:00.002509", "end": "2020-05-31 16:48:30.610648", "rc": 0, "start": "2020-05-31 16:48:30.608139", "stderr": "", "stderr_lines": [], "stdout": "full_deployment.yml", "stdout_lines": ["full_deployment.yml"]}

PLAY [Playbook only-config-change.yml] **************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

TASK [echo playbook name] ***************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

PLAY RECAP ******************************************************************************************************************************
172.31.6.248               : ok=9    changed=4    unreachable=0    failed=0
</code>```

Body:
how do i run some playbooks based on condition. I will explain my current scenario -
I have a main yml - main.yml which is importing 4 playbooks with conditions as below -

---
- import_playbook: current-deployment-status.yml

- import_playbook: current-config-status.yml

- import_playbook: full-deployment.yml
  when: target_release_version != current_release

- import_playbook: only-config-change.yml
  #when: config_var.changed  == true and target_release_version == current_release

The 1st playbook current-deployment-status.yml gets the current release version deployed and register a variable current_release.
Likewise the 2nd playbook do some configuration checks and registers into a variable config_var.

Now based on these 2 variables, I have to execute my further playbooks. If target_release_version == current_release then I don't want to do the deployment so only execute full-deployment.yml when condition meets as above.

Likewise, if there is only configuration change required and no deployment : config_var.changed  == true and target_release_version == current_release, then execute only-config-change.yml

Is there a way to execute the playbook only when condition meets otherwise skip it and proceed further.

Please let me know if someone can guide me in the right direction

Body:
Yes you can achieve it using set_facts ansible module.

main.yml

---
- import_playbook: current-deployment-status.yml

- import_playbook: current-config-status.yml

- import_playbook: full-deployment.yml
  when: target_release_version != current_release

- import_playbook: only-config-change.yml
  when: config_var.changed  == true and target_release_version == current_release

current-deployment-status.yml

- name : Playbook current-deployment-status
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "current-deployment-status.yml"

    - set_fact:
        current_release: "2"

current-config-status.yml

- name : Playbook current-config-status.yml
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "current-config-status.yml"

    - name: task2
      shell: echo "another task"
      register: config_var

    - debug: msg="{{config_var.changed}}"

full-deployment.yml

- name : Playbook
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "full_deployment.yml"

only-config-change.yml

- name : Playbook only-config-change.yml
  hosts: all
  user: ubuntu
  gather_facts: True

  tasks:
    - name: echo playbook name
      shell: echo "only-config-change.yml"

ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=2"

ubuntu@ip-172-31-38-43:~/ansible_test$ ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=2"
PLAY [Playbook current-deployment-status] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-deployment-status.yml\"", "delta": "0:00:00.002429", "end": "2020-05-31 16:46:29.900240", "rc": 0, "start": "2020-05-31 16:46:29.897811", "stderr": "", "stderr_lines": [], "stdout": "current-deployment-status.yml", "stdout_lines": ["current-deployment-status.yml"]}

TASK [set_fact] *************************************************************************************************************************
ok: [172.31.6.248] => {"ansible_facts": {"current_release": "2"}, "changed": false}

PLAY [Playbook current-config-status.yml] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-config-status.yml\"", "delta": "0:00:00.002484", "end": "2020-05-31 16:46:30.776486", "rc": 0, "start": "2020-05-31 16:46:30.774002", "stderr": "", "stderr_lines": [], "stdout": "current-config-status.yml", "stdout_lines": ["current-config-status.yml"]}

TASK [task2] ****************************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"another task\"", "delta": "0:00:00.002473", "end": "2020-05-31 16:46:31.048677", "rc": 0, "start": "2020-05-31 16:46:31.046204", "stderr": "", "stderr_lines": [], "stdout": "another task", "stdout_lines": ["another task"]}

TASK [debug] ****************************************************************************************************************************
ok: [172.31.6.248] => {
    "msg": true
}

PLAY [Playbook full_deployment.yml] *****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

TASK [echo playbook name] ***************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

PLAY [Playbook only-config-change.yml] **************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"only-config-change.yml\"", "delta": "0:00:00.002585", "end": "2020-05-31 16:46:32.017156", "rc": 0, "start": "2020-05-31 16:46:32.014571", "stderr": "", "stderr_lines": [], "stdout": "only-config-change.yml", "stdout_lines": ["only-config-change.yml"]}

PLAY RECAP ******************************************************************************************************************************
172.31.6.248               : ok=9    changed=4    unreachable=0    failed=0

ansible-playbook -i 172.31.6.248, main.yml -v --extra-vars "target_release_version=3"

PLAY [Playbook current-deployment-status] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-deployment-status.yml\"", "delta": "0:00:00.002490", "end": "2020-05-31 16:48:28.611482", "rc": 0, "start": "2020-05-31 16:48:28.608992", "stderr": "", "stderr_lines": [], "stdout": "current-deployment-status.yml", "stdout_lines": ["current-deployment-status.yml"]}

TASK [set_fact] *************************************************************************************************************************
ok: [172.31.6.248] => {"ansible_facts": {"current_release": "2"}, "changed": false}

PLAY [Playbook current-config-status.yml] ***********************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"current-config-status.yml\"", "delta": "0:00:00.002565", "end": "2020-05-31 16:48:29.440319", "rc": 0, "start": "2020-05-31 16:48:29.437754", "stderr": "", "stderr_lines": [], "stdout": "current-config-status.yml", "stdout_lines": ["current-config-status.yml"]}

TASK [task2] ****************************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"another task\"", "delta": "0:00:00.002459", "end": "2020-05-31 16:48:29.703006", "rc": 0, "start": "2020-05-31 16:48:29.700547", "stderr": "", "stderr_lines": [], "stdout": "another task", "stdout_lines": ["another task"]}

TASK [debug] ****************************************************************************************************************************
ok: [172.31.6.248] => {
    "msg": true
}

PLAY [Playbook full_deployment.yml] *****************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
ok: [172.31.6.248]

TASK [echo playbook name] ***************************************************************************************************************
changed: [172.31.6.248] => {"changed": true, "cmd": "echo \"full_deployment.yml\"", "delta": "0:00:00.002509", "end": "2020-05-31 16:48:30.610648", "rc": 0, "start": "2020-05-31 16:48:30.608139", "stderr": "", "stderr_lines": [], "stdout": "full_deployment.yml", "stdout_lines": ["full_deployment.yml"]}

PLAY [Playbook only-config-change.yml] **************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

TASK [echo playbook name] ***************************************************************************************************************
skipping: [172.31.6.248] => {"changed": false, "skip_reason": "Conditional result was False"}

PLAY RECAP ******************************************************************************************************************************
172.31.6.248               : ok=9    changed=4    unreachable=0    failed=0


问:
How to apply a list comprehension in Panda Dataframe?
From a list of values, I try to identify any sequential pair of values whose sum exceeds 10

```<code>a = [1,9,3,4,5]
</code>```

...so I wrote a for loop...

```<code>values = []
for i in range(len(a)-2):
    if sum(a[i:i+2]) >10:
        values += [a[i:i+2]]
</code>```

...which I rewritten as a list comprehension...

```<code>values = [a[i:i+2] for i in range(len(a)-2) if sum(a[i:i+2]) >10]
</code>```

Both produce same output:

```<code>values = [[1,9], [9,3]]
</code>```

My question is how best may I apply the above list comprehension in a DataFrame.

Here is the sample 5 rows DataFrame

```<code>import pandas as pd
df = pd.DataFrame({'A': [1,1,1,1,0],
                   'B': [9,8,3,2,2],
                   'C': [3,3,3,10,3],
                   'E': [4,4,4,4,4],
                   'F': [5,5,5,5,5]})
df['X'] = df.values.tolist()
</code>```

where:
- a is within a df['X'] which is a list of values Columns A - F

```<code>df['X'] = [[1,9,3,4,5],[1,8,3,4,5],[1,3,3,4,5],[1,2,10,4,5],[0,2,3,4,5]]
</code>```

and, result of the list comprehension is to be store in new column df['X1]

Desired output is:

```<code>df['X1'] = [[[1,9], [9,3]],[[8,3]],[[NaN]],[[2,10],[10,4]],[[NaN]]]
</code>```

Thank you.

答:
You could use pandas apply function, and put your list comprehension in it.

```<code>df = pd.DataFrame({'A': [1,1,1,1,0],
                   'B': [9,8,3,2,2],
                   'C': [3,3,3,10,3],
                   'E': [4,4,4,4,4],
                   'F': [5,5,5,5,5]})

df['x'] = df.apply(lambda a: [a[i:i+2] for i in range(len(a)-2) if sum(a[i:i+2]) >= 10], axis=1)

#Note the axis parameters tells if you want to apply this function by rows or by columns, axis = 1 applies the function to each row.
</code>```

This will give the output as stated in df['X1']

Body:
From a list of values, I try to identify any sequential pair of values whose sum exceeds 10

a = [1,9,3,4,5]

...so I wrote a for loop...

values = []
for i in range(len(a)-2):
    if sum(a[i:i+2]) >10:
        values += [a[i:i+2]]

...which I rewritten as a list comprehension...

values = [a[i:i+2] for i in range(len(a)-2) if sum(a[i:i+2]) >10]

Both produce same output:

values = [[1,9], [9,3]]

My question is how best may I apply the above list comprehension in a DataFrame.

Here is the sample 5 rows DataFrame

import pandas as pd
df = pd.DataFrame({'A': [1,1,1,1,0],
                   'B': [9,8,3,2,2],
                   'C': [3,3,3,10,3],
                   'E': [4,4,4,4,4],
                   'F': [5,5,5,5,5]})
df['X'] = df.values.tolist()

where:
- a is within a df['X'] which is a list of values Columns A - F

df['X'] = [[1,9,3,4,5],[1,8,3,4,5],[1,3,3,4,5],[1,2,10,4,5],[0,2,3,4,5]]

and, result of the list comprehension is to be store in new column df['X1]

Desired output is:

df['X1'] = [[[1,9], [9,3]],[[8,3]],[[NaN]],[[2,10],[10,4]],[[NaN]]]

Thank you.

Body:
You could use pandas apply function, and put your list comprehension in it.

df = pd.DataFrame({'A': [1,1,1,1,0],
                   'B': [9,8,3,2,2],
                   'C': [3,3,3,10,3],
                   'E': [4,4,4,4,4],
                   'F': [5,5,5,5,5]})

df['x'] = df.apply(lambda a: [a[i:i+2] for i in range(len(a)-2) if sum(a[i:i+2]) >= 10], axis=1)

#Note the axis parameters tells if you want to apply this function by rows or by columns, axis = 1 applies the function to each row.

This will give the output as stated in df['X1']


问:
what is the type of a pointer to dynamically allocated memory of pointers of type char?
I am new to C. I need to allocate memory and store pointers in it. These pointers are of type char. So what is the type of the pointer to that memory? char? or long because addresses are just numbers?</p>

答:
pointers have a type of the pointer to the referenced object. It does not matter how the memory was allocated.

examples

```<code>void *ptr = malloc(10);  // pointer to void

int c;
void *ptr = &c;          //pointer to void

int *ptr = malloc(sizeof(*ptr);  // pointer to integer
int *ptr = &c;                   // pointer to integer

char *cp = malloc(100);          // pointer to char
strcpy(cp, "Hello");

void foo(double *x)              // x is a pointer to double.
{
 /* .... */
}

double **p;                      //pointer to pointer to double

/* etc etc */
</code>```

Body:
pointers have a type of the pointer to the referenced object. It does not matter how the memory was allocated.

examples

void *ptr = malloc(10);  // pointer to void

int c;
void *ptr = &c;          //pointer to void

int *ptr = malloc(sizeof(*ptr);  // pointer to integer
int *ptr = &c;                   // pointer to integer

char *cp = malloc(100);          // pointer to char
strcpy(cp, "Hello");

void foo(double *x)              // x is a pointer to double.
{
 /* .... */
}

double **p;                      //pointer to pointer to double

/* etc etc */


问:
How to use django 3.0 ORM in a Jupyter Notebook without triggering the async context check?
Django 3.0 is adding asgi / async support and with it a guard around making synchronous requests in an async context. Concurrently, IPython just added top level async/await support, which seems to be running the whole interpreter session inside of a default event loop.

Unfortunately the combination of these two great addition means that any django ORM operation in a jupyter notebook causes a SynchronousOnlyOperation exception:

```<code>SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
</code>```

As the exception message says, it's possible to wrap each ORM call in a sync_to_async() like:

images = await sync_to_async(Image.objects.all)()
```

but it's not very convenient, especially for related fields which would usually be implicitly resolved on attribute lookup.

(I tried %autoawait off magic but it didn't work, from a quick glance at the docs I'm assuming it's because ipykernels always run in an asyncio loop)

So is there a way to either disable the sync in async context check in django or run an ipykernel in a synchronous context?

For context: I wrote a data science package that uses django as a backend server but also exposes a jupyter based interface on top of the ORM that allows you to clean/annotate data, track machine learning experiments and run training jobs all in a jupyter notebook.

答:
I added

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" code in the setting.py of your project all the way down to the file and then

command python3 manage.py shell_plus --notebook

if you are using python3 or use python

That's it. worked for me.

Body:
Django 3.0 is adding asgi / async support and with it a guard around making synchronous requests in an async context. Concurrently, IPython just added top level async/await support, which seems to be running the whole interpreter session inside of a default event loop.

Unfortunately the combination of these two great addition means that any django ORM operation in a jupyter notebook causes a SynchronousOnlyOperation exception:

SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

As the exception message says, it's possible to wrap each ORM call in a sync_to_async() like:

images = await sync_to_async(Image.objects.all)()

but it's not very convenient, especially for related fields which would usually be implicitly resolved on attribute lookup.

(I tried %autoawait off magic but it didn't work, from a quick glance at the docs I'm assuming it's because ipykernels always run in an asyncio loop)

So is there a way to either disable the sync in async context check in django or run an ipykernel in a synchronous context?

For context: I wrote a data science package that uses django as a backend server but also exposes a jupyter based interface on top of the ORM that allows you to clean/annotate data, track machine learning experiments and run training jobs all in a jupyter notebook.


问:
How to use key-words instead of URL's in youtube-dl?
I am writing a bot for my discord server and I've put a play command to my bot. It works fine with URL's but I want the bot to work with searchs too. So instead of copying and pasting the URL I want to be able to write the keyword for it. This is the play command:

```<code>@client.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):
    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.07

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        await ctx.send("ERROR: Music playing")
        return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old Queue folder")

    await ctx.send("Getting everything ready now")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])
    except:
        print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)")
        c_path = os.path.dirname(os.path.realpath(__file__))
        system("spotdl -f " + '"' + c_path + '"' + " -s " + url)

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.14

    nname = name.rsplit("-", 2)
    await ctx.send(f"Playing: {nname[0]}")
    print("playing\n")
</code>```

I know It looks a little complex, It's because It has a queue feature. I tried several solution I saw online, but they didn't help because of the differences between the code they gave and the code that I have. If there is any space mistakes, It's because I might have forgot to put spaces in stackoverflow.

答:
In your youtube-dl options, set default_search. For example,

```<code>ydl_opts = {
    'default_search': 'ytsearch',
# ... all other options
</code>```

will search using the YouTube search if the input is not a URL. This works with any of the supported sites, for example 'default_search': 'https://instagram.com/explore/tags/' will search instagram tags by default.

Body:
I am writing a bot for my discord server and I've put a play command to my bot. It works fine with URL's but I want the bot to work with searchs too. So instead of copying and pasting the URL I want to be able to write the keyword for it. This is the play command:

@client.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):
    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.07

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        await ctx.send("ERROR: Music playing")
        return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old Queue folder")

    await ctx.send("Getting everything ready now")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])
    except:
        print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)")
        c_path = os.path.dirname(os.path.realpath(__file__))
        system("spotdl -f " + '"' + c_path + '"' + " -s " + url)

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.14

    nname = name.rsplit("-", 2)
    await ctx.send(f"Playing: {nname[0]}")
    print("playing\n")

I know It looks a little complex, It's because It has a queue feature. I tried several solution I saw online, but they didn't help because of the differences between the code they gave and the code that I have. If there is any space mistakes, It's because I might have forgot to put spaces in stackoverflow.

Body:
In your youtube-dl options, set default_search. For example,

ydl_opts = {
    'default_search': 'ytsearch',
# ... all other options

will search using the YouTube search if the input is not a URL. This works with any of the supported sites, for example 'default_search': 'https://instagram.com/explore/tags/' will search instagram tags by default.

OwnerDisplayName: anon


问:
Where can i find the default WPF Control templates?
As per this MSDN link,

There is no way to replace only part
  of the visual tree of a control; to
  change the visual tree of a control
  you must set the Template property of
  the control to its new and complete
  ControlTemplate

.

I am trying to disable the click behaviour of GridViewColumnHeader ( I need to remove some triggers in the original control template), but i am not able to find the native "ColumnHeaderContainerStyle". All those i have found seem to have already done some customization and it is being difficult to get the original look and feel.

Can someone please suggest me how/where can i get the original control templates as defined in the native WPF controls?

Thanks for your interest.

答:
As this blog post says, use this code (call it once) and read the output file (defaultTemplate.xml):

```<code>public static void SaveDefaultTemplate()
{
    var control = Application.Current.FindResource(typeof(ButtonSpinner));
    using (XmlWriter writer = XmlWriter.Create(@"defaultTemplate.xml"))
    {
        XamlWriter.Save(control, writer);
    }
}
</code>```

In my opinion this is the best method.
Some elements like DataGridCell are not extractable through Visual Studio tweak: Properties>Template>Convert to New Resource... because you can't explicitly define any DataGridCell.

ContentLicense: CC BY-SA 2.5

Body:
As this blog post says, use this code (call it once) and read the output file (defaultTemplate.xml):

public static void SaveDefaultTemplate()
{
    var control = Application.Current.FindResource(typeof(ButtonSpinner));
    using (XmlWriter writer = XmlWriter.Create(@"defaultTemplate.xml"))
    {
        XamlWriter.Save(control, writer);
    }
}

In my opinion this is the best method.
Some elements like DataGridCell are not extractable through Visual Studio tweak: Properties>Template>Convert to New Resource... because you can't explicitly define any DataGridCell.


问:
Whats possible in a for loop
So today I went to an interview and one of the questions was the following (C# context).

```<code>//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}
</code>```

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

答:
In C and Java for loops you may specify an unlimited (or zero) number of comma separated initialisers (of the same data type) and end-of-loop actions.

The initializer section is really just one java statement; java variable definitions may be grouped if they are of the same type, ie:

```<code>int i = 0;
int j = 0;
</code>```

is equivalent to:

```<code>int i = 0, j = 0;
</code>```

You can do what you like in the end-of-loop section - any number of statements separated by commas.

Since java 5, there is also the foreach syntax, eg:

```<code>List<String> list;
for (String element : list) {
    // do something with the variable element
}
</code>```

The syntax works with Iterable types, which includes arrays and Collections.

Title: Whats possible in a for loop

Body:
So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.

Where does this syntax stem from?

Are there any other "not well known" structures that a for loop can take?

Is writing code like above considered bad practice given how hard it is to read?

Are there any good real world examples where such a structure is required?

Body:
In C and Java for loops you may specify an unlimited (or zero) number of comma separated initialisers (of the same data type) and end-of-loop actions.

The initializer section is really just one java statement; java variable definitions may be grouped if they are of the same type, ie:

int i = 0;
int j = 0;

is equivalent to:

int i = 0, j = 0;

You can do what you like in the end-of-loop section - any number of statements separated by commas.

Since java 5, there is also the foreach syntax, eg:

List<String> list;
for (String element : list) {
    // do something with the variable element
}

The syntax works with Iterable types, which includes arrays and Collections.


问:
How to supply levels to step_num2factor for multiple numeric features in tidymodel parsnip?
Following is the recipe I am creating where I want to convert few numeric features to factors:

```<code>    house_recipe <- training(house_split) %>%
      recipe(log_sale_price ~ MSSubClass + OverallCond + LowQualFinSF) %>%
      step_num2factor(
        select(MSSubClass,OverallCond,LowQualFinSF),
          levels = list(fct_cd_mssbclass, fct_cd_ovcond, fct_cd_lwqfinsf)
      )
</code>```

I get the following error:

Error: Please provide a character vector of appropriate length for levels.

The levels have been passed as list in the code above. The definition of levels is as follows:

```<code>#create levels
fct_cd_mssbclass <- as.character(unique(sort(training(house_split)$MSSubClass)))
fct_cd_ovcond <- as.character(unique(sort(training(house_split)$OverallCond)))
fct_cd_lwqfinsf <- as.character(unique(sort(training(house_split)$LowQualFinSF)))
</code>```

Please advise how to use this step function correctly. I didn't find any similar example in the documentation. Thanks.

答:
You can factor several variables at once with the function step_mutate_at(). It takes the variables you want to change and any function you want to use:
 step_mutate_at(MSSubClass,OverallCond,LowQualFinSF, fn = factor)

Body:
Following is the recipe I am creating where I want to convert few numeric features to factors:

    house_recipe <- training(house_split) %>%
      recipe(log_sale_price ~ MSSubClass + OverallCond + LowQualFinSF) %>%
      step_num2factor(
        select(MSSubClass,OverallCond,LowQualFinSF),
          levels = list(fct_cd_mssbclass, fct_cd_ovcond, fct_cd_lwqfinsf)
      )

I get the following error:

Error: Please provide a character vector of appropriate length for levels.

The levels have been passed as list in the code above. The definition of levels is as follows:

#create levels
fct_cd_mssbclass <- as.character(unique(sort(training(house_split)$MSSubClass)))
fct_cd_ovcond <- as.character(unique(sort(training(house_split)$OverallCond)))
fct_cd_lwqfinsf <- as.character(unique(sort(training(house_split)$LowQualFinSF)))

Please advise how to use this step function correctly. I didn't find any similar example in the documentation. Thanks.


问:
My Tinder bot won't stop autoswiping right
I want to avoid bot detection and my random stuff isn't working. Actually it's not hitting dislike at all. Xpaths are all right. What am I doing wrong here?</p>

```<code>def auto_swipe(self):
    while True:
        sleep_time = random.randrange(1, 3)
        time.sleep(sleep_time)
        try:
            rand1 = random.randrange(0,100)
            if rand1 < random.randrange(70,80):
                self.like()
            else:
                self.dislike()
        except Exception:
            try:
                self.close_popup()
            except Exception:
                self.close_match()
</code>```

答:
The standard way to use random is as follows. Assuming you'd like something to happen 75% of the time, you'll write the following:

```<code>if random.random() < 0.75:
   # do something
</code>```

Body:
I want to avoid bot detection and my random stuff isn't working. Actually it's not hitting dislike at all. Xpaths are all right. What am I doing wrong here?

def auto_swipe(self):
    while True:
        sleep_time = random.randrange(1, 3)
        time.sleep(sleep_time)
        try:
            rand1 = random.randrange(0,100)
            if rand1 < random.randrange(70,80):
                self.like()
            else:
                self.dislike()
        except Exception:
            try:
                self.close_popup()
            except Exception:
                self.close_match()

Body:
The standard way to use random is as follows. Assuming you'd like something to happen 75% of the time, you'll write the following:

if random.random() < 0.75:
   # do something


问:
Proper way (move semantics) to return a std::vector from function calling in C++11
I want to fill std::vector (or some other STL container):

```<code>class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}
</code>```

1.Good looking ctor, expensive performance

```<code>std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}
</code>```

2. Better performance, worse looking ctor

```<code>void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }
</code>```

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?

答:
I believe (1) and (2) have identical performance even without C++0x, as long as your compiler does the Named Return Value Optimization, which I believe most do. Neither should do any copies, nor any moves.

Please correct me if I'm wrong, because if so I misunderstand NRVO.

Body:
I want to fill std::vector (or some other STL container):

class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}

1.Good looking ctor, expensive performance

std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}

2. Better performance, worse looking ctor

void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?


问:
Spring Security: what do authorizeRequests(), anyRequest() and authenticated() do?
In the below code what do the different chained methods do?

```<code>protected void configure(HttpSecurity http ) throws Exception {

    http.authorizeRequests()
        .antMatchers(PUBLIC_URL).permitAll()
        .anyRequest().authenticated();

}
</code>```

NOTE: PUBLIC_URL is an array of strings containing public URLs.

答:
authorizeRequests() Allows restricting access based upon the HttpServletRequest using RequestMatcher implementations.

permitAll() This will allow the public access that is anyone can access endpoint PUBLIC_URL without authentication.

anyRequest().authenticated() will restrict the access for any other endpoint other than PUBLIC_URL, and the user must be authenticated.

We can also configure access based on authorities, can manage the sessions, HTTPS channel and much more. You may find more details from configure(HttpSecurity http).

Body:
In the below code what do the different chained methods do?

protected void configure(HttpSecurity http ) throws Exception {

    http.authorizeRequests()
        .antMatchers(PUBLIC_URL).permitAll()
        .anyRequest().authenticated();

}

NOTE: PUBLIC_URL is an array of strings containing public URLs.


问:
Octave: Filling specific values in random cells inside a table
I am trying to fill some values in a table (1 row n columns). 1 and 0 must be inside the table but in random positions and the remaining cells have to be random values between 0 and 1.

e.g for n=4 P should look something like this

P = 0.0000   0.58177  1.00000   0.86008

What I have done is: filling the first two positions inside the table with 1 and 0 and the rest of n (if n>2) is filled with randomized values [0,1]. Any ideas how to fix my code are welcome.

```<code>function P=pairwise_matrix(n)

P=zeros(1,n);

 a = 0; b = 1;
 x = a + (b-a) .* rand(1,1);

  P(1,1)=1

  if (n==1)
    printf("not applicable")
  endif

  if (n==2)
    P(1,1)=0
    P(1,2)=1
  endif

  for (i=3:n)
        P(1,i)=rand(x);
  endfor

endfunction
</code>```

答:
First fill the vector with random values, than define
two random positions for 0 and 1

```<code>function P=pairwise_matrix(n)

if (n<3) n=3; endif

P=rand(1,n); # fill vector with random numbers

n0=floor(n*rand()); # random integer between 0 and n-1
n1=mod(n0+1+floor((n-1)*rand()),n); # random integer different from n0

P(n0+1)=0;
P(n1+1)=1;

endfunction
</code>```

so we have

```<code>octave:65> pairwise_matrix(3)
ans =

   1.00000   0.73595   0.00000

octave:66> pairwise_matrix(7)
ans =

   0.19995   0.01847   1.00000   0.31813   0.84074   0.00000   0.68086
</code>```

Body:
I am trying to fill some values in a table (1 row n columns). 1 and 0 must be inside the table but in random positions and the remaining cells have to be random values between 0 and 1.

e.g for n=4 P should look something like this

P = 0.0000   0.58177  1.00000   0.86008

What I have done is: filling the first two positions inside the table with 1 and 0 and the rest of n (if n>2) is filled with randomized values [0,1]. Any ideas how to fix my code are welcome.

function P=pairwise_matrix(n)

P=zeros(1,n);

 a = 0; b = 1;
 x = a + (b-a) .* rand(1,1);

  P(1,1)=1

  if (n==1)
    printf("not applicable")
  endif

  if (n==2)
    P(1,1)=0
    P(1,2)=1
  endif

  for (i=3:n)
        P(1,i)=rand(x);
  endfor

endfunction

Body:
First fill the vector with random values, than define
two random positions for 0 and 1

function P=pairwise_matrix(n)

if (n<3) n=3; endif

P=rand(1,n); # fill vector with random numbers

n0=floor(n*rand()); # random integer between 0 and n-1
n1=mod(n0+1+floor((n-1)*rand()),n); # random integer different from n0

P(n0+1)=0;
P(n1+1)=1;

endfunction

so we have

octave:65> pairwise_matrix(3)
ans =

   1.00000   0.73595   0.00000

octave:66> pairwise_matrix(7)
ans =

   0.19995   0.01847   1.00000   0.31813   0.84074   0.00000   0.68086


问:
System.Data.DbType Vs System.Data.SqlType
Am using enterprise library data access application block...
is there any performance impact of using System.Data.DbType Vs System.Data.SqlType?

And also, would like to know performance impact for the statement:

```<code>DatabaseFactory.CreateDatabase("MyDB")
</code>```

Vs

```<code>new SqlDatabase(myConnectionString);
</code>```

答: The impact here is not one of performance but more explicitness versus flexibility. the DBType and DatabaseFactory methods are more flexible and allow you to flip the type of database you are using. You might see a small bit of perf in the other direction, but not enough to make your decision based on perf.</p>

OwnerDisplayName: Jeremy Thomson

Body:
Am using enterprise library data access application block...
is there any performance impact of using System.Data.DbType Vs System.Data.SqlType?

And also, would like to know performance impact for the statement:

DatabaseFactory.CreateDatabase("MyDB")

Vs

new SqlDatabase(myConnectionString);

OwnerDisplayName: Gregory A Beamer


问:
SQL update query not updating table data
Here is my code and it shows successful but it does not update row in table.</p>

```<code>cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");
</code>```

答: If you're using a file based database like a sql server mdf file that is being dynamically attached to your db server when you run your project you should be aware that the db your program is updating is not necessarily the same file you're looking in with your management studio. Take a look at your connection string- if it mentions DataDirectory then it's likely it's the database file in the bin/Debug or bin/Release (depending on your active build config) folder that is being updated, not the one in your project folder. The db in your project folder is copied out to bin/* every tine you run your project. This has classically been an awesome cause of "my program says it updates my db but it doesn't" - either the db is being replaced with a clean one every time the program is run or the dev is looking in one db file and the program is updating another </p>

Body:
Here is my code and it shows successful but it does not update row in table.

cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");


问:
Using accelerometer values in python with kivy crashes app
I'm having some trouble making use of accelerometer values inside a kivy android app.
I can read the accelerometer values correctly and they are displayed in a meaningful way in my app; I can print them to a textlabel.

However, as soon as I try to use them in a mathematical operation (say a subtraction, marked with a comment in the code), the app crashes giving the following error:

```<code>Unsupported operand type(s) for -: ‘NoneType’ and ‘NoneType’
</code>```

The code is as follows:

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from plyer import accelerometer
from plyer import gravity
import numpy as np

class TestApp(App):

    def __init__(self):
        super(TestApp, self).__init__()
        self.sensorEnabled= False
        self.acc= np.array([0, 0, 0])
        self.grav= np.array([0, 0, 0])
        self.lineal= np.array([0, 0, 0])

    def leer_accel(self, dt):
        self.acc= np.asarray(accelerometer.acceleration)
        self.grav= np.asarray(gravity.gravity)
        test= self.acc[0]- self.grav[0] #THIS LINE CRASHES THE APP!!
        self.root.ids['a_x'].text= f"{str(self.acc)}"
        self.root.ids['a_y'].text= f"{str(type(self.acc))}"
        self.root.ids['a_z'].text= " "
        #self.root.ids['g_x'].text= " "
        #self.root.ids['g_y'].text= " "
        self.root.ids['g_z'].text=f"{self.acc- self.grav}"
    def empezar(self):
        try:
            if not self.sensorEnabled:
                accelerometer.enable()
                gravity.enable()
                Clock.schedule_interval(self.leer_accel, 1/100)
                self.sensorEnabled= True
                self.root.ids['boton_1'].text= "Parar"
            else:
                accelerometer.disable()
                Clock.unschedule(self.leer_accel)
                self.sensorEnabled= False
                self.root.ids.boton_1.text= "Empezar"
        except NotImplementedError:
            import traceback
            traceback.print_exc()
            self.root.ids.status.text= "Accelerometro no soportado"

App= TestApp()
App.run()
</code>```

There's something (obvious) I'm sure I'm missing since the variables exist and I can access them to print them out, however I haven't caught the error yet.

Thanks

答:
It sounds like you probably get values of None at some point, perhaps when the accelerometer is first accessed. If you print every value along the way, you'll probably see that in the log.

The fix then would be to check for this in leer_accel and just return early if the data isn't good.

Body:
I'm having some trouble making use of accelerometer values inside a kivy android app.
I can read the accelerometer values correctly and they are displayed in a meaningful way in my app; I can print them to a textlabel.

However, as soon as I try to use them in a mathematical operation (say a subtraction, marked with a comment in the code), the app crashes giving the following error:

Unsupported operand type(s) for -: ‘NoneType’ and ‘NoneType’

The code is as follows:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from plyer import accelerometer
from plyer import gravity
import numpy as np

class TestApp(App):

    def __init__(self):
        super(TestApp, self).__init__()
        self.sensorEnabled= False
        self.acc= np.array([0, 0, 0])
        self.grav= np.array([0, 0, 0])
        self.lineal= np.array([0, 0, 0])

    def leer_accel(self, dt):
        self.acc= np.asarray(accelerometer.acceleration)
        self.grav= np.asarray(gravity.gravity)
        test= self.acc[0]- self.grav[0] #THIS LINE CRASHES THE APP!!
        self.root.ids['a_x'].text= f"{str(self.acc)}"
        self.root.ids['a_y'].text= f"{str(type(self.acc))}"
        self.root.ids['a_z'].text= " "
        #self.root.ids['g_x'].text= " "
        #self.root.ids['g_y'].text= " "
        self.root.ids['g_z'].text=f"{self.acc- self.grav}"
    def empezar(self):
        try:
            if not self.sensorEnabled:
                accelerometer.enable()
                gravity.enable()
                Clock.schedule_interval(self.leer_accel, 1/100)
                self.sensorEnabled= True
                self.root.ids['boton_1'].text= "Parar"
            else:
                accelerometer.disable()
                Clock.unschedule(self.leer_accel)
                self.sensorEnabled= False
                self.root.ids.boton_1.text= "Empezar"
        except NotImplementedError:
            import traceback
            traceback.print_exc()
            self.root.ids.status.text= "Accelerometro no soportado"

App= TestApp()
App.run()

There's something (obvious) I'm sure I'm missing since the variables exist and I can access them to print them out, however I haven't caught the error yet.

Thanks


问:
Article Share API from LinkedIn Throwing error
I'm trying to make a simple share button LinkedIn using the article share API. It's pretty straight foward, or so I thought.

When using the domain's href, it works:

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fsp156.prefeitura.sp.gov.br/portal

I can even make it to another page:

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fsp156.prefeitura.sp.gov.br/portal/servicos

However, if I try another page:

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fsp156.prefeitura.sp.gov.br/portal/servicos/informacao?servico=3832

It brings up a error. Looking at the console doesn't really help that much, and at the network tab all the requests return 200.

I tried removing the query parameters, although the page doesn't work without them, and still, didn't worked

@edit:
Even the LinkedIn official inspector of pages can recognize the page, now I'm really confused:

https://www.linkedin.com/post-inspector/inspect/https:%2F%2Fsp156.prefeitura.sp.gov.br%2Fportal%2Fservicos%2Finformacao%3Fservico=3832

Anyone has idea on what's happening? Thanks in advance.

答:
The URL you are sharing contains a ? character.  You need to escape that character using URL-encoding.  So, this is what you should want...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fsp156.prefeitura.sp.gov.br%2Fportal%2Fservicos%2Finformacao%3Fservico%3D3832
</code>```

Notice how the ? is rendered here as %3F.  URL's should only have one ? at all, because that indicates that $_GET data is going to proceed that mark.  With two of them, the server doesn't know and gets confused!

Looks good to me now!

In case you want to know more: Official LinkedIn Share Documentation

Body:
The URL you are sharing contains a ? character.  You need to escape that character using URL-encoding.  So, this is what you should want...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fsp156.prefeitura.sp.gov.br%2Fportal%2Fservicos%2Finformacao%3Fservico%3D3832

Notice how the ? is rendered here as %3F.  URL's should only have one ? at all, because that indicates that $_GET data is going to proceed that mark.  With two of them, the server doesn't know and gets confused!

Looks good to me now!

In case you want to know more: Official LinkedIn Share Documentation


问:
Ionic native device plugin returns all nulls in all platforms
I'm using @ionic-native/device plugin in my ionic application in order to detect the underlying device running the application.
However, when I try to use it I get the Device object with all properties set to null.

Note:
this is NOT a duplication of This question since the problem occurs even when running cordova run browser or running in android...

I've installed the @ionic-native/device plugin and used it as follows:

App.module.ts:

```<code>import { Device } from '@ionic-native/device/ngx';

@NgModule({
// ...
providers: [
    Device,
]
//...
})
export class AppModule { }
</code>```

App.component.ts:

```<code> constructor(private device: Device) {
    console.log('Device is: ', this.device);
 }
</code>```

package.json:

```<code>"dependencies": {
  ...
    "@ionic-native/core": "^5.24.0",
    "@ionic-native/device": "^5.26.0"
 }
</code>```

What is missing?

答:
i suggest you to try this since, the method ready of the platform object helps you to wait all the plugins to be ready in order to execute your code.
don't forget this in your constructor params list : "private platform : Platform"</p>

```<code>this.platform.ready().then(()=>{
    console.log('Device is: ', this.device);
}
</code>```

Body:
I'm using @ionic-native/device plugin in my ionic application in order to detect the underlying device running the application.
However, when I try to use it I get the Device object with all properties set to null.

Note:
this is NOT a duplication of This question since the problem occurs even when running cordova run browser or running in android...

I've installed the @ionic-native/device plugin and used it as follows:

App.module.ts:

import { Device } from '@ionic-native/device/ngx';

@NgModule({
// ...
providers: [
    Device,
]
//...
})
export class AppModule { }

App.component.ts:

 constructor(private device: Device) {
    console.log('Device is: ', this.device);
 }

package.json:

"dependencies": {
  ...
    "@ionic-native/core": "^5.24.0",
    "@ionic-native/device": "^5.26.0"
 }

What is missing?

Body:
i suggest you to try this since, the method ready of the platform object helps you to wait all the plugins to be ready in order to execute your code.
don't forget this in your constructor params list : "private platform : Platform"

this.platform.ready().then(()=>{
    console.log('Device is: ', this.device);
}


问:
link in alert boxes javascript
I have a simple question.  I have the following code:

```<code>alert("Are you sure you want to add: \n" + redirURL + "?");
</code>```

the variable redirURL is an actual working url.  I would like it to be 'clickable'

thank you in advance

答:
If you want to open the Link on alert and that too in new window, Use the code below:

```<code>if (window.confirm('Ok to Confirm, Cancel to Stay here'))
   {
   window.open('http://www.google.com', '_blank');
   };
</code>```

Note that most browsers will treat these links as popup.

There is an alternative too, Both works same, find it below:

```<code>//write this above first
let a=document.createElement('a');
a.target='_blank';
a.href='https://www.google.com';

//then use this code for alert
if (window.confirm('Ok to Confirm, Cancel to Stay here'))
{
a.click();
};
</code>```

Title: link in alert boxes javascript

Body:
I have a simple question.  I have the following code:

alert("Are you sure you want to add: \n" + redirURL + "?");

the variable redirURL is an actual working url.  I would like it to be 'clickable'

thank you in advance

Body:
If you want to open the Link on alert and that too in new window, Use the code below:

if (window.confirm('Ok to Confirm, Cancel to Stay here'))
   {
   window.open('http://www.google.com', '_blank');
   };

Note that most browsers will treat these links as popup.

There is an alternative too, Both works same, find it below:

//write this above first
let a=document.createElement('a');
a.target='_blank';
a.href='https://www.google.com';

//then use this code for alert
if (window.confirm('Ok to Confirm, Cancel to Stay here'))
{
a.click();
};


问:
Comparing two different python counter objects
I’m working on an algorithm in Python that would take user input and tell them what new letters they would need to add to a string to make it into a different string, and I’ve been playing around a lot with the dictionaries created by the Counter method.

I want to compare two different dictionaries that are counting letters from strings (like the objects returned from using the Counter tool from the collections module). We can call these dictionaries D1 and D2. I want there to be two resulting dictionaries (R1 and R2), the first being the shared letters between the two, and the second being the letters needed to make R1 into R2 (the letters that are in D2 but not in D1).

For example:

```<code># assuming they’ve been converted from counter objects into regular
dictionaries #

D1 = {‘A’: 2, ‘B’: 1, ‘C’: 4, ‘D’: 5}
D2 = {‘A’: 3, ‘B’: 4, ‘C’ : 4, ‘D’: 7}

# Some sort of comparison function executed here #
</code>```

Result:

```<code>R1={‘A’: 2, ‘B’: 3, ‘C’: 4, ‘D’: 5}
R2 = {‘A’: 1, ‘B’: 1, ‘C’: 0 , ‘D’: 2}
</code>```

答:
Since Dani Mesejo's answer, the subtract method (docs) has been added for keeping negative counts in Counter objects (only inplace however), i.e. the following is a more succinct solution:

```<code>from collections import Counter

D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5, 'E': 5})
D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7, 'E': 3})

R1 = D1 & D2
print(R1)

D2.subtract(D1)
print(D2)
</code>```

Output:

```<code>Counter({'D': 5, 'C': 4, 'E': 3, 'A': 2, 'B': 1})
Counter({'B': 3, 'D': 2, 'A': 1, 'C': 0, 'E': -2})
</code>```

Body:
I’m working on an algorithm in Python that would take user input and tell them what new letters they would need to add to a string to make it into a different string, and I’ve been playing around a lot with the dictionaries created by the Counter method.

I want to compare two different dictionaries that are counting letters from strings (like the objects returned from using the Counter tool from the collections module). We can call these dictionaries D1 and D2. I want there to be two resulting dictionaries (R1 and R2), the first being the shared letters between the two, and the second being the letters needed to make R1 into R2 (the letters that are in D2 but not in D1).

For example:

# assuming they’ve been converted from counter objects into regular
dictionaries #

D1 = {‘A’: 2, ‘B’: 1, ‘C’: 4, ‘D’: 5}
D2 = {‘A’: 3, ‘B’: 4, ‘C’ : 4, ‘D’: 7}

# Some sort of comparison function executed here #

Result:

R1={‘A’: 2, ‘B’: 3, ‘C’: 4, ‘D’: 5}
R2 = {‘A’: 1, ‘B’: 1, ‘C’: 0 , ‘D’: 2}

Body:
Since Dani Mesejo's answer, the subtract method (docs) has been added for keeping negative counts in Counter objects (only inplace however), i.e. the following is a more succinct solution:

from collections import Counter

D1 = Counter({'A': 2, 'B': 1, 'C': 4, 'D': 5, 'E': 5})
D2 = Counter({'A': 3, 'B': 4, 'C': 4, 'D': 7, 'E': 3})

R1 = D1 & D2
print(R1)

D2.subtract(D1)
print(D2)

Output:

Counter({'D': 5, 'C': 4, 'E': 3, 'A': 2, 'B': 1})
Counter({'B': 3, 'D': 2, 'A': 1, 'C': 0, 'E': -2})


问:
Laravel Forge Stripe ENV keys stopped working, still working fine on local dev
I have a Laravel 5.5 app using Stripe for subscriptions, deployed on Forge/Digital Ocean.

Everything has been working fine for many months, but today both environmental variables  env('PUB_STRIPE_API_KEY') and env('STRIPE_API_KEY') are showing as not present (if(empty) is coming up true for both variables) and Stripe functionality is therefore stopped. Both are present and accounted for in my .ENV file.

```<code>STRIPE_API_KEY=sk_test_fPpKzHV49vImGOh4Aqxxxxxx
PUB_STRIPE_API_KEY=pk_test_HrVhWbsRL90qm7RrCbxxxxxx
</code>```

However, my identical local development instance works just fine. Both were just fine a few days ago and no changes have been made to any Stripe or .ENV code. I'm perplexed.

Other .ENV variables, such as database connection parameters, all seem fine. Only Stripe is effected.

I have checked the .ENV file. I have cleared cache (php artisan cache:clear). No difference. I don't know where to go from here. Any suggestions...?

答: So, after days of chasing ghost solutions a simple artisan config:clear solved the issue. The glitch was on the Forge/Digital Ocean end, not my code. I had already tried artisan cache:clear thinking that would resolve what (correctly) appeared to be a caching issue, but I was using the wrong artisan cache clearing command. All good now and back working again :)

Body:
I have a Laravel 5.5 app using Stripe for subscriptions, deployed on Forge/Digital Ocean.

Everything has been working fine for many months, but today both environmental variables  env('PUB_STRIPE_API_KEY') and env('STRIPE_API_KEY') are showing as not present (if(empty) is coming up true for both variables) and Stripe functionality is therefore stopped. Both are present and accounted for in my .ENV file.

STRIPE_API_KEY=sk_test_fPpKzHV49vImGOh4Aqxxxxxx
PUB_STRIPE_API_KEY=pk_test_HrVhWbsRL90qm7RrCbxxxxxx

However, my identical local development instance works just fine. Both were just fine a few days ago and no changes have been made to any Stripe or .ENV code. I'm perplexed.

Other .ENV variables, such as database connection parameters, all seem fine. Only Stripe is effected.

I have checked the .ENV file. I have cleared cache (php artisan cache:clear). No difference. I don't know where to go from here. Any suggestions...?


问:
How to reduce the running time and memory utilization of the Louvain algorithm in the Neo4j Graph?
This is my data:
Neo4j data

This is the CQL:

```<code>"call algo.louvain.stream('','',{weightProperty: 'weight'}) YIELD nodeId,community return algo.getNodeById(nodeId).mno as name ,community","/mno-rel.csv",{});
</code>```

This is the neo4j config:

dbms.memory.heap.initial_size=71440m

dbms.memory.heap.max_size=71440m

dbms.memory.pagecache.size=20g

Neo4j version : neo4j-community-3.5.8

When I run the above algorithm, it will take me 5 hours and take more than 70 g of memory.

Please help me how to reduce memory and time. I appreciate it very much :D

==========================================================================

Answer logisima's question:

Total Store Size : 60.71 GiB

CPU(s) : 40

total used free shared buff/cache available

Mem: 125G 114G 1.4G 337M 9.7G 9.8G

debug.log
20-02-05 23:52:54.946+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=3882, gcTime=21, gcCount=1}

2020-02-05 23:53:05.327+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 0% round 3

2020-02-05 23:53:15.327+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 77% round 3

2020-02-05 23:53:25.385+0000 INFO [o.n.k.i.p.Procedures] [algo-3] Louvain 10% round 4

2020-02-05 23:53:35.378+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 90% round 4

2020-02-05 23:53:45.379+0000 INFO [o.n.k.i.p.Procedures] [algo-4] Louvain 26% round 5

2020-02-05 23:53:59.480+0000 INFO [o.n.k.i.p.Procedures] [neo4j.BoltWorker-4 [bolt] [/10.3.99.111:49607] ] Louvain 100% level: 7 communities: 7689984 q: 0.9808712031807056

2020-02-05 23:54:03.543+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=197, gcTime=202, gcCount=1}

2020-02-05 23:54:07.130+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=184, gcTime=243, gcCount=1}

2020-02-05 23:54:21.578+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 0% round 1

2020-02-05 23:54:23.528+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=366, gcTime=380, gcCount=1}

2020-02-05 23:54:26.352+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=121, gcTime=217, gcCount=1}

2020-02-05 23:54:31.579+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 80% round 1

2020-02-05 23:54:40.056+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=5693, gcTime=0, gcCount=0}

2020-02-05 23:54:41.580+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 98% round 1

2020-02-05 23:54:47.314+0000 INFO [o.n.k.i.p.Procedures] [neo4j.BoltWorker-4 [bolt] [/10.3.99.111:49607] ] Louvain 100% level: 8 communities: 7689984 q: -1.0

2020-02-05 23:55:11.177+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=5269, gcTime=0, gcCount=0}

答: I am not sure if you are aware, but try out the Neo4j Graph Data Science library. It is the successor of the graph algorithms library, which is deprecated, and should have better performance. Looking at the additional data you provided it seems that the bottleneck is not the Louvain algorithm, but actually writing the results back to a CSV file. Maybe you could try to write back the results to Neo4j and then fetch results parallel from Neo4j using APOC.</p>

Body:
This is my data:
Neo4j data

This is the CQL:

"call algo.louvain.stream('','',{weightProperty: 'weight'}) YIELD nodeId,community return algo.getNodeById(nodeId).mno as name ,community","/mno-rel.csv",{});

This is the neo4j config:

dbms.memory.heap.initial_size=71440m

dbms.memory.heap.max_size=71440m

dbms.memory.pagecache.size=20g

Neo4j version : neo4j-community-3.5.8

When I run the above algorithm, it will take me 5 hours and take more than 70 g of memory.

Please help me how to reduce memory and time. I appreciate it very much :D

==========================================================================

Answer logisima's question:

Total Store Size : 60.71 GiB

CPU(s) : 40

total used free shared buff/cache available

Mem: 125G 114G 1.4G 337M 9.7G 9.8G

debug.log
20-02-05 23:52:54.946+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=3882, gcTime=21, gcCount=1}

2020-02-05 23:53:05.327+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 0% round 3

2020-02-05 23:53:15.327+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 77% round 3

2020-02-05 23:53:25.385+0000 INFO [o.n.k.i.p.Procedures] [algo-3] Louvain 10% round 4

2020-02-05 23:53:35.378+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 90% round 4

2020-02-05 23:53:45.379+0000 INFO [o.n.k.i.p.Procedures] [algo-4] Louvain 26% round 5

2020-02-05 23:53:59.480+0000 INFO [o.n.k.i.p.Procedures] [neo4j.BoltWorker-4 [bolt] [/10.3.99.111:49607] ] Louvain 100% level: 7 communities: 7689984 q: 0.9808712031807056

2020-02-05 23:54:03.543+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=197, gcTime=202, gcCount=1}

2020-02-05 23:54:07.130+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=184, gcTime=243, gcCount=1}

2020-02-05 23:54:21.578+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 0% round 1

2020-02-05 23:54:23.528+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=366, gcTime=380, gcCount=1}

2020-02-05 23:54:26.352+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=121, gcTime=217, gcCount=1}

2020-02-05 23:54:31.579+0000 INFO [o.n.k.i.p.Procedures] [algo-1] Louvain 80% round 1

2020-02-05 23:54:40.056+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=5693, gcTime=0, gcCount=0}

2020-02-05 23:54:41.580+0000 INFO [o.n.k.i.p.Procedures] [algo-2] Louvain 98% round 1

2020-02-05 23:54:47.314+0000 INFO [o.n.k.i.p.Procedures] [neo4j.BoltWorker-4 [bolt] [/10.3.99.111:49607] ] Louvain 100% level: 8 communities: 7689984 q: -1.0

2020-02-05 23:55:11.177+0000 WARN [o.n.k.i.c.VmPauseMonitorComponent] Detected VM stop-the-world pause: {pauseTime=5269, gcTime=0, gcCount=0}