问:
Why data isn't updating after sorting in React Hooks?
I'm new to React Hooks. I'm trying to sort table inside React Hook, but after click my content doesn't update. Why is that?

This is my hook:

```<code>const Main = ({ dataProps }) => {
const [data, setData] = useState(dataProps);
const sortById = (field) => {
        let sortedData = data.sort((a, b) => {
            if(a[field] < b[field]) { return -1; }
            if(a[field] > b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};
return (
        <table>
            <thead>
                <tr>
                    <th>iD <div className="arrows"><div onClick={() => sortById("id")} className="arrow-up"/></th>
                    <th>First name <div className="arrows"><div onClick={() => sortById("firstName")} className="arrow-up"/></div></th>
                </tr>
            </thead>
            <tbody>
            {data.map((user) => {
                return <tr key={user.id}>
                    <td className="number">{user.id}</td>
                    <td className="firstname">{user.firstName}</td>
                </tr>
            })}
            </tbody>
        </table>
);
};
</code>```

答:
problem is sort return same array which won't cause re-render. if you slice before sorting it will fix issue.

```<code>const sortById = (field) => {
        let sortedData = data.slice().sort((a, b) => {
            if(a[field] < b[field]) { return -1; }
            if(a[field] > b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};
</code>```

BTW more efficient way of doing is mentioned by @jonas-wilms

Body:
I'm new to React Hooks. I'm trying to sort table inside React Hook, but after click my content doesn't update. Why is that?

This is my hook:

const Main = ({ dataProps }) => {
const [data, setData] = useState(dataProps);
const sortById = (field) => {
        let sortedData = data.sort((a, b) => {
            if(a[field]  b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};
return (

                    iD

 sortById("id")} className="arrow-up"/>
                    First name

 sortById("firstName")} className="arrow-up"/>

            {data.map((user) => {
                return

                    {user.id}
                    {user.firstName}

            })}

);
};

Body:
problem is sort return same array which won't cause re-render. if you slice before sorting it will fix issue.

const sortById = (field) => {
        let sortedData = data.slice().sort((a, b) => {
            if(a[field] < b[field]) { return -1; }
            if(a[field] > b[field]) { return 1; }
            return 0;
        });
        setData(sortedData);
};

BTW more efficient way of doing is mentioned by @jonas-wilms


来源: stackexchange

问:
custom element type reports HTMLElement when loaded in script type=module?
I'm working with custom elements and I noticed in one case I was unable to access the properties of an instance as in var prop = myCustomElement.myPropery // undefined where the property is defined in the class as e.g. get myProperty() { blah }.

I've boiled the problem down to what gets reported as in myCustomElement.constructor ( and thus the prototype/instance type ) when the custom element is defined in a script type="module" vs. without the module type.

Here's a very simple example:

var test = document.getElementById ( "test" );

console.log ( test.mood, test.constructor );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="module">
const template = document.createElement ( "template" );

template.innerHTML = "<span>Hello!</span>";

window.customElements.define ( "test-case",

class TestCase extends window.HTMLElement {
    constructor () {
        super ();

        var frag = template.content.cloneNode ( true ),
            shadow = this.attachShadow( { mode: "open" } );

        shadow.appendChild ( frag );
    }

    get mood () {
        return "Happy!";
    }
} );
</script>
<test-case id="test"></test-case></code>```

... and without the module type

var test = document.getElementById ( "test" );

console.log ( test.mood, test.constructor );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
const template = document.createElement ( "template" );

template.innerHTML = "<span>Hello!</span>";

window.customElements.define ( "test-case",

class TestCase extends window.HTMLElement {
    constructor () {
        super ();

        var frag = template.content.cloneNode ( true ),
            shadow = this.attachShadow( { mode: "open" } );

        shadow.appendChild ( frag );
    }

    get mood () {
        return "Happy!";
    }
} );
</script>
<test-case id="test"></test-case></code>```

This seems quite wrong, is this behavior intentional?

And also, assuming the need to use a module for the purpose of e.g. defining a custom element to be used inside a larger component or library, is there a straight forward way to prevent the module from hiding the type of the custom element?

Note: I'm testing this from latest Chrome (74.0.3729.157), and haven't tried other browsers.

答:
Your non-module script is running before the module script. So you simply need to wait until the element has been defined but calling customElements.whenDefined:
https://devdocs.io/dom/customelementregistry/whendefined

Also there is no reason to use window when using customElements or HTMLElement.

customElements.whenDefined('test-case').then(
  () => {
    const test = document.getElementById ( "test" );
    console.log ( test.mood, test.constructor );
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="module">
const template = document.createElement ( "template" );
template.innerHTML = "<span>Hello!</span>";
customElements.define ( "test-case",
  class TestCase extends HTMLElement {
    constructor () {
      super ();
      const frag = template.content.cloneNode ( true );
      const shadow = this.attachShadow( { mode: "open" } );
      shadow.appendChild ( frag );
    }

    get mood () {
      return "Happy!";
    }
  }
);
</script>
<test-case id="test"></test-case></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working with custom elements and I noticed in one case I was unable to access the properties of an instance as in var prop = myCustomElement.myPropery // undefined where the property is defined in the class as e.g. get myProperty() { blah }.

I've boiled the problem down to what gets reported as in myCustomElement.constructor ( and thus the prototype/instance type ) when the custom element is defined in a script type="module" vs. without the module type.

Here's a very simple example:

var test = document.getElementById ( "test" );

console.log ( test.mood, test.constructor );

<test-case id="test"></test-case>

... and without the module type

var test = document.getElementById ( "test" );

console.log ( test.mood, test.constructor );

<test-case id="test"></test-case>

This seems quite wrong, is this behavior intentional?

And also, assuming the need to use a module for the purpose of e.g. defining a custom element to be used inside a larger component or library, is there a straight forward way to prevent the module from hiding the type of the custom element?

Note: I'm testing this from latest Chrome (74.0.3729.157), and haven't tried other browsers.

Body:
Your non-module script is running before the module script. So you simply need to wait until the element has been defined but calling customElements.whenDefined:
https://devdocs.io/dom/customelementregistry/whendefined

Also there is no reason to use window when using customElements or HTMLElement.

customElements.whenDefined('test-case').then(
  () => {
    const test = document.getElementById ( "test" );
    console.log ( test.mood, test.constructor );
  }
);

<script type="module">
const template = document.createElement ( "template" );
template.innerHTML = "<span>Hello!</span>";
customElements.define ( "test-case",
  class TestCase extends HTMLElement {
    constructor () {
      super ();
      const frag = template.content.cloneNode ( true );
      const shadow = this.attachShadow( { mode: "open" } );
      shadow.appendChild ( frag );
    }

    get mood () {
      return "Happy!";
    }
  }
);
</script>
<test-case id="test"></test-case>


问:
How to read in .json file in python?
I want to read in only "text" part of the json file below. That is: HAPPY NEW YEAR!
....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!

then train the words in my RNN model, what should I do to get text and delete the others?

json file:

```<code>[{"source": "Twitter for iPhone", "id_str": "1079888205351145472", "text": "HAPPY NEW YEAR! ", "created_at": "Mon Dec 31 23:53:06 +0000 2018", "retweet_count": 33548, "in reply to user id str": null, "favorite_count": 136012, "is_retweet": false},
 {"source": "Twitter for iPhone", "id_str": "1079830268708556800", "text": "....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!", "created_at": "Mon Dec 31 20:02:52 +0000 2018", "retweet_count": 17456, "in reply to user id str": "25073877", "favorite_count": 65069, "is_retweet": false}]
</code>```

答:
Should be as simple as reading the file and concatenating the relevant section of the parsed json object. I'm assuming you need the whole thing as a single string and not a list of strings.

```<code>import json
with open('file.json') as f:
    data = json.load(f)
    text = "".join(d['text'] for d in data)

print(text)
</code>```

With file.json being your data file & text being the extracted string.

Title: How to read in .json file in python?

Body:
I want to read in only "text" part of the json file below. That is: HAPPY NEW YEAR!
....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!

then train the words in my RNN model, what should I do to get text and delete the others?

json file:

[{"source": "Twitter for iPhone", "id_str": "1079888205351145472", "text": "HAPPY NEW YEAR! ", "created_at": "Mon Dec 31 23:53:06 +0000 2018", "retweet_count": 33548, "in reply to user id str": null, "favorite_count": 136012, "is_retweet": false},
 {"source": "Twitter for iPhone", "id_str": "1079830268708556800", "text": "....Senator Schumer, more than a year longer than any other Administration in history. These are people who have been approved by committees and all others, yet Schumer continues to hold them back from serving their Country! Very Unfair!", "created_at": "Mon Dec 31 20:02:52 +0000 2018", "retweet_count": 17456, "in reply to user id str": "25073877", "favorite_count": 65069, "is_retweet": false}]

Body:
Should be as simple as reading the file and concatenating the relevant section of the parsed json object. I'm assuming you need the whole thing as a single string and not a list of strings.

import json
with open('file.json') as f:
    data = json.load(f)
    text = "".join(d['text'] for d in data)

print(text)

With file.json being your data file & text being the extracted string.


问:
Add class to parent div that matches label text
I would like to add a class to each parent div and have that class match the content of the label within the div with a hyphen added between each word.

In the example below, the first div would have class child-1-name, the second child-1-last-name, the third child-1-age. Any direction would be greatly appreciated!

Note that the HTML is generated automatically.

    child 1 name
    <input type="text">

    child 1 last name
    <input type="text">

    child 1 age
    <input type="text">

```

答:
Please check the code, hope it will help.</p>

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>

<script>
  $(document).ready(function() {
    $(".wrapable").each(function() {
      //   alert($(this).text());
      var data = $(this).text();
      $(this)
        .closest("div")
        .addClass(
          $(this)
            .text()
            .trim()
            .replace(/\s+/g, "-")
        );
    });
  });
</script>
</code>```

Body:
Please check the code, hope it will help.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 name</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 last name</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>
<div>
  <span class="req"></span>
  <span>
    <label class="wrapable">child 1 age</label>
    <span class="net"><input type="text"/></span>
  </span>
</div>

<script>
  $(document).ready(function() {
    $(".wrapable").each(function() {
      //   alert($(this).text());
      var data = $(this).text();
      $(this)
        .closest("div")
        .addClass(
          $(this)
            .text()
            .trim()
            .replace(/\s+/g, "-")
        );
    });
  });
</script>


问:
Store byte contents in S3
I need to save binary (byte[]) contents (PDF file) to S3.

I don't want to have a hard copy existing in HDD, pdf is being generated in the fly and then it needs to be sent to S3.

Java AWS SDK AmazonS3.putObject() requires File type in method signature, how can I pass my binary contents directly without saving it to hard drive?

答:
You can use the following method for aws file storage.

```<code>PutObjectResult         putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)
</code>```

Aws also provides the following overloaded method to use based upon the suitability.

```<code>PutObjectResult         putObject(PutObjectRequest putObjectRequest)
PutObjectResult         putObject(String bucketName, String key, File file)
PutObjectResult         putObject(String bucketName, String key, String content)
</code>```

You can convert byte[] to InputStream and you can pass in the above method. Refer below the javadocs for aws:

Amazon S3

PutObjectRequest

Title: Store byte contents in S3

Body:
You can use the following method for aws file storage.

PutObjectResult         putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)

Aws also provides the following overloaded method to use based upon the suitability.

PutObjectResult         putObject(PutObjectRequest putObjectRequest)
PutObjectResult         putObject(String bucketName, String key, File file)
PutObjectResult         putObject(String bucketName, String key, String content)

You can convert byte[] to InputStream and you can pass in the above method. Refer below the javadocs for aws:

Amazon S3

PutObjectRequest


问:
Django can't find model property
In my Django project, I have a models.py that looks like this:

from django.db import models

class Battle(models.Model):

    def __str__(self):
        return self.battle_name

    battle_name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    password = models.CharField(max_length=50)
```

<p>When I drop to the Django shell (<code>python manage.py shell</code>), I can't interact either of the DateTimeField properties.</p>

```$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
```

Am I missing something?

答:
You make syntax error

Try this

```<code>Battle.objects.filter(end_time__lt=datetime.datetime.now())
</code>```

Title: Django can't find model property

Body:
In my Django project, I have a models.py that looks like this:

from django.db import models

class Battle(models.Model):

    def __str__(self):
        return self.battle_name

    battle_name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    password = models.CharField(max_length=50)

When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties.

$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined

Am I missing something?

Body:
You make syntax error

Try this

Battle.objects.filter(end_time__lt=datetime.datetime.now())


问:
Generate permalinks on header with python markdown library
I was wondering how to generate permalinks from the following markup, using python markdown library:

```<code>A header
========

A paragraph
</code>```

The desired output would be something like

```<code><span id="a-header"></span>
<h1>
  A header
  <a class="headerlink" title="Permalink to this headline" href="#a-header">¶</a>
</h1>
<p>A paragraph</p>
</code>```

Answer:

Thanks @BlaXpirit (see answer)

Use headerid python markdown extension and input the following:

```<code># A header [¶](#a-header) {#a-header}

A paragraph
</code>```

This generates the following output:

```<code><h1 id="a-header">
  A header
  <a href="#a-header">¶</a>
</h1>
</code>```

Then use some css styling to get the common output, something like :

```<code>h1 a{visibility:hidden;}
h1:hover a{visibility:visible;}
</code>```

答:
Markdown in Python has an extension that does this.

It also lets you specify an id you like for the header, like this:

```
A header            {#a-header}
========
```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering how to generate permalinks from the following markup, using python markdown library:

A header
========

A paragraph

The desired output would be something like

  A header
  ¶

A paragraph

Answer:

Thanks @BlaXpirit (see answer)

Use headerid python markdown extension and input the following:

# A header [¶](#a-header) {#a-header}

A paragraph

This generates the following output:

  A header
  ¶

Then use some css styling to get the common output, something like :

h1 a{visibility:hidden;}
h1:hover a{visibility:visible;}

Body:
Markdown in Python has an extension that does this.

It also lets you specify an id you like for the header, like this:

A header            {#a-header}
========


问:
Record created in test class is not visible in controller
I am creating a test class for a controller and i dont know for what reason a record created for a object is not visible in a method in controller.That method is having a select query which is giving the blank output. If i run the same query in test class , that is giving me the output. Rest of the records for different objects are also visible and working fine.

Is there any specific reason why the record is not available in a method in a controller??

答:
Check 1:

It might be some access issue. So check the Object access in the Profile level.

If you are a System Admin, then try to create records by running as System Admin user.

```<code>User adminUser = [SELECT Id,Name FROM User WHERE Id =: UserInfo.getUserId()];
System.runAs(adminUser){
    //Test Class block
}
</code>```

Check 2:

If it is happening in a Trigger or Trigger_handler related Test Class. Then please see the below scenario.

Ex: Assume, you are working on Order and OrderItem objects. You have a trigger on Order object (after insert or after update).

To create any OrderItem, you first need the Order to be created. So you will insert an Order first and then OrderItem follows.

Since we have a trigger on Order object, the trigger will start to execute as soon as we insert the Order record.
In trigger we may have used the OrderItem records also. But they will not be available in Trigger yet.

Because, we have only created the Order record so far and the trigger started executing immediately and we are yet to create the OrderItem.

So, try the below approach:

```<code>Create/Insert an Order.
Create OrderItems by using the above Order id.
Now just do a simple update on Order record and see if it works.
</code>```

Body:
Check 1:

It might be some access issue. So check the Object access in the Profile level.

If you are a System Admin, then try to create records by running as System Admin user.

User adminUser = [SELECT Id,Name FROM User WHERE Id =: UserInfo.getUserId()];
System.runAs(adminUser){
    //Test Class block
}

Check 2:

If it is happening in a Trigger or Trigger_handler related Test Class. Then please see the below scenario.

Ex: Assume, you are working on Order and OrderItem objects. You have a trigger on Order object (after insert or after update).

To create any OrderItem, you first need the Order to be created. So you will insert an Order first and then OrderItem follows.

Since we have a trigger on Order object, the trigger will start to execute as soon as we insert the Order record.
In trigger we may have used the OrderItem records also. But they will not be available in Trigger yet.

Because, we have only created the Order record so far and the trigger started executing immediately and we are yet to create the OrderItem.

So, try the below approach:

Create/Insert an Order.
Create OrderItems by using the above Order id.
Now just do a simple update on Order record and see if it works.


问:
PyQt5 how to show keyinput in QLineEdit?
I am trying to get a readonly QLineEdit in a second window to show the name of the key pressed. For example if I press key a it shows a Key and if I press the spacebar it shows SpaceBar Key. I searched the net for solutions but most of them were about how to close a window when a certain key is pressed.

I have a working sample made with tkinter linked below.
https://gist.github.com/sangonkim/e397c420d93485f3896f9440bbcc77aa

I made 2 simple windows with QDesigner for the question.

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(347, 259)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 110, 121, 28))
        self.pushButton.clicked.connect(self.connect)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def connect(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow2()
        self.ui.setupUi(self.window)
        self.window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "To next window"))

class Ui_MainWindow2(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(384, 261)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(130, 100, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Main_Window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(Main_Window)
    Main_Window.show()
    sys.exit(app.exec_())
</code>```

I've tried adding

```<code>def keyinput(self, event):
    print(event.key())
</code>```

to Ui_MainWindow2see if I can capture the key I an typing. But it does not work.

And also tried

```<code>def keyinput(self, event):
    self.lineEdit.setText(str(event.key()))
</code>```

And failed.

答:
into setupUi add:

```<code>MainWindow.keyPressEvent = self.newOnkeyPressEvent
</code>```

and define function:

```<code>def newOnkeyPressEvent(self, event):

    key = event.key()
    modifiers = int(event.modifiers())
    keyname = QtGui.QKeySequence(modifiers + key).toString()
    print(keyname)
    self.lineEdit.setText(str(keyname))
</code>```

full code:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(347, 259)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 110, 121, 28))
        self.pushButton.clicked.connect(self.connect)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def connect(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow2()
        self.ui.setupUi(self.window)
        self.window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "To next window"))

