问:
children widget's closeEvent is not getting called on close
Either I don't understand completely how Qt's event propagation works or something, but I cannot understand why exactly closeEvent is not being called both for QPushButton-derived class and for QWidget-derived one itself.

Shouldn't wid.closeEvent() trigger closeEvents of all children widgets?

```<code>#!/bin/env python
# -*- coding: utf-8 -*-
import sys, os
from Qt.QtCore import *
from Qt.QtWidgets import *
from Qt.QtGui import *

class butt(QPushButton):
    def __init__(self, parent, name='Button'):
        super(self.__class__, self).__init__(parent)
        self.name = name

    def closeEvent(self, e):
        print('butt closeevent')
        e.accept()

class wid(QWidget):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        self.initUI()

    def initUI(self):
        #self.setAttribute(Qt.WA_DeleteOnClose)
        self.vl = QVBoxLayout(self)
        self.button = butt(self)
        self.button.setText('test1')
        self.vl.addWidget(self.button)
        self.button.clicked.connect(QCoreApplication.quit)

    def closeEvent(self, e):
        print('wid closeevent')
        e.accept()

def show():
    app = QApplication(sys.argv)
    win = QMainWindow()
    widget = wid(win)
    win.setCentralWidget(widget)
    win.show()
    app.exec_()

if __name__ == "__main__":
    show()
</code>```

I'm expecting to see 2 lines
    wid closeevent
    butt closeevent
as an output, but I see nothing. Why closeEvent it not being called for them?

答:
In the following examples when you press the button visually you will observe the same behavior: the window will close, but we see the difference, in the first one it is called closeEvent(), and in the second one it is not.

Example1:

#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    button = Button(text="Press me")
    button.clicked.connect(button.close)
    button.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
```

<p>Example2:</p>

<pre class="lang-py prettyprint-override"><code>#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    button = Button(text="Press me")
    button.clicked.connect(QtCore.QCoreApplication.quit)
    button.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

Why do not you call closeEvent when you call QCoreApplication::quit?
Because this method is used to exit the event loop of Qt, and if there is no event loop the events(QCloseEvent) do not work.

When a widget is closed, the children widget is not closed, that is, only if a widget is closed, only its own closeEvent will be called. So if you want the closeevent of the widget to be called, call your method close.

#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def __init__(self, name="Button", parent=None):
        super(Button, self).__init__(parent)
        self.m_name = name

    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        vl = QtWidgets.QVBoxLayout(self)
        button = Button()
        button.setText("test1")
        vl.addWidget(button)
        button.clicked.connect(self.close)

    def closeEvent(self, event):
        print("Widget closeevent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QMainWindow()
    widget = Widget()
    w.setCentralWidget(widget)
    w.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
```

<p>In the previous example depending on how you interact with the widget you will get the following behavior:</p>

<ul>
<li><p>If you press the button the widget will close so it will be called closeEvent, and will not call the closeEvent of the button because even your child is not closing it.</p></li>
<li><p>If you press the "X" button in the window it will not be called the closeEvent of the widget but the QMainWindow, the explanation is the same as the previous one.</p></li>
</ul>

<p><strong>Conclusions:</strong></p>

<ul>
<li><p>Each type of event has its own workflow, some events are only received by the widget and not by the children, while others send the information to the children.</p></li>
<li><p>The close method uses the event loop to notify that the widget is to be closed, but QCoreApplication::quit() terminates the event loop.</p></li>
</ul>

<p><strong>Update:</strong></p>

<p><em>why wid.closeEvent is not called when user pressing "X" button on Qt window? Aren't main window supposed to call closeEvent on all it's children widgets and then destroy them properly?</em></p>

<p>No, one thing is the closing of a widget and another thing is the destruction of the widget, it can be destroyed without closing and closing the window does not involve destroying the object.</p>

<p>As already pointed out closing a window does not imply deleting it, there may be other windows open, but if the last QApplication window is closed by default the eventloop that implies the destruction of the widget will be terminated which does not necessarily imply calling the close method.</p>

<p>To be understood, let's use the following code:</p>

<pre class="lang-py prettyprint-override"><code>from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("closeEvent Button")
        super(Button, self).closeEvent(event)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button_quit = Button(
            text="quit",
            clicked=QtCore.QCoreApplication.quit
        )
        button_close = Button(
            text="close",
            clicked=self.close
        )

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button_quit)
        lay.addWidget(button_close)

    def closeEvent(self, event):
        print("closeEvent Widget")
        super(Widget, self).closeEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
</code>```

There are 2 buttons, in the case of the first button that calls QCoreApplication::quit() that will end the eventloop so all the widgets will be destroyed, and in that case no closeEvent will be called, in the case of the second button it will be call near the window so it will call its closeEvent but not the closeEvents of its children.

my actual problem is that I have saveUI() func in closeEvent, and it's not being called upon widgets hierarchical destruction on window close

If you want the closeEvent method to be called hierarchically then you must call the close method manually since Qt does not design it that way. In the next part there is an example:

from PyQt5 import QtCore, QtGui, QtWidgets

class PushButton(QtWidgets.QPushButton):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent PushButton")
        super(PushButton, self).closeEvent(event)

class LineEdit(QtWidgets.QLineEdit):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent LineEdit")
        super(LineEdit, self).closeEvent(event)

class ComboBox(QtWidgets.QComboBox):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent ComboBox")
        super(ComboBox, self).closeEvent(event)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button_close = PushButton(text="close", clicked=self.close)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button_close)
        lay.addWidget(LineEdit())
        lay.addWidget(ComboBox())

    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent Widget")
        super(Widget, self).closeEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
```

Body:
Either I don't understand completely how Qt's event propagation works or something, but I cannot understand why exactly closeEvent is not being called both for QPushButton-derived class and for QWidget-derived one itself.

Shouldn't wid.closeEvent() trigger closeEvents of all children widgets?

#!/bin/env python
# -*- coding: utf-8 -*-
import sys, os
from Qt.QtCore import *
from Qt.QtWidgets import *
from Qt.QtGui import *

class butt(QPushButton):
    def __init__(self, parent, name='Button'):
        super(self.__class__, self).__init__(parent)
        self.name = name

    def closeEvent(self, e):
        print('butt closeevent')
        e.accept()

class wid(QWidget):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        self.initUI()

    def initUI(self):
        #self.setAttribute(Qt.WA_DeleteOnClose)
        self.vl = QVBoxLayout(self)
        self.button = butt(self)
        self.button.setText('test1')
        self.vl.addWidget(self.button)
        self.button.clicked.connect(QCoreApplication.quit)

    def closeEvent(self, e):
        print('wid closeevent')
        e.accept()

def show():
    app = QApplication(sys.argv)
    win = QMainWindow()
    widget = wid(win)
    win.setCentralWidget(widget)
    win.show()
    app.exec_()

if __name__ == "__main__":
    show()

I'm expecting to see 2 lines
    wid closeevent
    butt closeevent
as an output, but I see nothing. Why closeEvent it not being called for them?

Body:
In the following examples when you press the button visually you will observe the same behavior: the window will close, but we see the difference, in the first one it is called closeEvent(), and in the second one it is not.

Example1:

#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    button = Button(text="Press me")
    button.clicked.connect(button.close)
    button.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Example2:

#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    button = Button(text="Press me")
    button.clicked.connect(QtCore.QCoreApplication.quit)
    button.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Why do not you call closeEvent when you call QCoreApplication::quit?
Because this method is used to exit the event loop of Qt, and if there is no event loop the events(QCloseEvent) do not work.

When a widget is closed, the children widget is not closed, that is, only if a widget is closed, only its own closeEvent will be called. So if you want the closeevent of the widget to be called, call your method close.

#!/bin/env python
# -*- coding: utf-8 -*-

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def __init__(self, name="Button", parent=None):
        super(Button, self).__init__(parent)
        self.m_name = name

    def closeEvent(self, event):
        print("button closeEvent")
        event.accept()

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        vl = QtWidgets.QVBoxLayout(self)
        button = Button()
        button.setText("test1")
        vl.addWidget(button)
        button.clicked.connect(self.close)

    def closeEvent(self, event):
        print("Widget closeevent")
        event.accept()

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QMainWindow()
    widget = Widget()
    w.setCentralWidget(widget)
    w.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

In the previous example depending on how you interact with the widget you will get the following behavior:

If you press the button the widget will close so it will be called closeEvent, and will not call the closeEvent of the button because even your child is not closing it.

If you press the "X" button in the window it will not be called the closeEvent of the widget but the QMainWindow, the explanation is the same as the previous one.

Conclusions:

Each type of event has its own workflow, some events are only received by the widget and not by the children, while others send the information to the children.

The close method uses the event loop to notify that the widget is to be closed, but QCoreApplication::quit() terminates the event loop.

Update:

why wid.closeEvent is not called when user pressing "X" button on Qt window? Aren't main window supposed to call closeEvent on all it's children widgets and then destroy them properly?

No, one thing is the closing of a widget and another thing is the destruction of the widget, it can be destroyed without closing and closing the window does not involve destroying the object.

As already pointed out closing a window does not imply deleting it, there may be other windows open, but if the last QApplication window is closed by default the eventloop that implies the destruction of the widget will be terminated which does not necessarily imply calling the close method.

To be understood, let's use the following code:

from Qt import QtCore, QtGui, QtWidgets