class Ui_MainWindow2(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(384, 261)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(130, 100, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)

        MainWindow.keyPressEvent = self.newOnkeyPressEvent

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

    def newOnkeyPressEvent(self, event):

        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit.setText(str(keyname))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Main_Window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(Main_Window)
    Main_Window.show()
    sys.exit(app.exec_())
</code>```

Body:
I am trying to get a readonly QLineEdit in a second window to show the name of the key pressed. For example if I press key a it shows a Key and if I press the spacebar it shows SpaceBar Key. I searched the net for solutions but most of them were about how to close a window when a certain key is pressed.

I have a working sample made with tkinter linked below.
https://gist.github.com/sangonkim/e397c420d93485f3896f9440bbcc77aa

I made 2 simple windows with QDesigner for the question.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(347, 259)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 110, 121, 28))
        self.pushButton.clicked.connect(self.connect)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def connect(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow2()
        self.ui.setupUi(self.window)
        self.window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "To next window"))

class Ui_MainWindow2(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(384, 261)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(130, 100, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Main_Window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(Main_Window)
    Main_Window.show()
    sys.exit(app.exec_())

I've tried adding

def keyinput(self, event):
    print(event.key())

to Ui_MainWindow2see if I can capture the key I an typing. But it does not work.

And also tried

def keyinput(self, event):
    self.lineEdit.setText(str(event.key()))

And failed.

Body:
into setupUi add:

MainWindow.keyPressEvent = self.newOnkeyPressEvent

and define function:

def newOnkeyPressEvent(self, event):

    key = event.key()
    modifiers = int(event.modifiers())
    keyname = QtGui.QKeySequence(modifiers + key).toString()
    print(keyname)
    self.lineEdit.setText(str(keyname))

full code:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(347, 259)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 110, 121, 28))
        self.pushButton.clicked.connect(self.connect)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def connect(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow2()
        self.ui.setupUi(self.window)
        self.window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "To next window"))

class Ui_MainWindow2(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(384, 261)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(130, 100, 113, 21))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)

        MainWindow.keyPressEvent = self.newOnkeyPressEvent

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

    def newOnkeyPressEvent(self, event):

        key = event.key()
        modifiers = int(event.modifiers())
        keyname = QtGui.QKeySequence(modifiers + key).toString()
        print(keyname)
        self.lineEdit.setText(str(keyname))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Main_Window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(Main_Window)
    Main_Window.show()
    sys.exit(app.exec_())


问:
How to distinguish between two WebElements with the same id?
I have two fields with the same id on a single HTML page (using Angular)
How to I distinguise between the two without creating a collection and referring to the indexes>

An example of one field is below

I've tried this

```<code>#content-container > inv-sidebar-layout-content > ng-component > ng-component > section > div.row.tab-container > as-split > as-split-area:nth-child(1) > article > inv-people-tabs > inv-vertical-tabs-list > div.tab-content-container > div > inv-tab:nth-child(7) > div > inv-people-contact-details-tab > section > div.left-column > inv-person-contact-details > section > inv-address-edit > section > div:nth-child(2) > input
</code>```

but it's too long and cumbersome

The HTML for the first field is

```<code><input _ngcontent-gec-c113="" class="inv-input" id="towncity" formcontrolname="TownCity">
</code>```

and for the second it is

```<code><input _ngcontent-gec-c113="" class="inv-input ng-pristine ng-valid ng-touched" id="towncity" formcontrolname="TownCity" ng-reflect-name="TownCity">
</code>```

答:
The elements have different classes so you can distinguish them using class attribute

Example selectors:

First element:

```<code>//input[@id='towncity' and not(contains(@class,'touched'))]
</code>```

Second element

```<code>//input[@id='towncity' and contains(@class,'touched')]
</code>```

More information:

XPath Syntax

XPath Operators & Functions

Body:
I have two fields with the same id on a single HTML page (using Angular)
How to I distinguise between the two without creating a collection and referring to the indexes>

An example of one field is below

I've tried this

#content-container > inv-sidebar-layout-content > ng-component > ng-component > section > div.row.tab-container > as-split > as-split-area:nth-child(1) > article > inv-people-tabs > inv-vertical-tabs-list > div.tab-content-container > div > inv-tab:nth-child(7) > div > inv-people-contact-details-tab > section > div.left-column > inv-person-contact-details > section > inv-address-edit > section > div:nth-child(2) > input

but it's too long and cumbersome

The HTML for the first field is

<input _ngcontent-gec-c113="" class="inv-input" id="towncity" formcontrolname="TownCity">

and for the second it is

<input _ngcontent-gec-c113="" class="inv-input ng-pristine ng-valid ng-touched" id="towncity" formcontrolname="TownCity" ng-reflect-name="TownCity">

Body:
The elements have different classes so you can distinguish them using class attribute

Example selectors:

First element:

//input[@id='towncity' and not(contains(@class,'touched'))]

Second element

//input[@id='towncity' and contains(@class,'touched')]

More information:

XPath Syntax

XPath Operators & Functions


问:
jQuery - how can I get a value of the next option in a dropdown after the selected one?
I have a drop down with a selected option at index = 0.
How can I in jquery get the value of the next option at index = 1?
Of course I need to do that without specifying the value of the next option because I can;t assume what it will be at this point.

thx

答:
You can write

```<code>$('#dropDownId option:selected').next().val()
</code>```

Or

```<code>$('#dropDownId option:selected+option').val()
</code>```

Body:
You can write

$('#dropDownId option:selected').next().val()

Or

$('#dropDownId option:selected+option').val()


问:
On Windows what is the difference between Git Bash vs Windows Power Shell vs Command prompt
I am a Mac guy who is used to Mac's Terminal. Now I am using Windows.

Whats the diff between those CLI options?

When should I use one over the other?

Are there more CLI options that I should consider?

What CLI would you use if you were a Mac person trying to adapt to Windows?

The reason I am trying to use Windows, is that I want to ensure the CLI of my Docker projects work for Windows users, that I can write files coming from my container to Windows and ensure my README files have instructions for Windows users.  And basically test everything I do on Windows too, like Python.

答:
Git bash is bash, which is IIRC also the default shell on MacOS.  It is not the default shell on Windows, although several implementations exist (CygWin, MinGW, ...).

Git is bundled with a number of POSIX (UNIX/Linux/etc.) utilities in addition to bash; in order to avoid "collisions" with similarly named Windows commands, the most common installation option is to install bash in such a way that the other POSIX commands are only available when running bash.  The Git installer will create a shortcut to launch this "private" version of bash, hence "git bash".

The Windows command prompt runs the default Windows shell, CMD.EXE, which is a derivative of the old MS-DOS command shell, COMMAND.COM.  It is much less capable than most POSIX shells; for example, it did not until relatively recently support an if/then/else construct, and it does not support shell functions or aliases (although there are some workarounds for these limitations).

PowerShell is more of a scripting environment.  I'd compare it to Perl on UNIX/Linux systems -- much more powerful than the standard shell, but not necessarily something I'd want to use at the command line.

One thing to be aware of is that some of the nicer PowerShell features may require you to update your version of PowerShell -- the version bundled with Windows is typically a few years old.  And updating PowerShell usually requires admin privilege; depending on the version, you may also need to update the .NET framework.

If I were a Mac person trying to adapt to Windows ... it depends.  In the short term it would be easier to use something familiar like bash.  But long term, you -- and more importantly, your potential users -- may not want to be dependent on a third party tool, especially since for Windows users that will typically present an additional learning curve.

As to which to use when ... it really depends on what you're trying to accomplish -- both in terms of technical functionality and the interface you want to present to your users.  As noted above, I'd consider PowerShell more appropriate for scripting than the CLI, unless you just need to run a cmdlet (either a built-in or one you've created yourself).


问:
ggplot2 position_stack(vjust) with absolute unit rather than proportional
I have a stacked barplot and I want to label the value of each bar inside the bar. Here is an example :

```<code>diamonds %>%
  group_by(cut) %>%
  count(low_price = price < 3000) %>%
  ggplot() +
  aes(
    x = cut,
    y = n,
    fill = low_price
    ) +
  geom_col() +
  geom_text(
    aes(label = n),
    position = position_stack(vjust = 0.8)
    )
</code>```

I'm using position_stack(vjust = 0.8) to adjust the vertical position of the label within the bar. The problem is the adjustment is a percentage: it actualy places the label at 80% of the total height of the bar.
I would like to have something similar in absolute unit: for example -1 cm or - 30 px from the top of each bar. Is there a way to do that ?

Sorry for bad english and thanks for help.

答:
I'd recommend using the geom_text vjust rather than the position_stack vjust. It isn't a customizable absolute unit like you ask for, but it is relative to the size of the text, which is an absolute size in point size, so it is not proportional to the size of the bar.

```<code>diamonds %>%
  group_by(cut) %>%
  count(low_price = price < 3000) %>%
  ggplot() +
  aes(
    x = cut,
    y = n,
    fill = low_price
    ) +
  geom_col() +
  geom_text(
    aes(label = n),
    position = position_stack(),
    vjust = 1.2
    )
</code>```

Body:
I have a stacked barplot and I want to label the value of each bar inside the bar. Here is an example :

diamonds %>%
  group_by(cut) %>%
  count(low_price = price < 3000) %>%
  ggplot() +
  aes(
    x = cut,
    y = n,
    fill = low_price
    ) +
  geom_col() +
  geom_text(
    aes(label = n),
    position = position_stack(vjust = 0.8)
    )

I'm using position_stack(vjust = 0.8) to adjust the vertical position of the label within the bar. The problem is the adjustment is a percentage: it actualy places the label at 80% of the total height of the bar.
I would like to have something similar in absolute unit: for example -1 cm or - 30 px from the top of each bar. Is there a way to do that ?

Sorry for bad english and thanks for help.

Body:
I'd recommend using the geom_text vjust rather than the position_stack vjust. It isn't a customizable absolute unit like you ask for, but it is relative to the size of the text, which is an absolute size in point size, so it is not proportional to the size of the bar.

diamonds %>%
  group_by(cut) %>%
  count(low_price = price < 3000) %>%
  ggplot() +
  aes(
    x = cut,
    y = n,
    fill = low_price
    ) +
  geom_col() +
  geom_text(
    aes(label = n),
    position = position_stack(),
    vjust = 1.2
    )


问:
A different kind of jquery sortable
I have elements of different sizes that are arranged somewhat acording to a grid (like in the image below) and I want to drag and drop properly those elements. Is there a plugin that would do that? Sortable does not do it properly...

EDIT:
By "properly" I mean it should act normal (meaning if I drag and drop the big one on the right it should rearrange inteligently). Maybe I just need to see one that does what I want and I'll make it do stuff "properly"

EDIT:
If you move the big block on the right (how it should look like).

EDIT:
I just want a way to rearrange a grid-like layout like this one. I can accept other ideas..

答:
I know you asked for this a while ago, but I finally remembered what it was called...

http://masonry.desandro.com/

Cheers.

ContentLicense: CC BY-SA 2.5

Title: A different kind of jquery sortable


问:
Rectangle.contains() method never returns true
The diagram that i use returns a org.eclipse.draw2d.geometry.Rectangle with co-ordinates Rectangle(20.0, 450.0, 0.0, 0.0). I want to check if a point (20,450) is present within it.

I have tried this with contains and equals method. but it doesn't return true. what am i doing wrong?

```<code>if (rectangle.contains(new Point(20, 450)))
{
   return true;
}
</code>```

I except the output to be true. I can change the co-ordinates of the point but not the co-ordinates of the rectangle.

答:
The documentation literally explains this.

```<code>public boolean contains(double x, double y)
</code>```

Returns whether the given coordinates are within the boundaries of
  this Rectangle. The boundaries are inclusive of the top and left
  edges, but exclusive of the bottom and right edges.

Your point is the bottom right corner.

Body:
The diagram that i use returns a org.eclipse.draw2d.geometry.Rectangle with co-ordinates Rectangle(20.0, 450.0, 0.0, 0.0). I want to check if a point (20,450) is present within it.

I have tried this with contains and equals method. but it doesn't return true. what am i doing wrong?

if (rectangle.contains(new Point(20, 450)))
{
   return true;
}

I except the output to be true. I can change the co-ordinates of the point but not the co-ordinates of the rectangle.

Body:
The documentation literally explains this.

public boolean contains(double x, double y)

Returns whether the given coordinates are within the boundaries of
  this Rectangle. The boundaries are inclusive of the top and left
  edges, but exclusive of the bottom and right edges.

Your point is the bottom right corner.


问:
Can I somehow use nested functions in ANSI C?
I have background with high level languages, such as Java/Kotlin/Scala. Now I need to create a C library, but it's pretty hard for me to work without closures.

There is the nice extension in GCC, called "nested functions", that (if I correctly understood) is exactly what I need. Also the Apple "blocks" extension looks interesting. But I need a code, that will work with any compiler.

Does any existing solution present? I've seen some projects, that allow generating C code: https://github.com/dbohdan/compilers-targeting-c. But I really don't need another language, just one feature - closures. (I think that it hard to maintain completely different language and result C code will be not optimized).

UPD
Some explanation, why do I need closures.

Let say we have some function, connect(void (*on_failed_callback)());. It manages a connection in some way, and when the connection is lost, it calls the callback. And it takes 0 arguments, but I want to create some function that will bring some data with callback. If I've correctly understood, the most common used solution is to pass the callback with some arg connect(void (*on_failed_callback)(void *callback_arg), void* arg);. But it leads to a boilerplate code, that can be fixed by nested functions.

So next code:

```<code>void connect(void (*on_failed_callback)(void* arg), void* arg) {
    ...
    on_failed_callback(arg);
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char *msg = "Failed connection";
    ...
    connect(print_error, msg);
}
</code>```

Can be simplified to next:

```<code>void connect(void (*on_failed_callback)()) {
    ...
    on_failed_callback();
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char* msg = "Failed connection";
    ...
    void callback() {
       print_error(msg);
    }
    connect(callback);
}
</code>```

I mean, I want some tool/app, that analyzes my code with closures/nested functions and generates pure ANSI C code.

答:
Does any existing solution present?

It depends on what you mean.  Standard C does not provide closures, nested functions, or lambdas / blocks as language features.  But there is nothing you can do in some other language that has any or all of these that you cannot do in C without.  In fact, some languages that do have these features are themselves implemented in C.

In particular, your first example is approximately the normal C idiom for generic callbacks.  The callback function accepts a pointer to an object containing any data it needs, and the callback-registration interface accepts a pointer to the appropriate object together with a pointer to the function.  When the callback is triggered, the registered data pointer is passed to it.

Note, by the way, that this is a more general facility than closures alone afford, because the data on which the callback will operate do not need to be in scope where the function is defined.  Among other things, this permits standard, reusable callback implementations to be provided, where the association with specific data is made only at the point of callback registration.  In the event that multiple callbacks can be simultaneously associated with the same event, it also allows the same callback to be reused, with different data, for the same event.

Body:
I have background with high level languages, such as Java/Kotlin/Scala. Now I need to create a C library, but it's pretty hard for me to work without closures.

There is the nice extension in GCC, called "nested functions", that (if I correctly understood) is exactly what I need. Also the Apple "blocks" extension looks interesting. But I need a code, that will work with any compiler.

Does any existing solution present? I've seen some projects, that allow generating C code: https://github.com/dbohdan/compilers-targeting-c. But I really don't need another language, just one feature - closures. (I think that it hard to maintain completely different language and result C code will be not optimized).

UPD
Some explanation, why do I need closures.

Let say we have some function, connect(void (*on_failed_callback)());. It manages a connection in some way, and when the connection is lost, it calls the callback. And it takes 0 arguments, but I want to create some function that will bring some data with callback. If I've correctly understood, the most common used solution is to pass the callback with some arg connect(void (*on_failed_callback)(void *callback_arg), void* arg);. But it leads to a boilerplate code, that can be fixed by nested functions.

So next code:

void connect(void (*on_failed_callback)(void* arg), void* arg) {
    ...
    on_failed_callback(arg);
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char *msg = "Failed connection";
    ...
    connect(print_error, msg);
}

Can be simplified to next:

void connect(void (*on_failed_callback)()) {
    ...
    on_failed_callback();
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char* msg = "Failed connection";
    ...
    void callback() {
       print_error(msg);
    }
    connect(callback);
}

I mean, I want some tool/app, that analyzes my code with closures/nested functions and generates pure ANSI C code.


问:
Rasa X - Google Assistant connector doesn't receive any messages from Rasa
I'm creating a connector for Rasa X (rasa 1.0) to work with Google Assistant as a front-end. Before 1.0 came out, this tutorial: https://medium.com/rasa-blog/going-beyond-hey-google-building-a-rasa-powered-google-assistant-5ff916409a25 worked really well. However, when I tried to run Rasa X on the same structure there were incompatibilities between my old Flask-based connector and the Rasa agent starting the project.

In the new version, rasa.core.agent.handle_channels([input_channel], http_port=xxxx) uses Sanic instead, which seems to be incompatible with my old method.

I have tried to convert the old Flask connector to a Sanic(never used it before) one and I used Postman to check the health route, which works. I also receive the payload from Assistant. However, when I forward this to the Rasa agent, I get nothing in return.

This is the new Sanic connector:

```<code>class GoogleAssistant(InputChannel):

    @classmethod
    def name(cls):
        return "google_assistant"

    def blueprint(self, on_new_message):
        # this is a Sanic Blueprint
        google_webhook = sBlueprint("google_webhook")

        @google_webhook.route("/", methods=['GET'])
        def health(request):
            return response.json({"status": "ok"})

        @google_webhook.route("/webhook", methods=["POST"])
        def receive(request):
            #payload = json.loads(request)
            payload = request.json
            sender_id = payload["user"]['userId']
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']

            try:
                if intent == "actions.intent.MAIN":
                    message = "<speak>Hello! <break time=\"1\"/> Welcome to the Rasa-powered Google Assistant skill. You can start by saying hi."
                else:
                    # Here seems to be the issue. responses is always empty
                    out = CollectingOutputChannel()
                    on_new_message(UserMessage(text,out,sender_id))
                    responses = [m["text"] for m in out.messages]
                    message = responses[0]
            except LookupError as e:
                message = "RASA_NO_REPLY"
                print(e)

            r = json.dumps("some-response-json")
            return HTTPResponse(body=r, content_type="application/json")

        return google_webhook
</code>```

And this is the script starting the project:

```<code>action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('path-to-model')
agent = Agent.load('path-to-model-2', interpreter = nlu_interpreter, action_endpoint=action_endpoint)

input_channel = GoogleAssistant()
agent.handle_channels([input_channel], http_port=5010)
</code>```

I expect the output to be the text selected by the Rasa agent as a reply "This is the reply", but I get nothing (the list is empty).

EDIT

I defined def receive(request): as async def receive(request): and changed on_new_message(UserMessage(text,out,sender_id)) to await on_new_message(UserMessage(text,out,sender_id)). Furthermore, the script starting the project is now:

```<code>loop = asyncio.get_event_loop()

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('path')
agent = Agent.load('path2', interpreter = nlu_interpreter, action_endpoint=action_endpoint)
input_channel = GoogleAssistant()

loop.run_until_complete(agent.handle_channels([input_channel], http_port=5010))
loop.close()
</code>```

Unfortunately it didn't change anything, still not getting any reply from Rasa on the output channel.

答:
Due to the introduction of the async Sanic server, on_new_message has to be awaited. Try changing your function definition to

```<code>async def receive(request):
</code>```

and the else to

```<code>out = CollectingOutputChannel()
await on_new_message(UserMessage(query, output_channel, user_id))
m = [m['text'] for m in out.messages]
message = responses[0]
</code>```

Body:
I'm creating a connector for Rasa X (rasa 1.0) to work with Google Assistant as a front-end. Before 1.0 came out, this tutorial: https://medium.com/rasa-blog/going-beyond-hey-google-building-a-rasa-powered-google-assistant-5ff916409a25 worked really well. However, when I tried to run Rasa X on the same structure there were incompatibilities between my old Flask-based connector and the Rasa agent starting the project.

In the new version, rasa.core.agent.handle_channels([input_channel], http_port=xxxx) uses Sanic instead, which seems to be incompatible with my old method.

I have tried to convert the old Flask connector to a Sanic(never used it before) one and I used Postman to check the health route, which works. I also receive the payload from Assistant. However, when I forward this to the Rasa agent, I get nothing in return.

This is the new Sanic connector:

class GoogleAssistant(InputChannel):

    @classmethod
    def name(cls):
        return "google_assistant"

    def blueprint(self, on_new_message):
        # this is a Sanic Blueprint
        google_webhook = sBlueprint("google_webhook")

        @google_webhook.route("/", methods=['GET'])
        def health(request):
            return response.json({"status": "ok"})

        @google_webhook.route("/webhook", methods=["POST"])
        def receive(request):
            #payload = json.loads(request)
            payload = request.json
            sender_id = payload["user"]['userId']
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']

            try:
                if intent == "actions.intent.MAIN":
                    message = "<speak>Hello! <break time=\"1\"/> Welcome to the Rasa-powered Google Assistant skill. You can start by saying hi."
                else:
                    # Here seems to be the issue. responses is always empty
                    out = CollectingOutputChannel()
                    on_new_message(UserMessage(text,out,sender_id))
                    responses = [m["text"] for m in out.messages]
                    message = responses[0]
            except LookupError as e:
                message = "RASA_NO_REPLY"
                print(e)

            r = json.dumps("some-response-json")
            return HTTPResponse(body=r, content_type="application/json")

        return google_webhook

And this is the script starting the project:

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('path-to-model')
agent = Agent.load('path-to-model-2', interpreter = nlu_interpreter, action_endpoint=action_endpoint)

input_channel = GoogleAssistant()
agent.handle_channels([input_channel], http_port=5010)

I expect the output to be the text selected by the Rasa agent as a reply "This is the reply", but I get nothing (the list is empty).

EDIT

I defined def receive(request): as async def receive(request): and changed on_new_message(UserMessage(text,out,sender_id)) to await on_new_message(UserMessage(text,out,sender_id)). Furthermore, the script starting the project is now:

loop = asyncio.get_event_loop()

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('path')
agent = Agent.load('path2', interpreter = nlu_interpreter, action_endpoint=action_endpoint)
input_channel = GoogleAssistant()

loop.run_until_complete(agent.handle_channels([input_channel], http_port=5010))
loop.close()

Unfortunately it didn't change anything, still not getting any reply from Rasa on the output channel.

Body:
Due to the introduction of the async Sanic server, on_new_message has to be awaited. Try changing your function definition to

async def receive(request):

and the else to

out = CollectingOutputChannel()
await on_new_message(UserMessage(query, output_channel, user_id))
m = [m['text'] for m in out.messages]
message = responses[0]


问:
The access token is from the wrong issuer 'https://sts.windows.net'
I am using  'azure-arm-resource' for get all resources in azure for my node js project.

https://www.npmjs.com/package/azure-arm-resource

But using this I get some error,

```<code> msRestAzure.interactiveLogin().then(credentials => {
  const azureResources = new resourceManagement.ResourceManagementClient(credentials, subscriptionId);

  azureResources.resources
    .list()
    .then(res => {
      if (filter) {
        return res.filter(r => r.kind === filter);
      } else {
        return res;
      }
    })
    .then(d => {
      console.log('Done Resources');
    });
});
console.log('Pulling...');
 }