class Button(QtWidgets.QPushButton):
    def closeEvent(self, event):
        print("closeEvent Button")
        super(Button, self).closeEvent(event)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button_quit = Button(
            text="quit",
            clicked=QtCore.QCoreApplication.quit
        )
        button_close = Button(
            text="close",
            clicked=self.close
        )

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button_quit)
        lay.addWidget(button_close)

    def closeEvent(self, event):
        print("closeEvent Widget")
        super(Widget, self).closeEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

There are 2 buttons, in the case of the first button that calls QCoreApplication::quit() that will end the eventloop so all the widgets will be destroyed, and in that case no closeEvent will be called, in the case of the second button it will be call near the window so it will call its closeEvent but not the closeEvents of its children.

my actual problem is that I have saveUI() func in closeEvent, and it's not being called upon widgets hierarchical destruction on window close

If you want the closeEvent method to be called hierarchically then you must call the close method manually since Qt does not design it that way. In the next part there is an example:

from PyQt5 import QtCore, QtGui, QtWidgets

class PushButton(QtWidgets.QPushButton):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent PushButton")
        super(PushButton, self).closeEvent(event)

class LineEdit(QtWidgets.QLineEdit):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent LineEdit")
        super(LineEdit, self).closeEvent(event)

class ComboBox(QtWidgets.QComboBox):
    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent ComboBox")
        super(ComboBox, self).closeEvent(event)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button_close = PushButton(text="close", clicked=self.close)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button_close)
        lay.addWidget(LineEdit())
        lay.addWidget(ComboBox())

    def closeEvent(self, event):
        for children in self.findChildren(
            QtWidgets.QWidget, options=QtCore.Qt.FindDirectChildrenOnly
        ):
            children.close()
        print("closeEvent Widget")
        super(Widget, self).closeEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
How can I use location from Response Headers in the next request?
I'm perfoming some test using Karate test.

1st a Post that is expecting a 201 and a location.

2nd use the location from response to perfom a get.

Does anyone know how can I do this with Karate?

The following code is my try, after many other.

```<code>Given path 'alpha/test'
And request
"""
 {
   "id": '#(uuid)',
    "content": "test",
    "isActive": true
 }
"""
When method post
Then status 201
And def endpointLocation = responseHeaders['Location']
And print endpointLocation

Given url 'endpointLocation'
When method get
Then status 200
And match response ==
"""
 {
   "id": '#(uuid)'
 }
"""
</code>```

But i'm getting:

```<code>18:30:12.819 [main] ERROR com.intuit.karate - org.apache.http.client.ClientProtocolException, http call failed after 252 milliseconds for URL: endpointLocation
18:30:12.820 [main] ERROR com.intuit.karate - http request failed:
org.apache.http.client.ClientProtocolException
testApi.feature:263 -
org.apache.http.client.ClientProtocolException
</code>```

I'm not figuring it out why.

[EDIT]

After sugestion from Peter, that I Thanks!

The print return:

08:59:33.610 [main] INFO com.intuit.karate - [print] [
  "https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]

Now I'm calling

Given url endpointLocation

and I'm getting

08:59:33.611 [main] ERROR com.intuit.karate - http request failed: java.net.URISyntaxException: Illegal character in scheme name at index 0: ["https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]
fraudMgmtApi.feature:263 - java.net.URISyntaxException: Illegal character in scheme name at index 0: ["https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]

I was trying also to trim the first and last caracters, creating a:

def trim =
"""
function(myText) { result = myText.substring(1, myText.length-1) }
"""

Or myText.slice(1,-1)

答:
From the error message: http call failed after 252 milliseconds for URL: endpointLocation

It is clear you are setting the url wrong. First try hard-coding it, then make this change, if the endpointLocation variable is set correctly. You can print it to check.

```<code>Given url endpointLocation
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm perfoming some test using Karate test.

1st a Post that is expecting a 201 and a location.

2nd use the location from response to perfom a get.

Does anyone know how can I do this with Karate?

The following code is my try, after many other.

Given path 'alpha/test'
And request
"""
 {
   "id": '#(uuid)',
    "content": "test",
    "isActive": true
 }
"""
When method post
Then status 201
And def endpointLocation = responseHeaders['Location']
And print endpointLocation

Given url 'endpointLocation'
When method get
Then status 200
And match response ==
"""
 {
   "id": '#(uuid)'
 }
"""

But i'm getting:

18:30:12.819 [main] ERROR com.intuit.karate - org.apache.http.client.ClientProtocolException, http call failed after 252 milliseconds for URL: endpointLocation
18:30:12.820 [main] ERROR com.intuit.karate - http request failed:
org.apache.http.client.ClientProtocolException
testApi.feature:263 -
org.apache.http.client.ClientProtocolException

I'm not figuring it out why.

[EDIT]

After sugestion from Peter, that I Thanks!

The print return:

08:59:33.610 [main] INFO com.intuit.karate - [print] [
  "https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]

Now I'm calling

Given url endpointLocation

and I'm getting

08:59:33.611 [main] ERROR com.intuit.karate - http request failed: java.net.URISyntaxException: Illegal character in scheme name at index 0: ["https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]
fraudMgmtApi.feature:263 - java.net.URISyntaxException: Illegal character in scheme name at index 0: ["https://www.test.com/enpoint/4603b043-ea8c-470d-a5a9-2aa50aea4f75"]

I was trying also to trim the first and last caracters, creating a:

def trim =
"""
function(myText) { result = myText.substring(1, myText.length-1) }
"""

Or myText.slice(1,-1)

Body:
From the error message: http call failed after 252 milliseconds for URL: endpointLocation

It is clear you are setting the url wrong. First try hard-coding it, then make this change, if the endpointLocation variable is set correctly. You can print it to check.

Given url endpointLocation


问:
Limiting the lenght of response with python requests
I'm setting up a Views that save data from an API into my database on a button click and I'm having a hard time trying to figure out how to limit the size of the requests response for product descriptions in the following way:

If the lenght of a description is higher than 2000, delete some of the letters at the end of it until it reaches the limit of 2000, but don't remove it completely from the request.

As of now, what I've been able to achieve is to completely remove the product infos if the lenght is higher than 2000 as you can see below.

My django views function:

```<code>def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product
                Product.objects.get_or_create(
                    title=item['name'],
                    destination=item['city']['name'],
                    description=resp_2_data['contentListHtml'][0]['html'],
                    link=item['canonicalUrl'],
                    image=item['image']['url']
                )

    return render(request, "form.html")
</code>```

But I remove way to much rows by doing this so I would like to know how can I fix this?

Please help.

答:
Instead of using a conditional statement, you can use the slice operator to specify the character limit for the description. Using this approach you can refactor the relevant part of your code:

resp_2_data = resp_2.json()
Product.objects.get_or_create(title=item['name'],
                              destination=item['city']['name'],
                              description=resp_2_data['contentListHtml'][0]['html'][0:2000],
                              ....
                              )
```

Body:
I'm setting up a Views that save data from an API into my database on a button click and I'm having a hard time trying to figure out how to limit the size of the requests response for product descriptions in the following way:

If the lenght of a description is higher than 2000, delete some of the letters at the end of it until it reaches the limit of 2000, but don't remove it completely from the request.

As of now, what I've been able to achieve is to completely remove the product infos if the lenght is higher than 2000 as you can see below.

My django views function:

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_TEST_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"

        for item in resp_1_data['items']:
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_TEST_API_KEY
                })
            resp_2_data = resp_2.json()

            if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product
                Product.objects.get_or_create(
                    title=item['name'],
                    destination=item['city']['name'],
                    description=resp_2_data['contentListHtml'][0]['html'],
                    link=item['canonicalUrl'],
                    image=item['image']['url']
                )

    return render(request, "form.html")

But I remove way to much rows by doing this so I would like to know how can I fix this?

Please help.


问:
Cannot access property from object returned by Promise
I have the following object:

```<code>const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };
</code>```

When I do api.post().then((res) => console.log(res.data))
I get undefined even though console.log(res) prints the entire object.

答:
Try this:</p>

```<code>const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

api.post().then((res) => console.log(res.response.data))
</code>```

Body:
I have the following object:

const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

When I do api.post().then((res) => console.log(res.data))
I get undefined even though console.log(res) prints the entire object.

Body:
Try this:

const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

api.post().then((res) => console.log(res.response.data))


问:
Android Development: How To Get All EditText Children of a ViewGroup?
Basically, I have a LinearLayout that holds a random amount of horizontal LinearLayouts, and in each of the horizontal LinearLayouts there's a TextView and an EditText. I want to be able to get the value of each EditText children of the master LinearLayout.

Sorry if it's confusing, I'm no good at explaining things!

Could I just set the same ID for each of the EditTexts then use findViewById, or would that only return the first instance of an EditText?

Thanks,
Alex.

答: findViewById returns only the first view with the given id. You're going to have to traverse the view hierarchy yourself, at least until you get down to each horizontal linear layout. You'll find the methods ViewGroup.getChildCount() and ViewGroup.getChildAt(int) useful for this.

ContentLicense: CC BY-SA 3.0


问:
PHP Warning: Module 'soap' already loaded in Unknown on line 0
Hi, I have a problem with this error: PHP Warning:  Module 'soap' already loaded in Unknown on line 0

I am running vps on media temple.  I got some instructions from their knowledge base and I followed them exactly as described.  However to see if SOAP properly installed i went to the command line and ran "pear list" and this is what I get.

```<code>PHP Warning:  Module 'soap' already loaded in Unknown on line 0
Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.3.11  stable
Console_Getopt   1.3.1   stable
PEAR             1.9.4   stable
Structures_Graph 1.0.4   stable
XML_Util         1.2.1   stable
[root@w8ld-gg7p ~]# rep extension /usr/local/lib/php.ini
-bash: rep: command not found
[root@w8ld-gg7p ~]#
</code>```

Can anyone tell me what I'm doing wrong? First off it doesn't load SOAP in the installed packages list.  Second I get that SOAP loaded in unkown error.

I'm a newbie so any help would be greatly appreciated!  Thank you!

答:
Comment the extension=soap in one of the files:

e.g = in your Xampp (php.ini)

```<code>;extension=soap
</code>```

Body:
Hi, I have a problem with this error: PHP Warning:  Module 'soap' already loaded in Unknown on line 0

I am running vps on media temple.  I got some instructions from their knowledge base and I followed them exactly as described.  However to see if SOAP properly installed i went to the command line and ran "pear list" and this is what I get.

PHP Warning:  Module 'soap' already loaded in Unknown on line 0
Installed packages, channel pear.php.net:
=========================================
Package          Version State
Archive_Tar      1.3.11  stable
Console_Getopt   1.3.1   stable
PEAR             1.9.4   stable
Structures_Graph 1.0.4   stable
XML_Util         1.2.1   stable
[root@w8ld-gg7p ~]# rep extension /usr/local/lib/php.ini
-bash: rep: command not found
[root@w8ld-gg7p ~]#

Can anyone tell me what I'm doing wrong? First off it doesn't load SOAP in the installed packages list.  Second I get that SOAP loaded in unkown error.

I'm a newbie so any help would be greatly appreciated!  Thank you!

Body:
Comment the extension=soap in one of the files:

e.g = in your Xampp (php.ini)

;extension=soap


问:
error: At least one of apiVersion, kind and name was changed
Why am I getting an error when I try to change the apiVersion of a deployment via kubectl edit deployment example ?

Do I have to delete and recreate the object?

答: You're getting this because there are only certain attributes of a resource that you may change once it's created. ApiVersion, Kind, and Name are some of the prime identifiers of a resource so they can't be changed without deleting/recreating them.</p>


问:
Understanding Typescript definition
From the @types/d3 definition, we have the lines:

```<code>export type ValueFn<T extends BaseType, Datum, Result> = (this: T, datum: Datum, index: number, groups: T[] | ArrayLike<T>) => Result;

attrTween(name: string): ValueFn<GElement, Datum, (t: number) => string> | undefined;
</code>```

When I use the function attrTween, I use it like so :

```<code>caller.attrTween("points", (d, index, groups) => { return (t) => {return "";};  }
</code>```

In which caller is Transition<BaseType, PieArcDatum<number>

These parameters are inferred by VSCode as :

```<code>(parameter) d: d3.PieArcDatum<number>
(parameter) index: number
(parameter) groups: d3.BaseType[] | d3.ArrayLike<d3.BaseType>
</code>```

How does type definition enforce this behaviour?
Can It be explained word-by-word, especially the Generic usage?

答:
attrTween has three separate overloads, where the third entry (and only two-argument overload with a non-null second argument) is:

```<code>/**
 * Assign the attribute tween for the attribute with the specified name to the specified interpolator factory.
 * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element.
 * The returned interpolator will then be invoked for each frame of the transition, in order,
 * being passed the eased time t, typically in the range [0, 1]. Lastly, the return value of the interpolator will be used to set the attribute value.
 * The interpolator must return a string.
 *
 * @param name Name of attribute.
 * @param factory An interpolator factory which is evaluated for each selected element, in order, being passed the current datum (d),
 * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The interpolator factory returns a string interpolator,
 * which takes as its argument eased time t, typically in the range [0, 1] and returns the interpolated string.
 */
attrTween(name: string, factory: ValueFn<GElement, Datum, (t: number) => string>): this;
</code>```

This matches your call much better than the overload you listed. This definition exists in Transition, which is defined as the following:

```<code>export interface Transition<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>
</code>```

With this, we can see the direct mapping:

d is Datum, which from caller is d3.PieArcDatum<number>

index is number

groups is T[] | ArrayLike<T> where T extends BaseType.

Per attrTween's definition, T in ValueFn is the same as GElement in Transition.

GElement is BaseType per your callee.

Therefore T is BaseType, so groups is d3.BaseType[] | d3.ArrayLike<d3.BaseType> as you see it.

Title: Understanding Typescript definition

Body:
From the @types/d3 definition, we have the lines:

export type ValueFn<T extends BaseType, Datum, Result> = (this: T, datum: Datum, index: number, groups: T[] | ArrayLike<T>) => Result;

attrTween(name: string): ValueFn<GElement, Datum, (t: number) => string> | undefined;

When I use the function attrTween, I use it like so :

caller.attrTween("points", (d, index, groups) => { return (t) => {return "";};  }

In which caller is Transition<BaseType, PieArcDatum<number>

These parameters are inferred by VSCode as :

(parameter) d: d3.PieArcDatum<number>
(parameter) index: number
(parameter) groups: d3.BaseType[] | d3.ArrayLike<d3.BaseType>

How does type definition enforce this behaviour?
Can It be explained word-by-word, especially the Generic usage?

Body:
attrTween has three separate overloads, where the third entry (and only two-argument overload with a non-null second argument) is:

/**
 * Assign the attribute tween for the attribute with the specified name to the specified interpolator factory.
 * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element.
 * The returned interpolator will then be invoked for each frame of the transition, in order,
 * being passed the eased time t, typically in the range [0, 1]. Lastly, the return value of the interpolator will be used to set the attribute value.
 * The interpolator must return a string.
 *
 * @param name Name of attribute.
 * @param factory An interpolator factory which is evaluated for each selected element, in order, being passed the current datum (d),
 * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The interpolator factory returns a string interpolator,
 * which takes as its argument eased time t, typically in the range [0, 1] and returns the interpolated string.
 */
attrTween(name: string, factory: ValueFn<GElement, Datum, (t: number) => string>): this;

This matches your call much better than the overload you listed. This definition exists in Transition, which is defined as the following:

export interface Transition<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>

With this, we can see the direct mapping:

d is Datum, which from caller is d3.PieArcDatum<number>

index is number

groups is T[] | ArrayLike<T> where T extends BaseType.

Per attrTween's definition, T in ValueFn is the same as GElement in Transition.

GElement is BaseType per your callee.

Therefore T is BaseType, so groups is d3.BaseType[] | d3.ArrayLike<d3.BaseType> as you see it.


问:
web site configuration
One web site is required to be accessed by me (developer) and one user (DOMAIN_NAME\USER_NAME).

When I developed web site in visual studio using "automatic host" created by VS, the following settings in web.config were enough:

```<code><authentication mode="Windows"/>
<authorization>
  <allow users="DOMAIN_NAME\my_name,DOMAIN_NAME\USER_NAME" />
  <deny users="*" />
</authorization>
</code>```

But when I created web site in IIS I'm receiving error:

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.

Error message 401.2.: Unauthorized: Logon failed due to server configuration.  Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server.  Contact the Web server's administrator for additional assistance.

What  setting for ApplicationPoolIdentity and web site itself are required to be specified?

Thanks a lot!

EDIT:

I've configured Application Pool of local IIS to use 'LocalSystem' identity, web site - to use "pass-through" authentication, and as suggested disabled "Anonymous Authentication", enabled "Windows Authentication" - and web site locally became workable.

But locally I have windows 7 (IIS7), but on "TEST" environment (where I need to deploy web site) I have windows 2008 server and it doesn't have option to enable "Windows Authentication"... don't know why... probably that is for higher level of administrator, but I'm a member of Administrators group...

Guess, I'm doing something wrong...

Please advise.

答:
Maybe it can be useful: I started to receive 401.2. error in .ASPX application (no changes in the app made), in protected path amd Forms auth.:

```<code><authentication mode="Forms">
...
</authentication>
...
<location path="Admin">
    <system.web>
        <authorization>
            <allow roles="Admin,Client" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>
</code>```

AFTER launching of other MVC applications on same computer/IIS. It seems MVC changed something in server's config (routes, I believe). Any playing with Authentication in IIS (computer/server/site) did not help. But Next helped: I have changed  Application pool from .Net 4.5 to .Net 4.5 Classic for the web application. The difference in pool Managed pipeline mode, Integrated/Classic.

Title: web site configuration

Body:
One web site is required to be accessed by me (developer) and one user (DOMAIN_NAME\USER_NAME).

When I developed web site in visual studio using "automatic host" created by VS, the following settings in web.config were enough:

<authentication mode="Windows"/>
<authorization>
  <allow users="DOMAIN_NAME\my_name,DOMAIN_NAME\USER_NAME" />
  <deny users="*" />
</authorization>

But when I created web site in IIS I'm receiving error:

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.

Error message 401.2.: Unauthorized: Logon failed due to server configuration.  Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server.  Contact the Web server's administrator for additional assistance.

What  setting for ApplicationPoolIdentity and web site itself are required to be specified?

Thanks a lot!

EDIT:

I've configured Application Pool of local IIS to use 'LocalSystem' identity, web site - to use "pass-through" authentication, and as suggested disabled "Anonymous Authentication", enabled "Windows Authentication" - and web site locally became workable.

But locally I have windows 7 (IIS7), but on "TEST" environment (where I need to deploy web site) I have windows 2008 server and it doesn't have option to enable "Windows Authentication"... don't know why... probably that is for higher level of administrator, but I'm a member of Administrators group...

Guess, I'm doing something wrong...

Please advise.

Body:
Maybe it can be useful: I started to receive 401.2. error in .ASPX application (no changes in the app made), in protected path amd Forms auth.:

<authentication mode="Forms">
...
</authentication>
...
<location path="Admin">
    <system.web>
        <authorization>
            <allow roles="Admin,Client" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>

AFTER launching of other MVC applications on same computer/IIS. It seems MVC changed something in server's config (routes, I believe). Any playing with Authentication in IIS (computer/server/site) did not help. But Next helped: I have changed  Application pool from .Net 4.5 to .Net 4.5 Classic for the web application. The difference in pool Managed pipeline mode, Integrated/Classic.


问:
Generate a new Ecore metamodel based on another one in Java
I am a beginner in Eclipse EMF.
I have created an Ecore metamodel which I want to transform into a new Ecore metamodel in Java that takes into account some characteristics of the first metamodel. I have searched the web but the exlpanations I've found were not clear to me.

How can I get access to the first metamodel from a Java app and how can I generate a new metamodel with the corresponding .ecore and .genmodel files?

Is such a task even possible?

Thanks!

答:
You can access in this way :</p>

```<code>ResourceSet rs = new ResourceSetImpl();
Resource resource = rs.getResource(URI.createFileURI(metamodelStringURI), true);
</code>```

Body:
You can access in this way :

ResourceSet rs = new ResourceSetImpl();
Resource resource = rs.getResource(URI.createFileURI(metamodelStringURI), true);


问:
Laravel 5.3 - Carbon Date - UTC offset get timezone name
I am trying to get a timezone name from a UTC offset in Laravel 5.3 using Carbon. Code listed below any help would be much appreciated.

```<code>/* current code iteration */
$utcOffset = -5;
$timezone = Carbon::now($utcOffset)->timezone->getName();
echo $timezone;
// Result: -05:00
// Expected Result: EST

/* tried code */
$timezone = Carbon::now($utcOffset)->tzName;
// Result: -05:00

/* What I used prior to Carbon */
$timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone));
$timezone = $dateTime->format('T');'
</code>```

What am I missing? I feel daft..

答:
In a new Carbon it is timezoneName property;

```<code>$now = Carbon::now(-5);
echo $now->timezoneName;
//or
echo $now->timezone->getName();
</code>```

Body:
I am trying to get a timezone name from a UTC offset in Laravel 5.3 using Carbon. Code listed below any help would be much appreciated.

/* current code iteration */
$utcOffset = -5;
$timezone = Carbon::now($utcOffset)->timezone->getName();
echo $timezone;
// Result: -05:00
// Expected Result: EST

/* tried code */
$timezone = Carbon::now($utcOffset)->tzName;
// Result: -05:00

/* What I used prior to Carbon */
$timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone));
$timezone = $dateTime->format('T');'