</code>```

Error,

```<code> Uncaught (in promise) Error: The access token is from the wrong issuer
'https://sts.windows.net/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/'.
 It must match the tenant 'https://sts.windows.net/xxxx-xxx-xxxx-xxxx-
 c3xxx4xxffd57xx7/'
 associated with this subscription. Please use the authority (URL)
 'https://login.windows.net/xxxx-xxxx-xxx-xxxx-xxxxxxxx' to get the token.
  Note, if the subscription is transferred to another tenant there is no
 impact to the services, but information about new tenant could take time to
  propagate (up to an hour). If you just transferred your subscription and
  this error message, please try back later.
</code>```

Device Token Credentials undefined in azure interactive login

答:
It means the subscription is not part of the tenant the account you logged in with is on.

Make sure the account you logged in with has access to the subscription used.

Body:
I am using  'azure-arm-resource' for get all resources in azure for my node js project.

https://www.npmjs.com/package/azure-arm-resource

But using this I get some error,

 msRestAzure.interactiveLogin().then(credentials => {
  const azureResources = new resourceManagement.ResourceManagementClient(credentials, subscriptionId);

  azureResources.resources
    .list()
    .then(res => {
      if (filter) {
        return res.filter(r => r.kind === filter);
      } else {
        return res;
      }
    })
    .then(d => {
      console.log('Done Resources');
    });
});
console.log('Pulling...');
 }

Error,

 Uncaught (in promise) Error: The access token is from the wrong issuer
'https://sts.windows.net/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/'.
 It must match the tenant 'https://sts.windows.net/xxxx-xxx-xxxx-xxxx-
 c3xxx4xxffd57xx7/'
 associated with this subscription. Please use the authority (URL)
 'https://login.windows.net/xxxx-xxxx-xxx-xxxx-xxxxxxxx' to get the token.
  Note, if the subscription is transferred to another tenant there is no
 impact to the services, but information about new tenant could take time to
  propagate (up to an hour). If you just transferred your subscription and
  this error message, please try back later.

Device Token Credentials undefined in azure interactive login


问:
Taking input again if not valid input
I want to program it like that so while taking input of num1,num2 and operation if user doesn't give input in appropriate type it ask the user again for input.</p>

```<code>operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))
</code>```

答:
You are looking for a while loop:

```<code>num1 = None
while num1 is None:
    try:
        num1 = int(input('Enter a number: '))
    except ValueError:
        print('Invalid, input must be an integer!')
    else:
       # Examples of further tests you could add.
       # code here in the try-else block is only executed if the "try-part" was successful
       if num1 < 0:
           print('Number might not be negative')
           num1 = None
       elif:
           ...

</code>```

Note: Please, consider searching the forum first for similar questions, before you post your own, otherwise people might downvote you and mark it as duplicate.

Title: Taking input again if not valid input

Body:
I want to program it like that so while taking input of num1,num2 and operation if user doesn't give input in appropriate type it ask the user again for input.

operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))

Body:
You are looking for a while loop:

num1 = None
while num1 is None:
    try:
        num1 = int(input('Enter a number: '))
    except ValueError:
        print('Invalid, input must be an integer!')
    else:
       # Examples of further tests you could add.
       # code here in the try-else block is only executed if the "try-part" was successful
       if num1 < 0:
           print('Number might not be negative')
           num1 = None
       elif:
           ...

Note: Please, consider searching the forum first for similar questions, before you post your own, otherwise people might downvote you and mark it as duplicate.


问:
Python remove dictionary items when a value of a specific key is duplicate
I have a dictionary of this form:

```<code>nodes = [
    {"name": n1, "nodename": nod1, "nodetype": t1, "nodeip": nip1},
    {"name": n2, "nodename": nod2, "nodetype": t2, "nodeip": nip2},
    {"name": n3, "nodename": nod3, "nodetype": t1, "nodeip": nip3},
    {"name": n4, "nodename": nod4, "nodetype": t3, "nodeip": nip4},
    {"name": n5, "nodename": nod5, "nodetype": t2, "nodeip": nip5},
]
</code>```

and I want to remove all keys that have a duplicate value in "nodetype" such as:

```<code>uniq_nodes_per_type = [
    {"name": n1, "nodename": nod1, "nodetype": t1, "nodeip": nip1},
    {"name": n2, "nodename": nod2, "nodetype": t2, "nodeip": nip2},
    {"name": n4, "nodename": nod4, "nodetype": t3, "nodeip": nip4},
]
</code>```

It is not important which of n1,n3 or n2,n5 will be selected.
How can I get the above result?

I have tried to iterate the values like that:

```<code>seen = set()
uniq_nodes_per_type = {}
for node in node_list.items():
    nodetype = node["nodetype"]
    if nodetype not in seen:
        seen.add(nodetype)
        uniq_nodes.update(node)