What am I missing? I feel daft..

Body:
In a new Carbon it is timezoneName property;

$now = Carbon::now(-5);
echo $now->timezoneName;
//or
echo $now->timezone->getName();


问:
How to use graph data type using by pl/python in AgensGraph?

I am using AgensGraph.

I know the PostgreSQL supports pl/python driver.

So I think the AgensGraph supports it, too.

If I want to use a graph data type using by pl/python, is the way same with general data?

答:
In order to use PL/Python in AgensGraph you need to Create the plpythonu language.

A good example for PL/Python in AgensGraph would be as following:

Enabling the module

```<code>CREATE LANGUAGE plpythonu;
</code>```

Creating sample data

```<code>CREATE (a:person {id:1,name:'Bob'});
</code>```

Creating PL/Python function

```<code>CREATE OR REPLACE FUNCTION firstname()
RETURNS void
AS $$
#Python source code starts
records = plpy.execute("MATCH (a:person) RETURN a.name AS sample")
plpy.info(records[0]['sample'])
#Python source code ends
$$ LANGUAGE plpythonu;
</code>```

Calling the function

```<code>SELECT firstname();
</code>```

You can find more information in the following link:
AgensGraph

Body:
In order to use PL/Python in AgensGraph you need to Create the plpythonu language.

A good example for PL/Python in AgensGraph would be as following:

Enabling the module

CREATE LANGUAGE plpythonu;

Creating sample data

CREATE (a:person {id:1,name:'Bob'});

Creating PL/Python function

CREATE OR REPLACE FUNCTION firstname()
RETURNS void
AS $$
#Python source code starts
records = plpy.execute("MATCH (a:person) RETURN a.name AS sample")
plpy.info(records[0]['sample'])
#Python source code ends
$$ LANGUAGE plpythonu;

Calling the function

SELECT firstname();

You can find more information in the following link:
AgensGraph


问:
Cannot create Dynamic Scenario Outline via Java call
Cannot create Dynamic Scenario Outline via Java call in Karate.

I can create a Dynamic Scenario Outline with "hard-coded" Json Array for example:

```<code>* def foobar = [{ 'type': 'app' }]
</code>```

But when I attempt to generate the same Json Array from a Java class, I always get the following Karate warning(s) and the Dynamic Scenario Outline never executes:

WARN  com.intuit.karate - ignoring dynamic expression, did not evaluate to list

-- OR --

WARN  com.intuit.karate - ignoring dynamic expression list item 0, not map-like

I've tried using the Karate key-words 'def', 'string', 'json' as the var type but no luck. I've even tried hard-coding the same string shown above in the Java method with no luck.

I declare/call my Java class in 'Background:' and print what is given back and it "looks" correct.

```<code>Background:
 * def IdaDataApiUtil = Java.type('data.IdaDataApiUtil')
 * def foobar = IdaDataApiUtil.getClientExample('ida-sp')
 * print foobar
</code>```

I then try to utilize the JsonArray in my 'Example:' like such:

```<code>Examples:
 | foobar |
</code>```

At this point I get the above mentioned error(s), depending on what I've tried to return (JsonArray, JsonObject, Map, List).

If I simply use the hard-coded 'def':

```<code>* def foobar = [{ 'type': 'app' }]
</code>```

It works as expected.

In my Java code I've tried various things:

Hard-coded Json string:

```<code>public static String getClientExample() {
    return "[{ 'type': 'app' }]";
}
</code>```

List:

```<code>public static List<String> getClientExample() {
    List<String> list = new ArrayList<>();
    list.add("'type': 'app'");
    return list
}
</code>```

Map:

```<code>public static Map<String, Object> getClientExample() {
    Map<String, Object> map = new HashMap<>();
    map.put("type", "app");
    return map;
}
</code>```

I've played with variations of key/values in both list/map with no luck. I've also tried with JSONObject/JSONArray but no luck there as well.

I feel like I'm missing something vary obvious but I can't see the forest through the trees at the moment...

答:
I attempt to generate the same Json Array from a Java class,

What you return from the Java code should be a List<Map<String, Object>> and it should work fine. You have tried List<String> and that is the problem.

Read this section of the docs: https://github.com/intuit/karate#type-conversion

Another tip, you can try a "cast" to ensure it is in the JSON array form you need, so if you are too lazy to form properly nested Map-s, just return a raw JSON string from Java, and the below line will convert it correctly.

```<code>* json foobar = foobar
</code>```

Body:
Cannot create Dynamic Scenario Outline via Java call in Karate.

I can create a Dynamic Scenario Outline with "hard-coded" Json Array for example:

* def foobar = [{ 'type': 'app' }]

But when I attempt to generate the same Json Array from a Java class, I always get the following Karate warning(s) and the Dynamic Scenario Outline never executes:

WARN  com.intuit.karate - ignoring dynamic expression, did not evaluate to list

-- OR --

WARN  com.intuit.karate - ignoring dynamic expression list item 0, not map-like

I've tried using the Karate key-words 'def', 'string', 'json' as the var type but no luck. I've even tried hard-coding the same string shown above in the Java method with no luck.

I declare/call my Java class in 'Background:' and print what is given back and it "looks" correct.

Background:
 * def IdaDataApiUtil = Java.type('data.IdaDataApiUtil')
 * def foobar = IdaDataApiUtil.getClientExample('ida-sp')
 * print foobar

I then try to utilize the JsonArray in my 'Example:' like such:

Examples:
 | foobar |

At this point I get the above mentioned error(s), depending on what I've tried to return (JsonArray, JsonObject, Map, List).

If I simply use the hard-coded 'def':

* def foobar = [{ 'type': 'app' }]

It works as expected.

In my Java code I've tried various things:

Hard-coded Json string:

public static String getClientExample() {
    return "[{ 'type': 'app' }]";
}

List:

public static List<String> getClientExample() {
    List<String> list = new ArrayList<>();
    list.add("'type': 'app'");
    return list
}

Map:

public static Map<String, Object> getClientExample() {
    Map<String, Object> map = new HashMap<>();
    map.put("type", "app");
    return map;
}

I've played with variations of key/values in both list/map with no luck. I've also tried with JSONObject/JSONArray but no luck there as well.

I feel like I'm missing something vary obvious but I can't see the forest through the trees at the moment...

Body:
I attempt to generate the same Json Array from a Java class,

What you return from the Java code should be a List<Map<String, Object>> and it should work fine. You have tried List<String> and that is the problem.

Read this section of the docs: https://github.com/intuit/karate#type-conversion

Another tip, you can try a "cast" to ensure it is in the JSON array form you need, so if you are too lazy to form properly nested Map-s, just return a raw JSON string from Java, and the below line will convert it correctly.

* json foobar = foobar


问:
arcore, placing 3D model without the touch with unity

I'm making an AR application using ARCore and Unity.

I wanted to place 3D models on vertical walls without touch.

It is almost implemented, but when creating a 3D model, it Keeps going to the left down.

I think it's because I've set the anchor position

Vector3 position = new Vector3(0,0,0);
```

<p>But if I changed the anchor position to </p>

<pre class="lang-c# prettyprint-override"><code> Vector3 position = new Vector3 (hit.Pose.position.x, hit.Pose.position.y, hit.Pose.position.z)
</code>```

It doesn't go to the center too.

Does anyone know how to put a 3D object in the middle of the plane?

TrackableHit hit;
TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
TrackableHitFlags.FeaturePointWithSurfaceNormal;

if (Frame.Raycast(transform.position.x,transform.position.y, raycastFilter, out hit))
{
    if (CurrentNumberOfGameObjects < numberOfGameObjectsAllowed)
        {
            Destroy(ARObject);

        if ((hit.Trackable is DetectedPlane)
             && Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position, hit.Pose.rotation * Vector3.up) < 0)
        {
            Debug.Log("Hit at back of the current DetectedPlane");
        }
        else
        {
            Vector3 position = new Vector3(0,0,0);
            Quaternion rotation = new Quaternion(0f, 0f, 0f, 1f);

            ARObject = Instantiate(ARAndroidPrefab, hit.Pose.position, hit.Pose.rotation);
            ARObject.transform.Rotate(-90, 0, 0, Space.Self);
            var anchor = Session.CreateAnchor(new Pose(position, rotation));
            ARObject.transform.parent = anchor.transform;
                CurrentNumberOfGameObjects = CurrentNumberOfGameObjects + 1;

                // Hide Plane once ARObject is Instantiated
                foreach (GameObject Temp in DetectedPlaneGenerator.instance.PLANES) //RK
                {
                    Temp.SetActive(false);
                }
            }
        }
    }
```

答:
i changed code

```<code>Vector3 position = Vector3.zero; // Vector3 position = new Vector3(0,0,0);

</code>```

to

```<code>Vector3 position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y , hit.Pose.position.z);
</code>```

and then it works.

Body:
I'm making an AR application using ARCore and Unity.

I wanted to place 3D models on vertical walls without touch.

It is almost implemented, but when creating a 3D model, it Keeps going to the left down.

I think it's because I've set the anchor position

Vector3 position = new Vector3(0,0,0);

But if I changed the anchor position to

 Vector3 position = new Vector3 (hit.Pose.position.x, hit.Pose.position.y, hit.Pose.position.z)

It doesn't go to the center too.

Does anyone know how to put a 3D object in the middle of the plane?

TrackableHit hit;
TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
TrackableHitFlags.FeaturePointWithSurfaceNormal;

if (Frame.Raycast(transform.position.x,transform.position.y, raycastFilter, out hit))
{
    if (CurrentNumberOfGameObjects < numberOfGameObjectsAllowed)
        {
            Destroy(ARObject);

        if ((hit.Trackable is DetectedPlane)
             && Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position, hit.Pose.rotation * Vector3.up) < 0)
        {
            Debug.Log("Hit at back of the current DetectedPlane");
        }
        else
        {
            Vector3 position = new Vector3(0,0,0);
            Quaternion rotation = new Quaternion(0f, 0f, 0f, 1f);

            ARObject = Instantiate(ARAndroidPrefab, hit.Pose.position, hit.Pose.rotation);
            ARObject.transform.Rotate(-90, 0, 0, Space.Self);
            var anchor = Session.CreateAnchor(new Pose(position, rotation));
            ARObject.transform.parent = anchor.transform;
                CurrentNumberOfGameObjects = CurrentNumberOfGameObjects + 1;

                // Hide Plane once ARObject is Instantiated
                foreach (GameObject Temp in DetectedPlaneGenerator.instance.PLANES) //RK
                {
                    Temp.SetActive(false);
                }
            }
        }
    }

Body:
i changed code

Vector3 position = Vector3.zero; // Vector3 position = new Vector3(0,0,0);

to

Vector3 position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y , hit.Pose.position.z);

and then it works.


问:
Reordering Month and Year in formatted Fiscal Period column
I am trying to reorder a fiscal period column from alphabetical order to chronological order. That is, I have this column, which displays values as month-year (showing all distinct values in Query Editor):
 Period_Name Column

I would like to order this column chronologically, like this: JAN-18, FEB-18, MAR-18, APR-18, etc. in order to use it to plot a time series.

Right now if I try to change the column's data type in Query Editor to Date, it thinks that year is actually the day, and then assumes the year to be the current year (namely 2019); that is, APR-18 becomes April 18, 2019 instead of what it should be, April 2018, with no day (this is a fiscal period column). The custom date and time formats with the FORMAT function (https://learn.microsoft.com/en-us/dax/custom-date-and-time-formats-for-the-format-function) do not appear to recognize the current format that this column is in as month-year, and just spit out the same values back when I try to use it in a new calculated column.

Any help would be much appreciated!

答:
Being that your field is TEXT it will be sorted alphabetically. You can create a 'Sort By Column' to sort your data by doing something like this: </p>

```<code>Sort by Column :=
VAR YearNumber =
    RIGHT ( 'Table'[Column], 2 ) + 2000
VAR CurrentMonthName =
    LEFT ( 'Table'[Column], 3 )
RETURN YearNumber &
    SWITCH (
    CurrentMonthName,
    "JAN", "01",
    "FEB", "02",
    "MAR", "03",
    "APR", "04",
    "MAY", "05",
    "JUN", "06",
    "JUL", "07",
    "AUG", "08",
    "SEP", "09",
    "OCT", "10",
    "NOV", "11",
    "DEC", "12"
)
</code>```

<p>This will give you an index from which to sort your data by. Create this as a calculated column convert type from text to whole number and then sort your original column by this new column and you should be golden. </p>

Body:
Being that your field is TEXT it will be sorted alphabetically. You can create a 'Sort By Column' to sort your data by doing something like this:

Sort by Column :=
VAR YearNumber =
    RIGHT ( 'Table'[Column], 2 ) + 2000
VAR CurrentMonthName =
    LEFT ( 'Table'[Column], 3 )
RETURN YearNumber &
    SWITCH (
    CurrentMonthName,
    "JAN", "01",
    "FEB", "02",
    "MAR", "03",
    "APR", "04",
    "MAY", "05",
    "JUN", "06",
    "JUL", "07",
    "AUG", "08",
    "SEP", "09",
    "OCT", "10",
    "NOV", "11",
    "DEC", "12"
)

This will give you an index from which to sort your data by. Create this as a calculated column convert type from text to whole number and then sort your original column by this new column and you should be golden.


问:
is there any reason for writing a web crawler framework for Objective-C when there is framework for C language?
i wanted to write a web crawler library for Objective-C ! but there is a library available for C language !

since we can compile C codes in our Objective-C projects in Xcode ! is there any reasonable purpose that we write a new library for Objective-C with itself syntax?

any performance ? or any reason ?

thanks

答:
Sure;  lots of reasons.

The primary reason is if you want to hook the web crawler into an Objective-C application.  For example, you might want to crawl the web and store results in Core Data for later local retrieval.   Writing an Objective-C API makes it that much easier.

Wrapping a C based API in Objective-C is very easy, too.  It is quite common to wrap C API in Objecitve-C to make the C based API that much easier to work with.  OO patterns naturally encapsulate the notion of "session" or "context" that are typically represented by awkwardly managed manual malloc()d structures in C;   those structures typically fit naturally into an Objective-C class.


问:
How to detect use of query parameters not referenced in the corresponding DTO?
Is there any way to detect when a request contains a query parameter that is not referenced in its corresponding DTO?

For example, if I have the following query DTO:

export class GetCustomersQueryDTO {
    readonly firstName: string;
    readonly lastName: string;
}

```

How do I know it when the request contains a query parameter other than firstName or  lastName? For example: /customers?name=jon

答:
In the way I understand your question, I would say that you can achieve this using the ValidationPipe from NestJS itself.

You might need to tweak it a bit to suit your needs properly though, depending on whether you just need to reject those requests with unknown DTO attributes (in this case, then you can use the ValidationPipe options), or if you need to do further processing (in which case you would maybe use interceptor feature from NestJS).

See this page which might help you:
https://docs.nestjs.com/pipes#class-validator

Based on the above documentation link & Nest built-in ValidationPipe, your first comment to my answer, and the class-validator options docs, the use of the ValidationPipe for your use case would look something like this:

@Post()
@UsePipes(new ValidationPipe({ forbidUnknownValues: true }))
async search(@Body() getCustomersQueryDto: GetCustomersQueryDTO) {
  this.usersService.search(getCustomersQueryDto);
}
```

N.B. 1: This will throw an error when a request contains attributes that are not defined within the CreateCatDto class. See the validation options for more tweaking.

N.B. 2: You could use the above pipe at the controller level (in the above sample code it's at the route/method level only within the controller)

Let me know if it helps :)

Body:
Is there any way to detect when a request contains a query parameter that is not referenced in its corresponding DTO?

For example, if I have the following query DTO:

export class GetCustomersQueryDTO {
    readonly firstName: string;
    readonly lastName: string;
}

How do I know it when the request contains a query parameter other than firstName or  lastName? For example: /customers?name=jon

Body:
In the way I understand your question, I would say that you can achieve this using the ValidationPipe from NestJS itself.

You might need to tweak it a bit to suit your needs properly though, depending on whether you just need to reject those requests with unknown DTO attributes (in this case, then you can use the ValidationPipe options), or if you need to do further processing (in which case you would maybe use interceptor feature from NestJS).

See this page which might help you:
https://docs.nestjs.com/pipes#class-validator

Based on the above documentation link & Nest built-in ValidationPipe, your first comment to my answer, and the class-validator options docs, the use of the ValidationPipe for your use case would look something like this:

@Post()
@UsePipes(new ValidationPipe({ forbidUnknownValues: true }))
async search(@Body() getCustomersQueryDto: GetCustomersQueryDTO) {
  this.usersService.search(getCustomersQueryDto);
}

N.B. 1: This will throw an error when a request contains attributes that are not defined within the CreateCatDto class. See the validation options for more tweaking.

N.B. 2: You could use the above pipe at the controller level (in the above sample code it's at the route/method level only within the controller)

Let me know if it helps :)


问:
Python math operation on column
Data from json is in df and am trying to ouput to a csv.
I am trying to multiply dataframe column with a fixed value and having issues how data is displayed

I have used the following but the data is still not how i want to display

df_entry['Hours'] = df_entry['Hours'].multiply(2)
df_entry['Hours'] = df_entry['Hours'] * 2

```