</code>```

答:
Assuming your input was meant to be a list of dicts:

```<code>nodes = [
    {"name": "n1", "nodename": "nod1", "nodetype": "t1", "nodeip": "nip1"},
    {"name": "n2", "nodename": "nod2", "nodetype": "t2", "nodeip": "nip2"},
    {"name": "n3", "nodename": "nod3", "nodetype": "t1", "nodeip": "nip3"},
    {"name": "n4", "nodename": "nod4", "nodetype": "t3", "nodeip": "nip4"},
    {"name": "n5", "nodename": "nod5", "nodetype": "t2", "nodeip": "nip5"},
]
</code>```

Building a dictionary based on nodetype keys will remove duplicates:

```<code>nodetype_dict = {x["nodetype"]: x for x in nodes}

sorted(nodetype_dict.values(), key=lambda x: x["nodetype"])
[{'name': 'n3', 'nodeip': 'nip3', 'nodename': 'nod3', 'nodetype': 't1'},
 {'name': 'n5', 'nodeip': 'nip5', 'nodename': 'nod5', 'nodetype': 't2'},
 {'name': 'n4', 'nodeip': 'nip4', 'nodename': 'nod4', 'nodetype': 't3'}]
</code>```

Body:
I have a dictionary of this form:

nodes = [
    {"name": n1, "nodename": nod1, "nodetype": t1, "nodeip": nip1},
    {"name": n2, "nodename": nod2, "nodetype": t2, "nodeip": nip2},
    {"name": n3, "nodename": nod3, "nodetype": t1, "nodeip": nip3},
    {"name": n4, "nodename": nod4, "nodetype": t3, "nodeip": nip4},
    {"name": n5, "nodename": nod5, "nodetype": t2, "nodeip": nip5},
]

and I want to remove all keys that have a duplicate value in "nodetype" such as:

uniq_nodes_per_type = [
    {"name": n1, "nodename": nod1, "nodetype": t1, "nodeip": nip1},
    {"name": n2, "nodename": nod2, "nodetype": t2, "nodeip": nip2},
    {"name": n4, "nodename": nod4, "nodetype": t3, "nodeip": nip4},
]

It is not important which of n1,n3 or n2,n5 will be selected.
How can I get the above result?

I have tried to iterate the values like that:

seen = set()
uniq_nodes_per_type = {}
for node in node_list.items():
    nodetype = node["nodetype"]
    if nodetype not in seen:
        seen.add(nodetype)
        uniq_nodes.update(node)

Body:
Assuming your input was meant to be a list of dicts:

nodes = [
    {"name": "n1", "nodename": "nod1", "nodetype": "t1", "nodeip": "nip1"},
    {"name": "n2", "nodename": "nod2", "nodetype": "t2", "nodeip": "nip2"},
    {"name": "n3", "nodename": "nod3", "nodetype": "t1", "nodeip": "nip3"},
    {"name": "n4", "nodename": "nod4", "nodetype": "t3", "nodeip": "nip4"},
    {"name": "n5", "nodename": "nod5", "nodetype": "t2", "nodeip": "nip5"},
]

Building a dictionary based on nodetype keys will remove duplicates:

nodetype_dict = {x["nodetype"]: x for x in nodes}

sorted(nodetype_dict.values(), key=lambda x: x["nodetype"])
[{'name': 'n3', 'nodeip': 'nip3', 'nodename': 'nod3', 'nodetype': 't1'},
 {'name': 'n5', 'nodeip': 'nip5', 'nodename': 'nod5', 'nodetype': 't2'},
 {'name': 'n4', 'nodeip': 'nip4', 'nodename': 'nod4', 'nodetype': 't3'}]


问:
Creating table with dimension as rows and days between dates as columns
I have a data set of tickets broken into categories based on their operational category. I also calculated the time in between the start date and resolve date for each of these tickets. I want to display the count of each number of days to resolve per category.

Such as this:

I have tried including my calculated days to resolve variable as a column header but it is not working.

答:
So I was able to get it to work making a huge formula for datediff instead of something simple. I am sure there is a more simple solution but here is what I did for my "Time to Close" category:

```<code>IF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 0 THEN "0"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 1 THEN "1"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 2 THEN "2"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 3 THEN "3"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 4 THEN "4"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 5 THEN "5"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 6 THEN "6"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 7 THEN "7"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 8 THEN "8"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 9 THEN "9"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 10 THEN "10"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 11 THEN "11"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 12 THEN "12"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 13 THEN "13"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 14 THEN "14"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 15 THEN "15"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 16 THEN "16"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 17 THEN "17"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 18 THEN "18"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 19 THEN "19"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 20 THEN "20"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 21 THEN "21"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 22 THEN "22"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 23 THEN "23"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 24 THEN "24"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 25 THEN "25"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 26 THEN "26"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 27 THEN "27"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 28 THEN "28"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 29 THEN "29"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 30 THEN "30"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
> 30 THEN ">30"
ELSE "Still Open"
END
</code>```

Making this my columns, my operational category my rows and dragging count of operational category to text gave the desired result.

Body:
So I was able to get it to work making a huge formula for datediff instead of something simple. I am sure there is a more simple solution but here is what I did for my "Time to Close" category:

IF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 0 THEN "0"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 1 THEN "1"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 2 THEN "2"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 3 THEN "3"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 4 THEN "4"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 5 THEN "5"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 6 THEN "6"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 7 THEN "7"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 8 THEN "8"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 9 THEN "9"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 10 THEN "10"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 11 THEN "11"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 12 THEN "12"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 13 THEN "13"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 14 THEN "14"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 15 THEN "15"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 16 THEN "16"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 17 THEN "17"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 18 THEN "18"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 19 THEN "19"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 20 THEN "20"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 21 THEN "21"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 22 THEN "22"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 23 THEN "23"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 24 THEN "24"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 25 THEN "25"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 26 THEN "26"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 27 THEN "27"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 28 THEN "28"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 29 THEN "29"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
= 30 THEN "30"
ELSEIF (DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
> 30 THEN ">30"
ELSE "Still Open"
END

Making this my columns, my operational category my rows and dragging count of operational category to text gave the desired result.


问:
Problems with converting a string to timespan in order to sum a column imported from CSV
I want to import a CSV file with my working hours. Format is as follows:

```
Description;Start Time;End Time;Duration;Day
```

When I import the CSV, each object gets imported as string.
I try to convert the colmn 'Duration' as [timespan] in order to sum this column.
This does not work.

```<code>$import = Import-Csv -Path "C:\admin\test3\tst_tasks_Mai-2019.csv" -Delimiter ";" |
          Sort-Object -Top 15
$sort_description = $import | Sort-Object {$_.Description}
$set_dateformat = $sort_description | ForEach-Object {
    $_.Duration = [timespan]$_.Duration
}
</code>```

Error Message:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.TimeSpan"

答:
Times and dates have many different formats based on culture, with many possible places for ambiguity... one string doesn't always (or even often) map to exactly one one TimeSpan.  Therefore, it's not enough to simply cast the string via [timespan]. You must parse the string.

You can try this, but I'm not sure you won't also need to do something else to create the data project you're after, or use a Parse() overload that allows you to be more precise about the expected format:

```<code> $_.Duration = System.TimeSpan::Parse($_.Duration)
</code>```

Body:
I want to import a CSV file with my working hours. Format is as follows:

Description;Start Time;End Time;Duration;Day

When I import the CSV, each object gets imported as string.
I try to convert the colmn 'Duration' as [timespan] in order to sum this column.
This does not work.

$import = Import-Csv -Path "C:\admin\test3\tst_tasks_Mai-2019.csv" -Delimiter ";" |
          Sort-Object -Top 15
$sort_description = $import | Sort-Object {$_.Description}
$set_dateformat = $sort_description | ForEach-Object {
    $_.Duration = [timespan]$_.Duration
}

Error Message:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.TimeSpan"

Body:
Times and dates have many different formats based on culture, with many possible places for ambiguity... one string doesn't always (or even often) map to exactly one one TimeSpan.  Therefore, it's not enough to simply cast the string via [timespan]. You must parse the string.

You can try this, but I'm not sure you won't also need to do something else to create the data project you're after, or use a Parse() overload that allows you to be more precise about the expected format:

 $_.Duration = System.TimeSpan::Parse($_.Duration)


问:
Accessing Inner Array Values Properly With ForEach() - JavaScript
I have

b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach(element => element += 2)
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})```

And I'm wondering why this is logging

The value at 3 is 4,5

Instead of

The value at 3 is 6, 7

I thought I'd accessed the inner array by checking if the value is an array, and then I did another .forEach loop to access each element of that inner-array?

Trying to fully understand .forEach() in JS. Thanks!

答:
You are editing the property, not the value, but then you are not storing the new property anywhere. You should reference the value you are logging, not the properties:

b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach((element, i) => value[i] += 2)
    } else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})```
</div>
</div>
</p>

<p>Should you want to avoid writing this, you should use map to return a new array with the modified values: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>b = [1, 2, 3, [4, 5], 6];

b = b.map(value => Array.isArray(value) ? value.map(el => el + 2) : value + 2)

console.log(b)</code>```

Body:
I have

b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach(element => element += 2)
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})

And I'm wondering why this is logging

The value at 3 is 4,5

Instead of

The value at 3 is 6, 7

I thought I'd accessed the inner array by checking if the value is an array, and then I did another .forEach loop to access each element of that inner-array?

Trying to fully understand .forEach() in JS. Thanks!

Body:
You are editing the property, not the value, but then you are not storing the new property anywhere. You should reference the value you are logging, not the properties:

b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach((element, i) => value[i] += 2)
    } else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})

Should you want to avoid writing this, you should use map to return a new array with the modified values:

b = [1, 2, 3, [4, 5], 6];

b = b.map(value => Array.isArray(value) ? value.map(el => el + 2) : value + 2)

console.log(b)


问:
Why does this code throw an error - "Python stopped working"?
In this code, I want to sort some random generated Numbers. If I want to sort more than ~2000 elements, Python stops working when sorting via QuickSort (after it sorted via Bubblesort) and throws "Process finished with exit code -1073741571 (0xC00000FD)". I dont know, why this problem occurs. My recursion depth is extendet, so I dont think this is the problem. Has anyone a idea, how I can solve this problem?

import time
import random
from sys import setrecursionlimit
setrecursionlimit(1000000)

#------------------------------Sortieralgorithmen-----------------------------------------------
#-----------------------------------------------------------------------------------------------

def bubbleSort(array):

    length = len(array)

    for sorted in range(length):

        for j in range(0, length-sorted-1):
            if array[j] > array[j+1] :
                array[j], array[j+1] = array[j+1], array[j]

def help(array, low, high):
    pivot = array[low]
    fromhigh = high
    fromlow = low
    while True:
        while(array[fromhigh]>pivot):
            fromhigh = fromhigh-1
        while(array[fromlow]<pivot):
            fromlow = fromlow+1
        if(fromlow<fromhigh):
            array[fromlow], array[fromhigh] = array[fromhigh], array[fromlow]
        else:
            return fromhigh

def quickSort(array, low, high):
   if (low<high):
       pivot = help(array, low, high)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

#--------------------------------Zeitmessung-----------------------------------------------------
#------------------------------------------------------------------------------------------------

numb_elements = 6000

sortedarray = []
for i in range (0,numb_elements):
    sortedarray.append(i)

notsortedarray = random.sample(range(0,numb_elements),numb_elements)

copy1 = sortedarray.copy()
before = time.time()
bubbleSort(copy1)
after = time.time()
total = after-before
print("Bubblesort sortiertes Array:\t\t" + str(total))

copy2 = notsortedarray.copy()
before = time.time()
bubbleSort(copy2)
after = time.time()
total = after-before
print("Bubblesort nicht sortiertes Array:\t" + str(total))

copy3 = sortedarray.copy()
before = time.time()
quickSort(copy3, 0, len(copy3)-1)
after = time.time()
total = after-before
print("QuickSort sortiertes Array:\t\t\t" + str(total))

copy4 = notsortedarray.copy()
before = time.time()
quickSort(copy4, 0, len(copy4)-1)
after = time.time()
total = after-before
print("QuickSort nicht sortiertes Array:\t" + str(total)+"\t (Worst Case)")
```

Process finished with exit code -1073741571 (0xC00000FD)

答:
You've initially run up against the recursion limit, and (mostly) sensibly raised it in response.

def quickSort(array, low, high):
   if (low<high):
       pivot = help(array, low, high)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)
```

The array you're sorting has 6000 elements. At the first level of recursion, you call quicksort(array(low, pivot)), which splits your array and calls it again on an array with about 3000 elements. This carries on until you're sorting array[0:2], with about 3000 frames on the stack. That final call returns, freeing a frame from the stack, and then the second call to quicksort(array, pivot + 1, high) happens, filling it up again.

If we've reasoned correctly so far, it seems as if the stack grows to about 3k frames deep, bounces back and forth down to there (+/- calls to help()), before finally unwinding all the way back when you get your sorted array back.

If this is the case, then it seems the practical recursion limit, defined by the amount of frames you can fit in the stack, is something less than 3000.

In theory, any recursion algorithm can be solved iteratively, so you could try rewriting quicksort. If you're curious about the maximum recursion depth on your machine and os, you could pass an integer argument that you increment and print in every call. After it blows up, the highest number printed will be your actual recursion depth limit.

setrecursionlimit() lets you take matters into your own hands with the stack. With great power comes great responsibility.

Body:
In this code, I want to sort some random generated Numbers. If I want to sort more than ~2000 elements, Python stops working when sorting via QuickSort (after it sorted via Bubblesort) and throws "Process finished with exit code -1073741571 (0xC00000FD)". I dont know, why this problem occurs. My recursion depth is extendet, so I dont think this is the problem. Has anyone a idea, how I can solve this problem?

import time
import random
from sys import setrecursionlimit
setrecursionlimit(1000000)

#------------------------------Sortieralgorithmen-----------------------------------------------
#-----------------------------------------------------------------------------------------------

def bubbleSort(array):

    length = len(array)

    for sorted in range(length):

        for j in range(0, length-sorted-1):
            if array[j] > array[j+1] :
                array[j], array[j+1] = array[j+1], array[j]