<p>Input</p>

```ID, name,hrs
100,AB,37.5
```

<p>Expected</p>

```ID, name,hrs
100,AB,75.0
```

<p>What I am getting</p>

```ID, name,hrs
100,AB,37.537.5
```

答:
You can use apply function.</p>

```<code>df_entry['Hours'] = df_entry['Hours'].apply(lambda x: float(int(x))*2)
</code>```

Title: Python math operation on column

Body:
Data from json is in df and am trying to ouput to a csv.
I am trying to multiply dataframe column with a fixed value and having issues how data is displayed

I have used the following but the data is still not how i want to display

df_entry['Hours'] = df_entry['Hours'].multiply(2)
df_entry['Hours'] = df_entry['Hours'] * 2

Input

ID, name,hrs
100,AB,37.5

Expected

ID, name,hrs
100,AB,75.0

What I am getting

ID, name,hrs
100,AB,37.537.5

Body:
You can use apply function.

df_entry['Hours'] = df_entry['Hours'].apply(lambda x: float(int(x))*2)


问:
Dependency properties concept
I don't understand the Wpf dependency properties use.
Can anybody explain what is it and it’s use and how to use and learn simple the concept.</p>

答:
Dependency properties work much like ordinary properties, but you can set their values in XAML. For example, take the following dependency property declaration made in a class called MyCustomControl:

public bool EditMode
{
    get { return (bool)GetValue(EditModeProperty); }
    set { SetValue(EditModeProperty, value); }
}
public static readonly DependencyProperty EditModeProperty = DependencyProperty.Register("EditMode", typeof(bool), typeof(MyCustomControl), new PropertyMetadata(null));
```

<p>I can now set the EditMode property in the tag itself:</p>

<pre class="lang-xml prettyprint-override"><code><controls:MyCustomControl EditMode="True"/>
</code>```

Dependency properties also raise PropertyChanged events, so you can bind to them without having to implement INotifyPropertyChanged yourself.

Title: Dependency properties concept

Body:
Dependency properties work much like ordinary properties, but you can set their values in XAML. For example, take the following dependency property declaration made in a class called MyCustomControl:

public bool EditMode
{
    get { return (bool)GetValue(EditModeProperty); }
    set { SetValue(EditModeProperty, value); }
}
public static readonly DependencyProperty EditModeProperty = DependencyProperty.Register("EditMode", typeof(bool), typeof(MyCustomControl), new PropertyMetadata(null));

I can now set the EditMode property in the tag itself:

<controls:MyCustomControl EditMode="True"/>

Dependency properties also raise PropertyChanged events, so you can bind to them without having to implement INotifyPropertyChanged yourself.


答:
Should be res.response.data

```<code>api.post().then((res) => console.log(res.response.data)
</code>```

Or if you want to access it by res.data, update the object you returned from promise to

```<code>resolve({
  data: {
    token: "abcdefghijkl",
  }
});
</code>```

Title: Cannot access property from object returned by Promise

Body:
I have the following object:

const api = {
    post: () => {
        return new Promise((resolve, reject) => {
            resolve({
                response: {
                    data: {
                        token: "abcdefghijkl",
                    },
                 },
              });
        })
      }
   };

When I do api.post().then((res) => console.log(res.data))
I get undefined even though console.log(res) prints the entire object.

Body:
Should be res.response.data

api.post().then((res) => console.log(res.response.data)

Or if you want to access it by res.data, update the object you returned from promise to

resolve({
  data: {
    token: "abcdefghijkl",
  }
});


问:
Trouble Redirecting after successfull Auth0 login attempt
Using react-router and reacts context api i am attempting to authenticate a user in Auth0 and then redirect the user to a home page on successful login. What am i missing in my routing? I am passing the context to the rest of the app by wrapping the app using  and passing the login and logout methods down the tree. When I call the login() method from a child component the login method in the context gets called where i set state {isAuthenticated} to true and then i call the Auth.login() from within the context component as shown in the attached code.

I have searched Auth0 docs and have setup the correct callback route to http://localhost:3000/admin/dashboard

When i click login on the page the first time the appropriate Auth0 component shows up and i can login, however after i enter credentials and hit the login button i am redirected back to the {Login} component. If i then hit the login button in the {Login} component again after that i can see the page trying to redirect to my home route and then it kicks me back to the {Login} component.

```<code>import auth from '../Auth/Auth'

const AuthContext = React.createContext();
const Auth = new auth();

class AuthProvider extends React.Component {
  state = { isAuthenticated: false }
  constructor() {
    super()
    this.login = this.login.bind(this)
    this.logout = this.logout.bind(this)
  }

  auth0Signin() {
    Auth.login()
  }

  login() {
    this.setState({ isAuthenticated: true })
    this.auth0Signin()
  }

  logout() {
    Auth.logout()
    this.setState({ isAuthenticated: false })
  }

  render() {
    return (
      <AuthContext.Provider
        value={{
          isAuthenticated: this.state.isAuthenticated,
          login: this.login,
          logout: this.logout
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}
const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer };

import Auth from './Auth/Auth'
import Callback from './views/components/Callback'
import { createBrowserHistory } from "history";
import React from 'react';
import "react-notification-alert/dist/animate.css";
import { Redirect, Route, Router, Switch } from "react-router-dom";
import { AuthConsumer, AuthProvider } from './providers/AuthContext';
import Login from './views/pages/Login';
import Register from './views/pages/Register'
import Dashboard from './layouts/Admin/Admin'

const auth = new Auth()
const hist = createBrowserHistory();

const handleAuthentication = (nextState, replace) => {
  if (/access_token|id_token|error/.test(nextState.location.hash)) {
    auth.handleAuthentication();
  }
}

const ProtectedRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =>
          isAuthenticated ? <Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> : <Redirect to='/auth/login' />}
        {...rest}
      />
    )}
  </AuthConsumer>
)

const PublicRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =><Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> }
        {...rest}
      />
    )}
  </AuthConsumer>
)

const App = () => {
  return (
    <>
      <Router history={hist}>
        <AuthProvider>
          {/* <Header /> */}
            <Switch>
              <ProtectedRoute path='/admin/dashboard' component={Dashboard} />
              <PublicRoute path='/auth/Register' component={Register} />
              <PublicRoute path='/auth/Login' component={Login} />
              <Route path="/callback" render={(props) => {
                  handleAuthentication(props);
                  return <Callback {...props} />
                }}/>
              <PublicRoute path='/' component={Login} />
            </Switch>
          {/* <Footer /> */}
        </AuthProvider>
      </Router>
    </>
  );
}

export default App;

import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from './History';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    callbackUrl: AUTH_CONFIG.callbackUrl,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.redirectUri,
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        history.replace('/admin/dashboard');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  setSession(authResult) {
    // Set isLoggedIn flag in localStorage
    localStorage.setItem('isLoggedIn', 'true');

    // Set the time that the Access Token will expire at
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken;
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;

    // navigate to the home route
    history.replace('/home');
  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
       if (authResult && authResult.accessToken && authResult.idToken) {
         this.setSession(authResult);
       } else if (err) {
         this.logout();
         console.log(err);
         alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
       }
    });
  }

  logout() {
    // Remove tokens and expiry time
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;

    // Remove isLoggedIn flag from localStorage
    localStorage.removeItem('isLoggedIn');

    this.auth0.logout({
      returnTo: window.location.origin
    });

    // navigate to the home route
    history.replace('/auth/login');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }
}
</code>```

答:
The way I do it is with history.replace() in the Auth utility methods and then redirect to an authcheck component which upodates the global context state.

```<code>import auth0 from 'auth0-js'
import history from './history';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: 'webapp1.auth0.com',
    clientID: 'uZxUdMAsiDWeu3OrNpoi4JwJscdF5nAx',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid profile email'
  })

  userProfile = {}

  login = () => {
      this.auth0.authorize()
  }

  handleAuth = () => {
    this.auth0.parseHash((err, authResult) => {
      if(authResult) {
        localStorage.setItem('access_token', authResult.accessToken)
        localStorage.setItem('id_token', authResult.idToken)

        let expiresAt = JSON.stringify((authResult.expiresIn * 1000 + new Date().getTime()))
        localStorage.setItem('expiresAt', expiresAt)

        this.getProfile();
        setTimeout(() => { history.replace('/authcheck') }, 600);
      } else {
        console.log(err)
      }
    })
  }

  getAccessToken = () => {
    if(localStorage.getItem('access_token')) {
      const accessToken = localStorage.getItem('access_token')
      return accessToken
    } else {
      return null
    }
  }

  getProfile = () => {
    let accessToken = this.getAccessToken()
    if(accessToken) {
      this.auth0.client.userInfo(accessToken, (err, profile) => {
          if(profile) {
            this.userProfile = { profile }
          }
      } )
    }
  }

  logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('expiresAt')
    setTimeout(() => { history.replace('/authcheck') }, 200);
  }

  isAuthenticated = () => {
    let expiresAt = JSON.parse(localStorage.getItem('expiresAt'))
    return new Date().getTime() < expiresAt
  }

}

import React, { useEffect, useContext } from 'react';
import history from './history';
import Context from './context';
import * as ACTIONS from '../store/actions/actions';
import axios from 'axios';

const AuthCheck = () => {
  const context = useContext(Context)

  const send_profile_to_db = (profile) => {
   const data = profile
   axios.post('/api/posts/userprofiletodb', data )
    .then(axios.get('/api/get/userprofilefromdb', {params: {email: profile.profile.email}})
      .then(res => context.handleAddDBProfile(res.data)) )
    }

  useEffect(() => {
    if(context.authObj.isAuthenticated()) {
      context.handleUserLogin()
      context.handleUserAddProfile(context.authObj.userProfile)
      send_profile_to_db(context.authObj.userProfile)
      history.replace('/')
    }
    else {
      context.handleUserLogout()
      context.handleUserRemoveProfile()
      history.replace('/')
      }
    }, [])

    return(
        <div>
        </div>
    )}

export default AuthCheck;
</code>```

You can check out the fully functioning app here

https://github.com/iqbal125/react_hooks_fullstack_skeleton

Body:
Using react-router and reacts context api i am attempting to authenticate a user in Auth0 and then redirect the user to a home page on successful login. What am i missing in my routing? I am passing the context to the rest of the app by wrapping the app using  and passing the login and logout methods down the tree. When I call the login() method from a child component the login method in the context gets called where i set state {isAuthenticated} to true and then i call the Auth.login() from within the context component as shown in the attached code.

I have searched Auth0 docs and have setup the correct callback route to http://localhost:3000/admin/dashboard

When i click login on the page the first time the appropriate Auth0 component shows up and i can login, however after i enter credentials and hit the login button i am redirected back to the {Login} component. If i then hit the login button in the {Login} component again after that i can see the page trying to redirect to my home route and then it kicks me back to the {Login} component.

import auth from '../Auth/Auth'

const AuthContext = React.createContext();
const Auth = new auth();

class AuthProvider extends React.Component {
  state = { isAuthenticated: false }
  constructor() {
    super()
    this.login = this.login.bind(this)
    this.logout = this.logout.bind(this)
  }

  auth0Signin() {
    Auth.login()
  }

  login() {
    this.setState({ isAuthenticated: true })
    this.auth0Signin()
  }

  logout() {
    Auth.logout()
    this.setState({ isAuthenticated: false })
  }

  render() {
    return (
      <AuthContext.Provider
        value={{
          isAuthenticated: this.state.isAuthenticated,
          login: this.login,
          logout: this.logout
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}
const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer };

import Auth from './Auth/Auth'
import Callback from './views/components/Callback'
import { createBrowserHistory } from "history";
import React from 'react';
import "react-notification-alert/dist/animate.css";
import { Redirect, Route, Router, Switch } from "react-router-dom";
import { AuthConsumer, AuthProvider } from './providers/AuthContext';
import Login from './views/pages/Login';
import Register from './views/pages/Register'
import Dashboard from './layouts/Admin/Admin'

const auth = new Auth()
const hist = createBrowserHistory();

const handleAuthentication = (nextState, replace) => {
  if (/access_token|id_token|error/.test(nextState.location.hash)) {
    auth.handleAuthentication();
  }
}

const ProtectedRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =>
          isAuthenticated ? <Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> : <Redirect to='/auth/login' />}
        {...rest}
      />
    )}
  </AuthConsumer>
)

const PublicRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =><Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> }
        {...rest}
      />
    )}
  </AuthConsumer>
)

const App = () => {
  return (
    <>
      <Router history={hist}>
        <AuthProvider>
          {/*  */}
            <Switch>
              <ProtectedRoute path='/admin/dashboard' component={Dashboard} />
              <PublicRoute path='/auth/Register' component={Register} />
              <PublicRoute path='/auth/Login' component={Login} />
              <Route path="/callback" render={(props) => {
                  handleAuthentication(props);
                  return <Callback {...props} />
                }}/>
              <PublicRoute path='/' component={Login} />
            </Switch>
          {/*  */}
        </AuthProvider>
      </Router>
    </>
  );
}

export default App;

import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from './History';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    callbackUrl: AUTH_CONFIG.callbackUrl,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.redirectUri,
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        history.replace('/admin/dashboard');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  setSession(authResult) {
    // Set isLoggedIn flag in localStorage
    localStorage.setItem('isLoggedIn', 'true');

    // Set the time that the Access Token will expire at
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken;
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;

    // navigate to the home route
    history.replace('/home');
  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
       if (authResult && authResult.accessToken && authResult.idToken) {
         this.setSession(authResult);
       } else if (err) {
         this.logout();
         console.log(err);
         alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
       }
    });
  }

  logout() {
    // Remove tokens and expiry time
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;

    // Remove isLoggedIn flag from localStorage
    localStorage.removeItem('isLoggedIn');

    this.auth0.logout({
      returnTo: window.location.origin
    });

    // navigate to the home route
    history.replace('/auth/login');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }
}

Body:
The way I do it is with history.replace() in the Auth utility methods and then redirect to an authcheck component which upodates the global context state.

import auth0 from 'auth0-js'
import history from './history';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: 'webapp1.auth0.com',
    clientID: 'uZxUdMAsiDWeu3OrNpoi4JwJscdF5nAx',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid profile email'
  })

  userProfile = {}

  login = () => {
      this.auth0.authorize()
  }

  handleAuth = () => {
    this.auth0.parseHash((err, authResult) => {
      if(authResult) {
        localStorage.setItem('access_token', authResult.accessToken)
        localStorage.setItem('id_token', authResult.idToken)

        let expiresAt = JSON.stringify((authResult.expiresIn * 1000 + new Date().getTime()))
        localStorage.setItem('expiresAt', expiresAt)

        this.getProfile();
        setTimeout(() => { history.replace('/authcheck') }, 600);
      } else {
        console.log(err)
      }
    })
  }

  getAccessToken = () => {
    if(localStorage.getItem('access_token')) {
      const accessToken = localStorage.getItem('access_token')
      return accessToken
    } else {
      return null
    }
  }

  getProfile = () => {
    let accessToken = this.getAccessToken()
    if(accessToken) {
      this.auth0.client.userInfo(accessToken, (err, profile) => {
          if(profile) {
            this.userProfile = { profile }
          }
      } )
    }
  }

  logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('expiresAt')
    setTimeout(() => { history.replace('/authcheck') }, 200);
  }

  isAuthenticated = () => {
    let expiresAt = JSON.parse(localStorage.getItem('expiresAt'))
    return new Date().getTime() < expiresAt
  }

}

import React, { useEffect, useContext } from 'react';
import history from './history';
import Context from './context';
import * as ACTIONS from '../store/actions/actions';
import axios from 'axios';

const AuthCheck = () => {
  const context = useContext(Context)

  const send_profile_to_db = (profile) => {
   const data = profile
   axios.post('/api/posts/userprofiletodb', data )
    .then(axios.get('/api/get/userprofilefromdb', {params: {email: profile.profile.email}})
      .then(res => context.handleAddDBProfile(res.data)) )
    }

  useEffect(() => {
    if(context.authObj.isAuthenticated()) {
      context.handleUserLogin()
      context.handleUserAddProfile(context.authObj.userProfile)
      send_profile_to_db(context.authObj.userProfile)
      history.replace('/')
    }
    else {
      context.handleUserLogout()
      context.handleUserRemoveProfile()
      history.replace('/')
      }
    }, [])

    return(
        <div>
        </div>
    )}

export default AuthCheck;

You can check out the fully functioning app here

https://github.com/iqbal125/react_hooks_fullstack_skeleton


Title: Efficient use of numpy select

Body:
I have some data as follows. I'm trying to compute the values in the Time bw column (it should be 0 in the 4th row). Whenever the Location moves to a new one, like a to b, I want the Time bw to restart from 0. I'm trying to use ne ,select and diff()

+----------+---------------------+----------+
| Location |         Date        | Time bw  |
+----------+---------------------+----------+
| a        | 2018-06-26 00:00:00 |        0 |
| a        | 2018-06-26 00:00:00 |        0 |
| a        | 2018-06-26 00:00:00 |        0 |
| b        | 2018-08-03 00:00:00 |       38 |
| b        | 2018-08-03 00:00:00 |        0 |
| b        | 2018-08-04 00:00:00 |        1 |
| b        | 2018-08-04 00:00:00 |        0 |
| b        | 2018-08-04 00:00:00 |        0 |
| b        | 2018-08-04 00:00:00 |        0 |
| b        | 2018-08-04 00:00:00 |        0 |
| b        | 2018-08-04 00:00:00 |        0 |
| b        | 2018-08-05 00:00:00 |        1 |
| b        | 2018-08-08 00:00:00 |        3 |
| b        | 2018-08-08 00:00:00 |        0 |
| b        | 2018-08-08 00:00:00 |        0 |
| b        | 2018-08-08 00:00:00 |        0 |
| b        | 2018-08-08 00:00:00 |        0 |
| c        | 2018-08-14 00:00:00 |        6 |
| c        | 2018-08-14 00:00:00 |        0 |
| c        | 2018-08-14 00:00:00 |        0 |
+----------+---------------------+----------+