def help(array, low, high):
    pivot = array[low]
    fromhigh = high
    fromlow = low
    while True:
        while(array[fromhigh]>pivot):
            fromhigh = fromhigh-1
        while(array[fromlow]<pivot):
            fromlow = fromlow+1
        if(fromlow<fromhigh):
            array[fromlow], array[fromhigh] = array[fromhigh], array[fromlow]
        else:
            return fromhigh

def quickSort(array, low, high):
   if (low<high):
       pivot = help(array, low, high)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

#--------------------------------Zeitmessung-----------------------------------------------------
#------------------------------------------------------------------------------------------------

numb_elements = 6000

sortedarray = []
for i in range (0,numb_elements):
    sortedarray.append(i)

notsortedarray = random.sample(range(0,numb_elements),numb_elements)

copy1 = sortedarray.copy()
before = time.time()
bubbleSort(copy1)
after = time.time()
total = after-before
print("Bubblesort sortiertes Array:\t\t" + str(total))

copy2 = notsortedarray.copy()
before = time.time()
bubbleSort(copy2)
after = time.time()
total = after-before
print("Bubblesort nicht sortiertes Array:\t" + str(total))

copy3 = sortedarray.copy()
before = time.time()
quickSort(copy3, 0, len(copy3)-1)
after = time.time()
total = after-before
print("QuickSort sortiertes Array:\t\t\t" + str(total))

copy4 = notsortedarray.copy()
before = time.time()
quickSort(copy4, 0, len(copy4)-1)
after = time.time()
total = after-before
print("QuickSort nicht sortiertes Array:\t" + str(total)+"\t (Worst Case)")

Process finished with exit code -1073741571 (0xC00000FD)

Body:
You've initially run up against the recursion limit, and (mostly) sensibly raised it in response.

def quickSort(array, low, high):
   if (low<high):
       pivot = help(array, low, high)
       quickSort(array, low, pivot)
       quickSort(array, pivot + 1, high)

The array you're sorting has 6000 elements. At the first level of recursion, you call quicksort(array(low, pivot)), which splits your array and calls it again on an array with about 3000 elements. This carries on until you're sorting array[0:2], with about 3000 frames on the stack. That final call returns, freeing a frame from the stack, and then the second call to quicksort(array, pivot + 1, high) happens, filling it up again.

If we've reasoned correctly so far, it seems as if the stack grows to about 3k frames deep, bounces back and forth down to there (+/- calls to help()), before finally unwinding all the way back when you get your sorted array back.

If this is the case, then it seems the practical recursion limit, defined by the amount of frames you can fit in the stack, is something less than 3000.

In theory, any recursion algorithm can be solved iteratively, so you could try rewriting quicksort. If you're curious about the maximum recursion depth on your machine and os, you could pass an integer argument that you increment and print in every call. After it blows up, the highest number printed will be your actual recursion depth limit.

setrecursionlimit() lets you take matters into your own hands with the stack. With great power comes great responsibility.


问:
Optional parameters on delegates doesn't work properly
Why this piece of code does not compile? </p>

```<code>delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}
</code>```

答:
Optional parameters are for use on the calling side - not on what is effectively like a single-method-interface implementation. So for example, this should compile:

```<code>delegate void SimpleDelegate(bool x = true);

static void Main()
{
    SimpleDelegate x = Foo;
    x(); // Will print "True"
}

static void Foo(bool y)
{
    Console.WriteLine(y);
}
</code>```

Body:
Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}

Body:
Optional parameters are for use on the calling side - not on what is effectively like a single-method-interface implementation. So for example, this should compile:

delegate void SimpleDelegate(bool x = true);

static void Main()
{
    SimpleDelegate x = Foo;
    x(); // Will print "True"
}

static void Foo(bool y)
{
    Console.WriteLine(y);
}


答:
There are two reasons:

forEach completely ignores the value you return from its callback

You never do anything to update value

If you want to modify value, you'd either do this:

```<code>value = value.map(element => element + 2);
</code>```

...which creates a new array and assigns it to value; note that b is completely unaffected. (This is just like your value += 2 in the other branch, which also doesn't affect b at all.) Live example:

const b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value = value.map(element => element + 2);
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is unaffected:
console.log(`b[3] = ${b[3]}`);```
</div>
</div>
</p>

<p>Or this:</p>

```value.forEach((element, index) => {
    value[index] = element + 2;
});
```

<p>...which changes the original array (inside <code>b</code>), which <strong>doesn't</strong> match the <code>else</code> branch (which doesn't update <code>b</code>). Live example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach((element, index) => {
            value[index] = element + 2;
        });
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is modified:
console.log(`b[3] = ${b[3]}`);</code>```

But, if you want to modify b, you should probably do it consistently. Kobe posted how you'd do that with map, which creates a new array and is often what you want. If you wanted to update the existing array instead, then:

const b = [1, 2, 3, [4, 5], 6];
for (const [bIndex, value] of b.entries()) {
    if (Array.isArray(value)) {
        for (const [vIndex, entry] of value.entries()) {
            value[vIndex] = entry + 2;
        }
    } else {
        b[bIndex] = value + 2;
    }
}
console.log(`b = ${JSON.stringify(b)}`);```

...but Kobe's map solution is usually what I'd reach for unless I had a good reason to update in place.

Title: Accessing Inner Array Values Properly With ForEach() - JavaScript

Body:
There are two reasons:

forEach completely ignores the value you return from its callback

You never do anything to update value

If you want to modify value, you'd either do this:

value = value.map(element => element + 2);

...which creates a new array and assigns it to value; note that b is completely unaffected. (This is just like your value += 2 in the other branch, which also doesn't affect b at all.) Live example:

const b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value = value.map(element => element + 2);
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is unaffected:
console.log(`b[3] = ${b[3]}`);

Or this:

value.forEach((element, index) => {
    value[index] = element + 2;
});

...which changes the original array (inside b), which doesn't match the else branch (which doesn't update b). Live example:

const b = [1, 2, 3, [4, 5], 6];

b.forEach((value, index) => {
    if (Array.isArray(value)) {
        value.forEach((element, index) => {
            value[index] = element + 2;
        });
    }
    else {
        value += 2;
    }
    console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is modified:
console.log(`b[3] = ${b[3]}`);

But, if you want to modify b, you should probably do it consistently. Kobe posted how you'd do that with map, which creates a new array and is often what you want. If you wanted to update the existing array instead, then:

const b = [1, 2, 3, [4, 5], 6];
for (const [bIndex, value] of b.entries()) {
    if (Array.isArray(value)) {
        for (const [vIndex, entry] of value.entries()) {
            value[vIndex] = entry + 2;
        }
    } else {
        b[bIndex] = value + 2;
    }
}
console.log(`b = ${JSON.stringify(b)}`);

...but Kobe's map solution is usually what I'd reach for unless I had a good reason to update in place.


问:
Can scrapy skip the error of empty data and keeping scraping?
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

```<code>import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item
</code>```

error message

```<code>    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'
</code>```

答:
You could check if a value is returned before extracting:

```<code>if response.css("div.subtitle.subtitle-pdp::text"):
    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").get().strip
</code>```

That way the subTitle code line would only run if a value was to be returned...

Body:
I want to scrape product pages from its sitemap, the products page are similar, but not all of them are the same.

for example

Product A
https://www.vitalsource.com/products/environment-the-science-behind-the-stories-jay-h-withgott-matthew-v9780134446400

Product B
https://www.vitalsource.com/products/abnormal-psychology-susan-nolen-hoeksema-v9781259765667

we can see the product A has the subtitle but another one doesn't have.

So I get errors when I trying to scrape all the product pages.

My question is, is there a way to let the spider skip the error for returning no data?

There is a simple way to bypass it. that is not using strip()
But I am wondering if there is a better way to do the job.

import scrapy
import re
from VitalSource.items import VitalsourceItem
from scrapy.selector import Selector
from scrapy.spiders import SitemapSpider

class VsSpider(SitemapSpider):
    name = 'VS'
    allowed_domains = ['vitalsource.com']
    sitemap_urls = ['https://storage.googleapis.com/vst-stargate-production/sitemap/sitemap1.xml.gz']
    sitemap_rules = [
        ('/products/', 'parse_product'),
    ]
    def parse_product(self, response):
        selector = Selector(response=response)
        item = VitalsourceItem()
        item['Ebook_Title'] = response.css('.product-overview__title-header::text').extract()[1].strip
        item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
        print(item)
        return item

error message

    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").extract().strip
AttributeError: 'list' object has no attribute 'strip'

Body:
You could check if a value is returned before extracting:

if response.css("div.subtitle.subtitle-pdp::text"):
    item['Ebook_SubTitle'] = response.css("div.subtitle.subtitle-pdp::text").get().strip

That way the subTitle code line would only run if a value was to be returned...