Body:
IIUC:

df['Time bw'] = np.where(df.Location.ne(df.Location.shift()), 0, df['Time bw'])

output:

    Location    Date    Time bw
0   a   20180626 00:00:00   0
1   a   20180626 00:00:00   0
2   a   20180626 00:00:00   0
3   b   20180803 00:00:00   0
4   b   20180803 00:00:00   0
5   b   20180804 00:00:00   1
6   b   20180804 00:00:00   0
7   b   20180804 00:00:00   0
8   b   20180804 00:00:00   0
9   b   20180804 00:00:00   0
10  b   20180804 00:00:00   0
11  b   20180805 00:00:00   1
12  b   20180808 00:00:00   3
13  b   20180808 00:00:00   0
14  b   20180808 00:00:00   0
15  b   20180808 00:00:00   0
16  b   20180808 00:00:00   0
17  c   20180814 00:00:00   0
18  c   20180814 00:00:00   0
19  c   20180814 00:00:00   0


问:
How can I pass context params using talend api?
I'm trying to automate talend job executions using the Talend API but I'm getting an error when I try to pass the context params using the api.

The json I'm encoding to 64 is the following:

```<code>JSON='{ "actionName":"runTask", "authPass": "TalendPass", "authUser": "name@example.com", "jvmParams": [ "-Xmx256m" , "-Xms64m" ], "contextParams": ["host_mysql_db01": "failed", "database_analytics": "testing.it"],"mode": "synchronous", "taskId": 43}'
</code>```

Error message:

```<code>{"error":"Expected a ',' or ']' at character 172","returnCode":2}
</code>```

I found another stackoverflow issue Add context parameters to Talend job in Tac via API without actually running it but he doesn't say how he pass it and I cannot reply with a comment asking how he did it

The real talend api call is:

```<code>wget -O file http://localhost:8080/org.talend.administrator/metaServlet?$JSON_ENCODED
</code>```

Can I get some help?

答:
Actually, the json your are passing to the metaservlet is not valid json. You can check it with an online validator like http://jsonlint.com.

You are specifying the contextParams attribute as an array, but that syntax is not valid in json. An array can contain either a list of values (like jvmParams) or objects (which can themselves contain arrays). Here's an example.

Moreover, according to Talend reference, the attribute should be called "context" and must be an object instead of an array, like so:

```<code>"context":{"varname1": "varvalue", "varname2": "varvalue2"}
</code>```

Body:
I'm trying to automate talend job executions using the Talend API but I'm getting an error when I try to pass the context params using the api.

The json I'm encoding to 64 is the following:

JSON='{ "actionName":"runTask", "authPass": "TalendPass", "authUser": "name@example.com", "jvmParams": [ "-Xmx256m" , "-Xms64m" ], "contextParams": ["host_mysql_db01": "failed", "database_analytics": "testing.it"],"mode": "synchronous", "taskId": 43}'

Error message:

{"error":"Expected a ',' or ']' at character 172","returnCode":2}

I found another stackoverflow issue Add context parameters to Talend job in Tac via API without actually running it but he doesn't say how he pass it and I cannot reply with a comment asking how he did it

The real talend api call is:

wget -O file http://localhost:8080/org.talend.administrator/metaServlet?$JSON_ENCODED

Can I get some help?

Body:
Actually, the json your are passing to the metaservlet is not valid json. You can check it with an online validator like http://jsonlint.com.

You are specifying the contextParams attribute as an array, but that syntax is not valid in json. An array can contain either a list of values (like jvmParams) or objects (which can themselves contain arrays). Here's an example.

Moreover, according to Talend reference, the attribute should be called "context" and must be an object instead of an array, like so:

"context":{"varname1": "varvalue", "varname2": "varvalue2"}


问:
Is it possible to train a CNN starting at an intermediate layer (in general and in Keras)?
I'm using mobilenet v2 to train a model on my images. I've frozen all but a few layers and then added additional layers for training. I'd like to be able to train from an intermediate layer rather than from the beginning. My questions:

Is it possible to provide the output of the last frozen layer as the
input for training (it would be a tensor of (?, 7,7,1280))?

How does one specify training to start from that first trainable
(non-frozen) layer? In this case, mbnetv2_conv.layer[153].

What is y_train in this case? I don't quite understand how y_train
is being used during the training process- in general, when does the
CNN refer back to y_train?

Load mobilenet v2

```<code>image_size = 224
mbnetv2_conv = MobileNetV2(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))

    # Freeze all layers except the last 3 layers
    for layer in mbnetv2_conv.layers[:-3]:
        layer.trainable = False

    # Create the model
    model = models.Sequential()
    model.add(mbnetv2_conv)
    model.add(layers.Flatten())
    model.add(layers.Dense(16, activation='relu'))
    model.add(layers.Dropout(0.5))
    model.add(layers.Dense(3, activation='softmax'))
    model.summary()

    # Build an array (?,224,224,3) from images
    x_train = np.array(all_images)

    # Get layer output
    from keras import backend as K
    get_last_frozen_layer_output = K.function([mbnetv2_conv.layers[0].input],
                                  [mbnetv2_conv.layers[152].output])
    last_frozen_layer_output = get_last_frozen_layer_output([x_train])[0]

    # Compile the model
    from keras.optimizers import SGD
    sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['acc'])

    # how to train from a specific layer and what should y_train be?
    model.fit(last_frozen_layer_output, y_train, batch_size=2, epochs=10)
</code>```

答:
Yes, you can.   Two different ways.

First, the hard way makes you build two new models, one with all your frozen layers, one with all your trainable layers. Add a Flatten() layer to the frozen-layers-only model.  And you will copy the weights from mobilenet v2 layer by layer to populate the weights of the frozen-layers-only model.  Then you will run your input images through the frozen-layers-only model, saving the output to disk in CSV or pickle form.  This is now the input for your trainable-layers model, which you train with the model.fit() command as you did above.   Save the weights when you're done training.  Then you will have to build the original model with both sets of layers, and load the weights into each layer, and save the whole thing.  You're done!

However, the easier way is to save the weights of your model separately from the architecture with:

```<code>model.save_weights(filename)
</code>```

then modify the layer.trainable property of the layers in MobileNetV2 before you add it into a new empty model:

```<code>mbnetv2_conv = MobileNetV2(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))
for layer in mbnetv2_conv.layers[:153]:
    layer.trainable = False
model = models.Sequential()
model.add(mbnetv2_conv)
</code>```

then reload the weights with

```<code>newmodel.load_weights(filename)
</code>```

This lets you adjust which layers in your mbnetv2_conv model you will be training on the fly, and then just call model.fit() to continue training.

Body:
I'm using mobilenet v2 to train a model on my images. I've frozen all but a few layers and then added additional layers for training. I'd like to be able to train from an intermediate layer rather than from the beginning. My questions:

Is it possible to provide the output of the last frozen layer as the
input for training (it would be a tensor of (?, 7,7,1280))?

How does one specify training to start from that first trainable
(non-frozen) layer? In this case, mbnetv2_conv.layer[153].

What is y_train in this case? I don't quite understand how y_train
is being used during the training process- in general, when does the
CNN refer back to y_train?

Load mobilenet v2

image_size = 224
mbnetv2_conv = MobileNetV2(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))

    # Freeze all layers except the last 3 layers
    for layer in mbnetv2_conv.layers[:-3]:
        layer.trainable = False

    # Create the model
    model = models.Sequential()
    model.add(mbnetv2_conv)
    model.add(layers.Flatten())
    model.add(layers.Dense(16, activation='relu'))
    model.add(layers.Dropout(0.5))
    model.add(layers.Dense(3, activation='softmax'))
    model.summary()

    # Build an array (?,224,224,3) from images
    x_train = np.array(all_images)

    # Get layer output
    from keras import backend as K
    get_last_frozen_layer_output = K.function([mbnetv2_conv.layers[0].input],
                                  [mbnetv2_conv.layers[152].output])
    last_frozen_layer_output = get_last_frozen_layer_output([x_train])[0]

    # Compile the model
    from keras.optimizers import SGD
    sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['acc'])

    # how to train from a specific layer and what should y_train be?
    model.fit(last_frozen_layer_output, y_train, batch_size=2, epochs=10)

Body:
Yes, you can.   Two different ways.

First, the hard way makes you build two new models, one with all your frozen layers, one with all your trainable layers. Add a Flatten() layer to the frozen-layers-only model.  And you will copy the weights from mobilenet v2 layer by layer to populate the weights of the frozen-layers-only model.  Then you will run your input images through the frozen-layers-only model, saving the output to disk in CSV or pickle form.  This is now the input for your trainable-layers model, which you train with the model.fit() command as you did above.   Save the weights when you're done training.  Then you will have to build the original model with both sets of layers, and load the weights into each layer, and save the whole thing.  You're done!

However, the easier way is to save the weights of your model separately from the architecture with:

model.save_weights(filename)

then modify the layer.trainable property of the layers in MobileNetV2 before you add it into a new empty model:

mbnetv2_conv = MobileNetV2(weights='imagenet', include_top=False, input_shape=(image_size, image_size, 3))
for layer in mbnetv2_conv.layers[:153]:
    layer.trainable = False
model = models.Sequential()
model.add(mbnetv2_conv)

then reload the weights with

newmodel.load_weights(filename)

This lets you adjust which layers in your mbnetv2_conv model you will be training on the fly, and then just call model.fit() to continue training.