问:
UIcollectionView sizing issue
My all output string on console.</p>
```<code>15:57:56.116319+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.116509+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.116638+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.116911+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.117059+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.117211+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.117328+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.129857+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.130183+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.130318+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.130450+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.130591+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.130702+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.130939+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.131069+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.131166+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.131269+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.131613+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.132090+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.132379+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.132827+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.133225+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.133876+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.134260+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.134523+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.134832+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.135166+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.135464+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.135893+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.136121+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.136446+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.136759+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.137100+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.137436+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.137683+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
</code>```

答:
You need to double check these things:

Collection view bounds (width, height), where and how do you set them.

Collection view cell bounds (width, height). Width and height of cells must not be more than collection view bounds.

Check collection view content insets, they can break your layout. If cell size is more, than (Collection view bounds - collectionView insets), than you can have this error.

Title: UIcollectionView sizing issue

Body:
My all output string on console.

15:57:56.116319+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.116509+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.116638+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.116911+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.117059+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.117211+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.117328+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.129857+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.130183+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.130318+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.130450+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.130591+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.130702+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.130939+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.131069+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.131166+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.131269+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.131613+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.132090+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.132379+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.132827+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.133225+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.133876+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.134260+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.134523+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.134832+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.135166+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.135464+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.135893+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.136121+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
2020-02-14 15:57:56.136446+0500 Flo[5489:191774] The behavior of the UICollectionViewFlowLayout is not defined because:
2020-02-14 15:57:56.136759+0500 Flo[5489:191774] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2020-02-14 15:57:56.137100+0500 Flo[5489:191774] Please check the values returned by the delegate.
2020-02-14 15:57:56.137436+0500 Flo[5489:191774] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7fc39cd05c80>, and it is attached to <UICollectionView: 0x7fc39d80ca00; frame = (0 44; 414 589); clipsToBounds = YES; autoresize = H; gestureRecognizers = <NSArray: 0x600002e75f50>; layer = <CALayer: 0x60000203d0e0>; contentOffset: {-15, -15}; contentSize: {384, 760}; adjustedContentInset: {15, 15, 10, 15}; layout: <UICollectionViewFlowLayout: 0x7fc39cd05c80>; dataSource: <Flo.DashboardViewController: 0x7fc39ce07930>>.
2020-02-14 15:57:56.137683+0500 Flo[5489:191774] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.


来源: stackexchange

问:
Spring security: How I make to follow a link after logging and not going to the homepage
I'm one of the developers of an application in what we have a login page to enter the dashboard. Inside the dashboard, there are different links that send you to other parts of the application.

The problem comes when you want to enter one of the internal links when you are no login. so in the browser you enter the address, put your credentials to continue to the web page, but instead, you are redirected to the dashboard.

The webpage I want to enter is:

```<code>http://localhost:8080/admin-ng/index.html#!/events/events/cd15fb84-d6b1-49ab-a28c-e5e07683907e/tools/editor
</code>```

but after login always redirects to the dashboard:

```<code>http://localhost:8080/admin-ng/index.html#!/events/events
</code>```

Then if I enter again the address works.

Also, I tried with a rest endpoint to call again the address after you log in, but it doesn't work, it is the same behavior.

I think it should be with the spring security config file. In how handle the requests after you are log in. I think it loses the rest of the information after the "#". What I can do?

Thanks

答:
The problem comes from your authentication success handler, or your entry point.

I suggest to debug to figure out what is put in the INITIAL_REQUEST_PATH session attribute and if it is what you want.

ContentLicense: CC BY-SA 4.0

Body:
I'm one of the developers of an application in what we have a login page to enter the dashboard. Inside the dashboard, there are different links that send you to other parts of the application.

The problem comes when you want to enter one of the internal links when you are no login. so in the browser you enter the address, put your credentials to continue to the web page, but instead, you are redirected to the dashboard.

The webpage I want to enter is:

http://localhost:8080/admin-ng/index.html#!/events/events/cd15fb84-d6b1-49ab-a28c-e5e07683907e/tools/editor

but after login always redirects to the dashboard:

http://localhost:8080/admin-ng/index.html#!/events/events

Then if I enter again the address works.

Also, I tried with a rest endpoint to call again the address after you log in, but it doesn't work, it is the same behavior.

I think it should be with the spring security config file. In how handle the requests after you are log in. I think it loses the rest of the information after the "#". What I can do?

Thanks


问:
Interrupt when clicking on button
I've done a basic interface with the code bellow. When I click the start button, a word start to be displayed / hidden in using a loop.

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'gui.ui',
# licensing of 'gui.ui' applies.
#
# Created: Fri Feb 14 11:07:45 2020
#      by: pyside2-uic  running on PySide2 5.13.2
#
# WARNING! All changes made in this file will be lost!

from PySide2 import QtCore, QtGui, QtWidgets
import time

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        spacerItem = QtWidgets.QSpacerItem(20, 117, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 0, 0, 1, 1)
        self.label = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(45)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        spacerItem1 = QtWidgets.QSpacerItem(20, 117, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem1, 2, 0, 1, 1)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.horizontalLayout_4.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_2.addWidget(self.label_3)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout_3.addWidget(self.lineEdit_3)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_3)
        self.gridLayout.addLayout(self.horizontalLayout_4, 3, 0, 1, 1)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_5.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_5.addWidget(self.pushButton_2)
        self.gridLayout.addLayout(self.horizontalLayout_5, 4, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.start)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow", "MainWindow", None, -1))
        self.label.setText(QtWidgets.QApplication.translate("MainWindow", "Bonjour", None, -1))
        self.label_2.setText(QtWidgets.QApplication.translate("MainWindow", "Mot", None, -1))
        self.lineEdit.setText(QtWidgets.QApplication.translate("MainWindow", "Bonjour", None, -1))
        self.label_3.setText(QtWidgets.QApplication.translate("MainWindow", "Temps ON (s)", None, -1))
        self.lineEdit_2.setText(QtWidgets.QApplication.translate("MainWindow", "1", None, -1))
        self.label_4.setText(QtWidgets.QApplication.translate("MainWindow", "Temps OFF (s)", None, -1))
        self.lineEdit_3.setText(QtWidgets.QApplication.translate("MainWindow", "1", None, -1))
        self.pushButton.setText(QtWidgets.QApplication.translate("MainWindow", "Start", None, -1))
        self.pushButton_2.setText(QtWidgets.QApplication.translate("MainWindow", "Stop", None, -1))

    def start(self):
        mot = self.lineEdit.text()
        print(mot)
        temps_on = float(self.lineEdit_2.text())
        temps_off = float(self.lineEdit_3.text())

        stop = 0

        while True:
            self.label.setText(mot)
            time.sleep(temps_on)
            QtGui.qApp.processEvents()
            self.label.setText('')
            time.sleep(temps_off)
            QtGui.qApp.processEvents()

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

BUT I would like to stop the loop when I click on the stop button. Any idea on how to do that ?

I know it is not usually to integrate the functions directly into the gui file, but it is not important here.

答:
In a GUI you should not use sleep since it blocks the GUI, in general if you want to make a delay the correct thing is to use a QTimer. On the other hand, if you are going to obtain numerical values from the GUI, it is better to have a QSpinBox or QDoubleSpinBox or a QLineEdit with a suitable QValidator to prevent the user from entering non-numerical elements, considering that I have implemented the following solution:

from PySide2 import QtCore, QtGui, QtWidgets

class Timer(QtCore.QObject):
    timeout = QtCore.Signal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self._time_on = 1000
        self._time_off = 1000

        self._state = False
        self._is_running = False
        self._timer = QtCore.QTimer(singleShot=True, timeout=self._on_timeout)

    @property
    def state(self):
        return self._state

    @property
    def time_on(self):
        return self._time_on

    @time_on.setter
    def time_on(self, time):
        self._time_on = time

    @property
    def time_off(self):
        return self._time_off

    @time_off.setter
    def time_off(self, time):
        self._time_off = time

    def start(self):
        self._state = True
        self._on_timeout()

    def stop(self):
        self._timer.stop()

    def _on_timeout(self):
        self.timeout.emit(self.state)
        self._timer.start(self.time_on if self.state else self.time_off)
        self._state = not self._state

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.label = QtWidgets.QLabel()
        self.lineedit = QtWidgets.QLineEdit(text="Bonjour")
        self.on_spinbox = QtWidgets.QDoubleSpinBox(minimum=0)
        self.off_spinbox = QtWidgets.QDoubleSpinBox(minimum=0)
        self.start_button = QtWidgets.QPushButton("Start")
        self.stop_button = QtWidgets.QPushButton("Stop")

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QGridLayout(central_widget)
        lay.addWidget(self.label, 0, 0, 1, 6)
        lay.addWidget(QtWidgets.QLabel("Mot"), 1, 0)
        lay.addWidget(self.lineedit, 1, 1)
        lay.addWidget(QtWidgets.QLabel("Temps ON (s)"), 1, 2)
        lay.addWidget(self.on_spinbox, 1, 3)
        lay.addWidget(QtWidgets.QLabel("Temps OFF (s)"), 1, 4)
        lay.addWidget(self.off_spinbox, 1, 5)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.start_button)
        hlay.addWidget(self.stop_button)
        lay.addLayout(hlay, 2, 0, 1, 6)
        self.resize(640, 480)

        font = QtGui.QFont()
        font.setPointSize(45)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        self.start_button.clicked.connect(self.start)
        self.stop_button.clicked.connect(self.stop)

        self.timer = Timer()
        self.timer.timeout.connect(self.onTimeout)

    @QtCore.Slot()
    def start(self):
        self.timer.time_on = 1000 * self.on_spinbox.value()
        self.timer.time_off = 1000 * self.off_spinbox.value()
        self.timer.start()

    @QtCore.Slot()
    def stop(self):
        self.timer.stop()

    @QtCore.Slot(bool)
    def onTimeout(self, state):
        if state:
            self.label.setText(self.lineedit.text())
        else:
            self.label.clear()

if __name__ == "__main__":
    import sys

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

Title: Interrupt when clicking on button

Body:
I've done a basic interface with the code bellow. When I click the start button, a word start to be displayed / hidden in using a loop.

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'gui.ui',
# licensing of 'gui.ui' applies.
#
# Created: Fri Feb 14 11:07:45 2020
#      by: pyside2-uic  running on PySide2 5.13.2
#
# WARNING! All changes made in this file will be lost!

from PySide2 import QtCore, QtGui, QtWidgets
import time

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        spacerItem = QtWidgets.QSpacerItem(20, 117, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 0, 0, 1, 1)
        self.label = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(45)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        spacerItem1 = QtWidgets.QSpacerItem(20, 117, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem1, 2, 0, 1, 1)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.horizontalLayout_4.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_2.addWidget(self.label_3)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout_3.addWidget(self.lineEdit_3)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_3)
        self.gridLayout.addLayout(self.horizontalLayout_4, 3, 0, 1, 1)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_5.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_5.addWidget(self.pushButton_2)
        self.gridLayout.addLayout(self.horizontalLayout_5, 4, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.start)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow", "MainWindow", None, -1))
        self.label.setText(QtWidgets.QApplication.translate("MainWindow", "Bonjour", None, -1))
        self.label_2.setText(QtWidgets.QApplication.translate("MainWindow", "Mot", None, -1))
        self.lineEdit.setText(QtWidgets.QApplication.translate("MainWindow", "Bonjour", None, -1))
        self.label_3.setText(QtWidgets.QApplication.translate("MainWindow", "Temps ON (s)", None, -1))
        self.lineEdit_2.setText(QtWidgets.QApplication.translate("MainWindow", "1", None, -1))
        self.label_4.setText(QtWidgets.QApplication.translate("MainWindow", "Temps OFF (s)", None, -1))
        self.lineEdit_3.setText(QtWidgets.QApplication.translate("MainWindow", "1", None, -1))
        self.pushButton.setText(QtWidgets.QApplication.translate("MainWindow", "Start", None, -1))
        self.pushButton_2.setText(QtWidgets.QApplication.translate("MainWindow", "Stop", None, -1))

    def start(self):
        mot = self.lineEdit.text()
        print(mot)
        temps_on = float(self.lineEdit_2.text())
        temps_off = float(self.lineEdit_3.text())

        stop = 0

        while True:
            self.label.setText(mot)
            time.sleep(temps_on)
            QtGui.qApp.processEvents()
            self.label.setText('')
            time.sleep(temps_off)
            QtGui.qApp.processEvents()

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

BUT I would like to stop the loop when I click on the stop button. Any idea on how to do that ?

I know it is not usually to integrate the functions directly into the gui file, but it is not important here.


问:
DenseNet: Graph disconnected: cannot obtain value for tensor
I am trying to build up a Densenet but stuck with the following error..
Here is the smallest example to reproduce:

```<code>import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))
</code>```

The error I get:

```<code>ValueError: Graph disconnected: cannot obtain value for tensor Tensor("Conv2/Identity:0", shape=(None, 128, 128, 16), dtype=float32) at layer "Concat1". The following previous layers were accessed without issue: ['Inputs', 'Conv1']
</code>```

I could not realize what is wrong with this model?

The idea behind using feature_list here is that later I can create a dense block with a variable number of convolution layers, i.e.:

```<code>    for i in range(nb_layers):
          nb_filter += growth_rate
          x = tfkl.Concatenate(axis=-1)(feature_list)
          x = tfkl.Conv2D(nb_filter , kernel_size=(3, 3), padding="same")(x)
          feature_list.append(x)
</code>```

Furthermore, if I comment out the following two lines in create_model function:

```<code>    #feature_list.append(x)
    #x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)
</code>```

then the model works without problems (so it means that generally Concatenate works correctly):

```<code>z.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
Inputs (InputLayer)             [(None, 128, 128, 2) 0
__________________________________________________________________________________________________
Conv1 (Conv2D)                  (None, 128, 128, 16) 304         Inputs[0][0]
__________________________________________________________________________________________________
Concat1 (Concatenate)           (None, 128, 128, 18) 0           Inputs[0][0]
                                                                 Conv1[0][0]
__________________________________________________________________________________________________
Conv2 (Conv2D)                  (None, 128, 128, 16) 2608        Concat1[0][0]
==================================================================================================
Total params: 2,912
Trainable params: 2,912
Non-trainable params: 0
__________________________________________________________________________________________________
</code>```

答:
Think that keras functional model creation does not run eagerly and the lists are just references. So when you append the Conv2 output to feature list it is also reflected at the following line: x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list) where you don't really have Conv2 output.

What you should do is to call the Concat layer with a copy of the features list. See the example below:

```<code>import copy
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(copy.copy(feature_list))
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    print(feature_list)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(copy.copy(feature_list))

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))
</code>```

Body:
I am trying to build up a Densenet but stuck with the following error..
Here is the smallest example to reproduce:

import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))

The error I get:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("Conv2/Identity:0", shape=(None, 128, 128, 16), dtype=float32) at layer "Concat1". The following previous layers were accessed without issue: ['Inputs', 'Conv1']

I could not realize what is wrong with this model?

The idea behind using feature_list here is that later I can create a dense block with a variable number of convolution layers, i.e.:

    for i in range(nb_layers):
          nb_filter += growth_rate
          x = tfkl.Concatenate(axis=-1)(feature_list)
          x = tfkl.Conv2D(nb_filter , kernel_size=(3, 3), padding="same")(x)
          feature_list.append(x)

Furthermore, if I comment out the following two lines in create_model function:

    #feature_list.append(x)
    #x = tfkl.Concatenate(axis=-1, name="Concat2")(feature_list)

then the model works without problems (so it means that generally Concatenate works correctly):

z.summary()
Model: "model"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
Inputs (InputLayer)             [(None, 128, 128, 2) 0
__________________________________________________________________________________________________
Conv1 (Conv2D)                  (None, 128, 128, 16) 304         Inputs[0][0]
__________________________________________________________________________________________________
Concat1 (Concatenate)           (None, 128, 128, 18) 0           Inputs[0][0]
                                                                 Conv1[0][0]
__________________________________________________________________________________________________
Conv2 (Conv2D)                  (None, 128, 128, 16) 2608        Concat1[0][0]
==================================================================================================
Total params: 2,912
Trainable params: 2,912
Non-trainable params: 0
__________________________________________________________________________________________________

Body:
Think that keras functional model creation does not run eagerly and the lists are just references. So when you append the Conv2 output to feature list it is also reflected at the following line: x = tfkl.Concatenate(axis=-1, name="Concat1")(feature_list) where you don't really have Conv2 output.

What you should do is to call the Concat layer with a copy of the features list. See the example below:

import copy
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as tfkl

def create_model(input_dim):

    feature_list = list()
    input_x = tfkl.Input(shape=input_dim, name="Inputs")
    feature_list.append(input_x)
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv1")(input_x)
    feature_list.append(x)

    x = tfkl.Concatenate(axis=-1, name="Concat1")(copy.copy(feature_list))
    x = tfkl.Conv2D(16, kernel_size=(3, 3), padding="same", name="Conv2")(x)
    feature_list.append(x)
    print(feature_list)
    x = tfkl.Concatenate(axis=-1, name="Concat2")(copy.copy(feature_list))

    return tf.keras.Model(inputs=input_x, outputs=x)

z = create_model((128,128,2))


问:
How to expand tabs in QTabWidget Qt
I have a QTabWidget like this one:

But I want to expand the tabs to "fill" the entire widget width, like this:

How can I do that?

I am using Qt 5.3.2 and Qt Creator 3.2.1

Update:

I tried to use the setExpanding function:

```<code>ui->myTabWidget->tabBar()->setExpanding(true);
</code>```

But it didn't work.

答:
Suggestion from Mitak worked. Assuming the tabwiget is in the centralwidget of the mainwindow, one can replace a tabwidget created with the designer as follow in the code :

```<code>QTabWidget* newTabWidget = new GeneralTabWidget(ui->tabWidget_ToReplace->parentWidget());
ui->centralWidget->layout()->replaceWidget(ui->tabWidget_ToReplace, newTabWidget );
delete ui->tabWidget_ToReplace;
ui->tabWidget_ToReplace= newTabWidget ;
</code>```

if the tabwidget is situated in another location or in a dialog, one need to replace it in the appropriate layout.

ContentLicense: CC BY-SA 3.0

Title: How to expand tabs in QTabWidget Qt

Body:
I have a QTabWidget like this one:

But I want to expand the tabs to "fill" the entire widget width, like this:

How can I do that?

I am using Qt 5.3.2 and Qt Creator 3.2.1

Update:

I tried to use the setExpanding function:

ui->myTabWidget->tabBar()->setExpanding(true);

But it didn't work.

Body:
Suggestion from Mitak worked. Assuming the tabwiget is in the centralwidget of the mainwindow, one can replace a tabwidget created with the designer as follow in the code :

QTabWidget* newTabWidget = new GeneralTabWidget(ui->tabWidget_ToReplace->parentWidget());
ui->centralWidget->layout()->replaceWidget(ui->tabWidget_ToReplace, newTabWidget );
delete ui->tabWidget_ToReplace;
ui->tabWidget_ToReplace= newTabWidget ;

if the tabwidget is situated in another location or in a dialog, one need to replace it in the appropriate layout.


问:
soft keyboard not appearing
I have a following dialog:

```<code>import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}
</code>```

I open it from a different activity like this:

```<code>IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();
</code>```

And the layout of the dialog is the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>
</code>```

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

```<code>InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);
</code>```

What else can I try? What is the issue here?

答:
Have you tried to post showSoftInput? I use a utility function for this:

```<code>public static void showSoftKeyboard(EditText v) {
    Context c = v.getContext();
    InputMethodManager keyboard = (InputMethodManager)
            c.getSystemService(Context.INPUT_METHOD_SERVICE);
    v.requestFocus();
    keyboard.showSoftInput(v, 0);
}

public static boolean postShowSoftKeyboard(final EditText v) {
    return v.post(new Runnable() {
        @Override
        public void run() {
            showSoftKeyboard(v);
        }
    });
}
</code>```

Title: soft keyboard not appearing

Body:
I have a following dialog:

import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}

I open it from a different activity like this:

IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();

And the layout of the dialog is the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);

What else can I try? What is the issue here?

Body:
Have you tried to post showSoftInput? I use a utility function for this:

public static void showSoftKeyboard(EditText v) {
    Context c = v.getContext();
    InputMethodManager keyboard = (InputMethodManager)
            c.getSystemService(Context.INPUT_METHOD_SERVICE);
    v.requestFocus();
    keyboard.showSoftInput(v, 0);
}

public static boolean postShowSoftKeyboard(final EditText v) {
    return v.post(new Runnable() {
        @Override
        public void run() {
            showSoftKeyboard(v);
        }
    });
}


问:
Why does my altered tkinter widget not place correctly?
Im creating a user management system that allows the admin to create user / employee accounts. When using the default tkinter "Entry" widget it places correctly. correct placement

However when i use my version of the tk entry (LabeledEntry), it places like this

this is the code for my altered entry widget:

```<code>class LabeledEntry(tk.Entry): #creates a version of the tkEntry widget that allows for "ghost" text to be within the entry field.
    def __init__(self, master=None, label = ""): #which instructs the user on what to enter in the field.
        tk.Entry.__init__(self)
        self.label = label
        self.on_exit()
        self.bind('<FocusOut>', self.on_exit)
        self.bind('<FocusIn>', self.on_entry)

    def on_entry(self, event=None):
        if self.get() == self.label: #checks if the given label is present
            self.delete(0, tk.END)  #If the text field of the entry is the same as the label, it is deleted to allow for user input
            self.configure(fg = "black") #sets the text color to black

    def on_exit(self, event=None):
        if not self.get(): #checks if user entered anything into the entry when clicked into it.
            self.insert(0, self.label) #If they did not, sets the text to the original label
            self.configure(fg = "grey") #and changes the color of the text to grey.
</code>```

Is there a way to resolve this issue?

答:
You aren't passing master to the superclass ctor, which is probably part of the issue:

```<code>class LabeledEntry(tk.Entry):
    def __init__(self, master=None, label = ""):
        super().__init__(master=master)
        # ...
</code>```

Body:
Im creating a user management system that allows the admin to create user / employee accounts. When using the default tkinter "Entry" widget it places correctly. correct placement

However when i use my version of the tk entry (LabeledEntry), it places like this

this is the code for my altered entry widget:

class LabeledEntry(tk.Entry): #creates a version of the tkEntry widget that allows for "ghost" text to be within the entry field.
    def __init__(self, master=None, label = ""): #which instructs the user on what to enter in the field.
        tk.Entry.__init__(self)
        self.label = label
        self.on_exit()
        self.bind('<FocusOut>', self.on_exit)
        self.bind('<FocusIn>', self.on_entry)

    def on_entry(self, event=None):
        if self.get() == self.label: #checks if the given label is present
            self.delete(0, tk.END)  #If the text field of the entry is the same as the label, it is deleted to allow for user input
            self.configure(fg = "black") #sets the text color to black

    def on_exit(self, event=None):
        if not self.get(): #checks if user entered anything into the entry when clicked into it.
            self.insert(0, self.label) #If they did not, sets the text to the original label
            self.configure(fg = "grey") #and changes the color of the text to grey.

Is there a way to resolve this issue?

Body:
You aren't passing master to the superclass ctor, which is probably part of the issue:

class LabeledEntry(tk.Entry):
    def __init__(self, master=None, label = ""):
        super().__init__(master=master)
        # ...


问:
How do I use Dataframe apply function to normalize Data
I'm trying to normalize new data with the mean and std values which I already have got.

```<code>t = np.array([[1,2,3],
     [4,5,6],
     [7,8,9]])

tt = np.array([[1,1,1],
     [100,100,100]])

a = pd.DataFrame(t, columns=['a','b','c'])
b = pd.DataFrame(tt, columns=['a', 'b', 'c'], index=['mean', 'std'])

def standardize(x, y):
    return (x - y.loc['mean']) / y.loc['std']
</code>```

```<code>a.apply(standardize(a,b))
</code>```

I want to get normalized dataframe that each values is calculated by 'b' dataframe's mean and std on each columns with apply function

ex) a[0]['a'] = (a[0]['a'] - b['mean']['a']) / b['std'][a]

any better ways would be fine as well. Thanks..

答: You already have it. Do standardize(a,b) instead of a.apply(standardize(a,b)).

Body:
I'm trying to normalize new data with the mean and std values which I already have got.

t = np.array([[1,2,3],
     [4,5,6],
     [7,8,9]])

tt = np.array([[1,1,1],
     [100,100,100]])

a = pd.DataFrame(t, columns=['a','b','c'])
b = pd.DataFrame(tt, columns=['a', 'b', 'c'], index=['mean', 'std'])

def standardize(x, y):
    return (x - y.loc['mean']) / y.loc['std']

a.apply(standardize(a,b))

I want to get normalized dataframe that each values is calculated by 'b' dataframe's mean and std on each columns with apply function

ex) a[0]['a'] = (a[0]['a'] - b['mean']['a']) / b['std'][a]

any better ways would be fine as well. Thanks..


问:
Filter intermediary ManyToMany django
```<code>class Ingredient(Model):
    name = CharField(max_length=55, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Product(Model):
    name = CharField(max_length=55)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name', )

class ProductIngredient(Model):
    product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients')
    ingredient = ForeignKey(Ingredient, on_delete=CASCADE)
    optional = BooleanField(default=False)

    class Meta:
        unique_together = (('product', 'ingredient'),)
        ordering = ('product__name',)

    def __str__(self):
        return f'{self.product} - {self.ingredient}'
</code>```

I want to make two queries:

select all products, whose ingredients contain strawberry AND milk

select all products, whose ingredients contain strawberry OR milk

The first query is: Product.objects.prefetch_related('product_ingredients__ingredient').filter(product__ingredients__ingredient__name='strawberry').filter(product__ingredients__ingredient__name='milk')

Do I need to write distinct in the first query?
How to write the second query?

答:
Use Q object for complex lookups</p>

```<code>Product.objects.prefetch_related('product_ingredients__ingredient').filter(Q(product__ingredients__ingredient__name='strawberry')|Q(product__ingredients__ingredient__name='milk'))
</code>```

Title: Filter intermediary ManyToMany django

Body:
class Ingredient(Model):
    name = CharField(max_length=55, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Product(Model):
    name = CharField(max_length=55)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name', )

class ProductIngredient(Model):
    product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients')
    ingredient = ForeignKey(Ingredient, on_delete=CASCADE)
    optional = BooleanField(default=False)

    class Meta:
        unique_together = (('product', 'ingredient'),)
        ordering = ('product__name',)

    def __str__(self):
        return f'{self.product} - {self.ingredient}'

I want to make two queries:

select all products, whose ingredients contain strawberry AND milk

select all products, whose ingredients contain strawberry OR milk

The first query is: Product.objects.prefetch_related('product_ingredients__ingredient').filter(product__ingredients__ingredient__name='strawberry').filter(product__ingredients__ingredient__name='milk')

Do I need to write distinct in the first query?
How to write the second query?

Body:
Use Q object for complex lookups

Product.objects.prefetch_related('product_ingredients__ingredient').filter(Q(product__ingredients__ingredient__name='strawberry')|Q(product__ingredients__ingredient__name='milk'))


问:
Trigger Google Cloud Build with Google Cloud Scheduler periodically
Is it somehow possible to trigger a Google Cloud Build with Google Cloud Scheduler periodically?

I can't find anything related to it on the Internet.

答:
The first option is to create a schedule to trigger a build:

```<code>gcloud scheduler jobs create http ${PROJECT_ID}-run-trigger \
    --schedule='0 12 * * *' \
    --uri=https://cloudbuild.googleapis.com/v1/projects/${PROJECT_ID}/triggers/${TRIGGER_ID}:run \
    --message-body='{\"branchName\": \"${BRANCH_NAME}\"}' \
    --oauth-service-account-email=${PROJECT_ID}@appspot.gserviceaccount.com \
    --oauth-token-scope=https://www.googleapis.com/auth/cloud-platform
</code>```

Note that you can almost run this from within a cloud build. PROJECT_ID is the name of the project and BRANCH_NAME is the name of the branch (development, master, etc.). Both are available from within your cloud build pipeline. TRIGGER_ID can be fetched with the following command:

```<code>gcloud beta builds triggers list --format json
</code>```

Additional to branchName, you can also specify other attributes in the message body, giving you more flexibility:

commitSha

dir

invertRegex

projectId

repoName

substitutions

tagName

The second option is to submit a cloudbuild on a schedule:

```<code>gcloud scheduler jobs create http ${PROJECT_ID}-run-build \
    --schedule='0 12 * * *' \
    --uri=https://cloudbuild.googleapis.com/v1/projects/${PROJECT_ID}/builds \
    --message-body-from-file=cloudbuild.json \
    --message-body="{\"branchName\": \"${BRANCH_NAME}\"} \
    --oauth-service-account-email=${PROJECT_ID}@appspot.gserviceaccount.com \
    --oauth-token-scope=https://www.googleapis.com/auth/cloud-platform
</code>```

Your cloudbuild.json can look something like this:

```<code>{
    "timeout": "60s",
    "steps": [
        {
            "name": "gcr.io/cloud-builders/gcloud",
            "entrypoint": "bash",
            "args": [
                "-c",
                "echo "Hello"
            ]
        },
        {
            "name": "gcr.io/cloud-builders/gcloud",
            "entrypoint": "bash",
            "args": [
                "-c",
                "echo "World"
            ]
        }
    ],
    "substitutions": {
        "BRANCH_NAME": "$BRANCH_NAME"
    }
}
</code>```

Body:
The first option is to create a schedule to trigger a build:

gcloud scheduler jobs create http ${PROJECT_ID}-run-trigger \
    --schedule='0 12 * * *' \
    --uri=https://cloudbuild.googleapis.com/v1/projects/${PROJECT_ID}/triggers/${TRIGGER_ID}:run \
    --message-body='{\"branchName\": \"${BRANCH_NAME}\"}' \
    --oauth-service-account-email=${PROJECT_ID}@appspot.gserviceaccount.com \
    --oauth-token-scope=https://www.googleapis.com/auth/cloud-platform

Note that you can almost run this from within a cloud build. PROJECT_ID is the name of the project and BRANCH_NAME is the name of the branch (development, master, etc.). Both are available from within your cloud build pipeline. TRIGGER_ID can be fetched with the following command:

gcloud beta builds triggers list --format json

Additional to branchName, you can also specify other attributes in the message body, giving you more flexibility:

commitSha

dir

invertRegex

projectId

repoName

substitutions

tagName

The second option is to submit a cloudbuild on a schedule:

gcloud scheduler jobs create http ${PROJECT_ID}-run-build \
    --schedule='0 12 * * *' \
    --uri=https://cloudbuild.googleapis.com/v1/projects/${PROJECT_ID}/builds \
    --message-body-from-file=cloudbuild.json \
    --message-body="{\"branchName\": \"${BRANCH_NAME}\"} \
    --oauth-service-account-email=${PROJECT_ID}@appspot.gserviceaccount.com \
    --oauth-token-scope=https://www.googleapis.com/auth/cloud-platform

Your cloudbuild.json can look something like this:

{
    "timeout": "60s",
    "steps": [
        {
            "name": "gcr.io/cloud-builders/gcloud",
            "entrypoint": "bash",
            "args": [
                "-c",
                "echo "Hello"
            ]
        },
        {
            "name": "gcr.io/cloud-builders/gcloud",
            "entrypoint": "bash",
            "args": [
                "-c",
                "echo "World"
            ]
        }
    ],
    "substitutions": {
        "BRANCH_NAME": "$BRANCH_NAME"
    }
}


问:
Is there a way to determine if a Linux PID is paused or not?
I have a python script that is using the SIGSTOP and .SIGCONT commands with os.kill to pause or resume a process.  Is there a way to determine whether the related PID is in the paused or resumed state?</p>

答:
You can find information about a process from its /proc directory (/proc/<PID>). Specifically, you can find its run state with this python expression:

```<code>open(os.path.join('/proc', str(pid), 'stat')).readline().split()[2]=='T'
</code>```

EDIT: This next expression fixes a (presumably rare) bug with the original:

```<code>re.sub(r'\(.*\)', '()', open(os.path.join('/proc', str(pid), 'stat')).readline()).split()[2]=='T'
</code>```

Body:
You can find information about a process from its /proc directory (/proc/<PID>). Specifically, you can find its run state with this python expression:

open(os.path.join('/proc', str(pid), 'stat')).readline().split()[2]=='T'

EDIT: This next expression fixes a (presumably rare) bug with the original:

re.sub(r'\(.*\)', '()', open(os.path.join('/proc', str(pid), 'stat')).readline()).split()[2]=='T'


问:
Arrange values within a specific group
I'm trying to arrange values in decreasing order within a exact group in a nested dataframe. My input data looks like this. I've got two grouping variables (group1 and group2) and three values (i.e. id, value2, value3).

```<code>library(tidyverse)
set.seed(1234)

df <- tibble(group1 = c(rep(LETTERS[1:3], 4)),
             group2 = c(rep(0, 6), rep(2, 6)),
             value2 = rnorm(12, 20, sd = 10),
             value3 = rnorm(12, 20, sd = 50)) %>%
  group_by(group1) %>%
  mutate(id = c(1:4)) %>%
  ungroup()
</code>```

I decided to group them by group1 and group2 and then nest():

```<code>df_nested <- df %>%
  group_by(group1, group2) %>%
  nest()

# A tibble: 6 x 3
# Groups:   group1, group2 [6]
  group1 group2 data
  <chr>   <dbl> <list>
1 A           0 <tibble [2 x 3]>
2 B           0 <tibble [2 x 3]>
3 C           0 <tibble [2 x 3]>
4 A           2 <tibble [2 x 3]>
5 B           2 <tibble [2 x 3]>
6 C           2 <tibble [2 x 3]>
</code>```

Perfect. Now I need to sort only those data which group2 is equal to 2 by id. However I'm receiving a following error:

```<code>df_nested %>%
  mutate(data = map2_df(.x = data, .y = group2,
                     ~ifelse(.y == 2, arrange(-.x$id),
                             .x)))
</code>```

Error: Argument 1 must have names

答:
I would suggest creating an additional variable id_ which will be equal to the original id variable when group2 == 2 and NA otherwise. This way if we use it in sorting it'll make no effect when group2 != 2.

df %>%
  mutate(id_ = if_else(group2 == 2, id, NA_integer_)) %>%
  arrange(group1, group2, -id_)
#> # A tibble: 12 x 6
#>    group1 group2 value2 value3    id   id_
#>    <chr>   <dbl>  <dbl>  <dbl> <int> <int>
#>  1 A           0   17.6  50.2      1    NA
#>  2 A           0   33.8 -14.4      2    NA
#>  3 A           2   23.1  22.6      4     4
#>  4 A           2   13.7  50.2      3     3
#>  5 B           0   15.4  49.9      1    NA
#>  6 B           0   16.2  63.7      2    NA
#>  7 B           2   41.7  -2.90     4     4
#>  8 B           2   16.6  46.7      3     3
#>  9 C           0   19.9 -64.3      1    NA
#> 10 C           0   19.9  59.7      2    NA
#> 11 C           2   34.1  48.5      4     4
#> 12 C           2   32.3  23.1      3     3
```

Then if needed we can group and nest the result.

Title: Arrange values within a specific group

Body:
I'm trying to arrange values in decreasing order within a exact group in a nested dataframe. My input data looks like this. I've got two grouping variables (group1 and group2) and three values (i.e. id, value2, value3).

library(tidyverse)
set.seed(1234)

df <- tibble(group1 = c(rep(LETTERS[1:3], 4)),
             group2 = c(rep(0, 6), rep(2, 6)),
             value2 = rnorm(12, 20, sd = 10),
             value3 = rnorm(12, 20, sd = 50)) %>%
  group_by(group1) %>%
  mutate(id = c(1:4)) %>%
  ungroup()

I decided to group them by group1 and group2 and then nest():

df_nested <- df %>%
  group_by(group1, group2) %>%
  nest()

# A tibble: 6 x 3
# Groups:   group1, group2 [6]
  group1 group2 data
  <chr>   <dbl> <list>
1 A           0 <tibble [2 x 3]>
2 B           0 <tibble [2 x 3]>
3 C           0 <tibble [2 x 3]>
4 A           2 <tibble [2 x 3]>
5 B           2 <tibble [2 x 3]>
6 C           2 <tibble [2 x 3]>

Perfect. Now I need to sort only those data which group2 is equal to 2 by id. However I'm receiving a following error:

df_nested %>%
  mutate(data = map2_df(.x = data, .y = group2,
                     ~ifelse(.y == 2, arrange(-.x$id),
                             .x)))

Error: Argument 1 must have names

Body:
I would suggest creating an additional variable id_ which will be equal to the original id variable when group2 == 2 and NA otherwise. This way if we use it in sorting it'll make no effect when group2 != 2.

df %>%
  mutate(id_ = if_else(group2 == 2, id, NA_integer_)) %>%
  arrange(group1, group2, -id_)
#> # A tibble: 12 x 6
#>    group1 group2 value2 value3    id   id_
#>    <chr>   <dbl>  <dbl>  <dbl> <int> <int>
#>  1 A           0   17.6  50.2      1    NA
#>  2 A           0   33.8 -14.4      2    NA
#>  3 A           2   23.1  22.6      4     4
#>  4 A           2   13.7  50.2      3     3
#>  5 B           0   15.4  49.9      1    NA
#>  6 B           0   16.2  63.7      2    NA
#>  7 B           2   41.7  -2.90     4     4
#>  8 B           2   16.6  46.7      3     3
#>  9 C           0   19.9 -64.3      1    NA
#> 10 C           0   19.9  59.7      2    NA
#> 11 C           2   34.1  48.5      4     4
#> 12 C           2   32.3  23.1      3     3

Then if needed we can group and nest the result.


答:
Do I need to write distinct in the first query?

No, or at least not if the product-ingredient combination is unique, like here. It will be distinct, since the two ingredients are clearly distinct. You furthermore should not use .prefetch_related(..) here, unless you really want to render the Product with the related Ingredients. So it is sufficient to write:

```<code>Product.objects.filter(
    product__ingredients__ingredient__name='strawberry'
).filter(
    product__ingredients__ingredient__name='milk'
)</code>```

How to write the second query?

You can filter with an __in lookup [Django-doc]:

```<code>Product.objects.filter(
    <b>product__ingredients__ingredient__name__in=['strawberry', 'milk']</b>
)</code>```

Title: Filter intermediary ManyToMany django

Body:
Do I need to write distinct in the first query?

No, or at least not if the product-ingredient combination is unique, like here. It will be distinct, since the two ingredients are clearly distinct. You furthermore should not use .prefetch_related(..) here, unless you really want to render the Product with the related Ingredients. So it is sufficient to write:

Product.objects.filter(
    product__ingredients__ingredient__name='strawberry'
).filter(
    product__ingredients__ingredient__name='milk'
)

How to write the second query?

You can filter with an __in lookup [Django-doc]:

Product.objects.filter(
    product__ingredients__ingredient__name__in=['strawberry', 'milk']
)


问:
SQLite: Inner join on result set
In SQLite, is there way to do an inner join of some table on a result set?

Kind of like this hypothetical query:

```<code>SELECT el1,el2 FROM pairs
INNER JOIN (<some_query> AS result) ON el1 IN result AND el2 IN result;
</code>```

The redundant working query should be:

```<code>SELECT el1,el2 FROM pairs
WHERE el1 IN (<some_query>) AND el2 IN (<same_query>);
</code>```

Where <some_query> is:

```<code>SELECT el FROM set1 INNER JOIN set2 ON set1.el=set2.el;
</code>```

Obviously, the latter looks like it might be very expensive.

What would be the preferred query?

答:
The logic of some_query can be written more efficiently with INTERSECT:

```<code>SELECT el FROM set1
INTERSECT
SELECT el FROM set2
</code>```

and if you use a CTE for some_query then for your requirement you can do this:

```<code>WITH cte AS (
  SELECT el FROM set1
  INTERSECT
  SELECT el FROM set2
)
SELECT el1, el2
FROM pairs
WHERE el1 IN cte AND el2 IN cte
</code>```

Title: SQLite: Inner join on result set

Body:
In SQLite, is there way to do an inner join of some table on a result set?

Kind of like this hypothetical query:

SELECT el1,el2 FROM pairs
INNER JOIN (<some_query> AS result) ON el1 IN result AND el2 IN result;

The redundant working query should be:

SELECT el1,el2 FROM pairs
WHERE el1 IN (<some_query>) AND el2 IN (<same_query>);

Where <some_query> is:

SELECT el FROM set1 INNER JOIN set2 ON set1.el=set2.el;

Obviously, the latter looks like it might be very expensive.

What would be the preferred query?

Body:
The logic of some_query can be written more efficiently with INTERSECT:

SELECT el FROM set1
INTERSECT
SELECT el FROM set2

and if you use a CTE for some_query then for your requirement you can do this:

WITH cte AS (
  SELECT el FROM set1
  INTERSECT
  SELECT el FROM set2
)
SELECT el1, el2
FROM pairs
WHERE el1 IN cte AND el2 IN cte


问:
Angular7 and NgbModal: how to remove default auto focus
we just upgraded our application to angular 7 and we noticed that all ngBootstrap modals have now a default autofocus on the close button  like the following picture.

here is my code:

html modal code:

```<code><form [formGroup]="storeForm" novalidate>
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Modal Test</h4>
            <button type="button" class="close" aria-label="Close"
               (click)="activeModal.dismiss('Cross click')">
               <span aria-hidden="true">×</span>
            </button>
        </div>
        <div class="modal-body">
            <h4>Todo</h4>
        </div>
        <div class="modal-footer">
            <button role="button" type="submit" class="btn btn-primary"
               (click)="activeModal.close('Finish click')" prevent-double-
               submit>{{ 'store.add.finish' | translate }}</button>
       </div>
    </div>
</form>
</code>```

and how is the modal called thanks to my component.ts

```<code>    const modal = this._modalService.open(ModalComponent, { backdrop:
       'static', size: 'lg'});
    modal.result.then(
        (data) => {
           // some code
        },
        () => {
        }
    );
</code>```

My question is how can i remove this default autofocus that doesn't fit with our expected behaviour?

Thanks for the reading and please forgive the misspellings.

答:
Add style="outline: none;" to your close button

Example :

```<code><button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</code>```

Body:
we just upgraded our application to angular 7 and we noticed that all ngBootstrap modals have now a default autofocus on the close button  like the following picture.

here is my code:

html modal code:

<form [formGroup]="storeForm" novalidate>

Modal Test

            <button type="button" class="close" aria-label="Close"
               (click)="activeModal.dismiss('Cross click')">
               ×
            </button>

Todo

            <button role="button" type="submit" class="btn btn-primary"
               (click)="activeModal.close('Finish click')" prevent-double-
               submit>{{ 'store.add.finish' | translate }}</button>

</form>

and how is the modal called thanks to my component.ts

    const modal = this._modalService.open(ModalComponent, { backdrop:
       'static', size: 'lg'});
    modal.result.then(
        (data) => {
           // some code
        },
        () => {
        }
    );

My question is how can i remove this default autofocus that doesn't fit with our expected behaviour?

Thanks for the reading and please forgive the misspellings.

Body:
Add style="outline: none;" to your close button

Example :

<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">&times;</span>
</button>


问:
Sortying array by two criteria
I have array like this:

```<code>const array = [{
    id: 1,
    date: 591020824000,
    isImportant: false,
  },
  {
    id: 2,
    date: 591080224000,
    isImportant: false,
  },
  {
    id: 3,
    date: 591080424000,
    isImportant: true,
  },
  {
    id: 4,
    date: 591080225525,
    isImportant: false,
  },
  {
    id: 5,
    date: 591020225525,
    isImportant: true,
  },
];
</code>```

And I'm trying to sort this array so elements that are isImportant: true with the most recent date are displayed first and then elements that have isImportant:false with the most recent date

答:
```<code>array.sort(function(a,b){
    if(a.isImportant && !b.isImportant)
        return -1;
    if(!a.isImportant && b.isImportant)
        return 1;
    return b.date-a.date;
});
</code>```

I hope this will resolve your issue

Title: Sortying array by two criteria

Body:
I have array like this:

const array = [{
    id: 1,
    date: 591020824000,
    isImportant: false,
  },
  {
    id: 2,
    date: 591080224000,
    isImportant: false,
  },
  {
    id: 3,
    date: 591080424000,
    isImportant: true,
  },
  {
    id: 4,
    date: 591080225525,
    isImportant: false,
  },
  {
    id: 5,
    date: 591020225525,
    isImportant: true,
  },
];

And I'm trying to sort this array so elements that are isImportant: true with the most recent date are displayed first and then elements that have isImportant:false with the most recent date

Body:
array.sort(function(a,b){
    if(a.isImportant && !b.isImportant)
        return -1;
    if(!a.isImportant && b.isImportant)
        return 1;
    return b.date-a.date;
});

I hope this will resolve your issue


问:
ASP.Net core 3.0 (3.1) set PathBase for single page application
I have the following asp.net core spa application configured (react-redux template)

```<code>        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UsePathBase(new PathString("/foo"));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
</code>```

I’d like to set pathBase for application, but app.UsePathBase(new PathString("/foo")) just ignored. On 2.2 it perfectly worked. Automatically modified index.html and all static files were moved to relative path. But on 3.0 (3.1) static + generated files are placed on root.

Generated files on .Net Core 2.2

Generated files on .Net Core 3.0

Does anyone have any ideas for solving it? Or may be some examples of Startup.cs with working pathBase?

答:
Usually, app.UsePathBase(new PathString("/foo")); is used because the reverse proxy cuts off some prefix and causes ASP.NET Core app doesn't realize the virtual app path is start with /foo. In your scenario, if you don't have a reverse proxy that rewrite the prefix to empty string, you don't need app.UsePathBase(...).

Instead, if you your spa runs on a subpath, you could setup a middleware that branches the /foo.

Finally, you might want to add a property of homepage in your package.json so that it will generate the <base url="/foo/"/> when publishing. Or as an alternative, you could update the <base url=""> in ClientApp/public/index.html manually.

In short, add a "homepage": "/foo/" in your package.json

```
  "private": true,
  <b>"homepage": "/foo/",</b>
  "dependencies": {
      ...
   }
```

And setup a /foo branch to make SPA runs under that path:

string spaPath = "/foo";
app.Map(spaPath,appBuilder =>{
    appBuilder.UseSpa(spa =>
    {
        spa.Options.DefaultPage = spaPath+"/index.html";
        spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions{
            RequestPath = spaPath,
        };
        spa.Options.SourcePath = "ClientApp";
        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
});
```

Don't use app.UsePathBase(new PathString("/foo")) unless you understand you do want to override the path base for all routes.

Body:
I have the following asp.net core spa application configured (react-redux template)

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UsePathBase(new PathString("/foo"));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }

I’d like to set pathBase for application, but app.UsePathBase(new PathString("/foo")) just ignored. On 2.2 it perfectly worked. Automatically modified index.html and all static files were moved to relative path. But on 3.0 (3.1) static + generated files are placed on root.

Generated files on .Net Core 2.2

Generated files on .Net Core 3.0

Does anyone have any ideas for solving it? Or may be some examples of Startup.cs with working pathBase?

Body:
Usually, app.UsePathBase(new PathString("/foo")); is used because the reverse proxy cuts off some prefix and causes ASP.NET Core app doesn't realize the virtual app path is start with /foo. In your scenario, if you don't have a reverse proxy that rewrite the prefix to empty string, you don't need app.UsePathBase(...).

Instead, if you your spa runs on a subpath, you could setup a middleware that branches the /foo.

Finally, you might want to add a property of homepage in your package.json so that it will generate the <base url="/foo/"/> when publishing. Or as an alternative, you could update the <base url=""> in ClientApp/public/index.html manually.

In short, add a "homepage": "/foo/" in your package.json

  "private": true,
  "homepage": "/foo/",
  "dependencies": {
      ...
   }

And setup a /foo branch to make SPA runs under that path:

string spaPath = "/foo";
app.Map(spaPath,appBuilder =>{
    appBuilder.UseSpa(spa =>
    {
        spa.Options.DefaultPage = spaPath+"/index.html";
        spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions{
            RequestPath = spaPath,
        };
        spa.Options.SourcePath = "ClientApp";
        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
});

Don't use app.UsePathBase(new PathString("/foo")) unless you understand you do want to override the path base for all routes.


问:
C# OracleDependency OnChange firing multiple times
It is my understanding that the OracleDependency can be tied to monitor a query (not just a table). I make 2 command objects and 2 dependency objects but the query for both have different where clauses so they should be looking at 2 different subsets of this table.

I assign both of these dependency objects to the same callback. My expectations are that when I change something in the table that one of these dependency objects are watching that the OnChange event would fire for that one. I would then be able to do the following in the OnChange event to get the query that triggered teh change:

OracleDependency OraDep = (OracleDependency)sender;
string sql = (string)OraDep.RegisteredResources[0];

So I setup 2 queries against the same table with a different where clause value. Then I go into the DB and change one of them but to my surprise the OnChange even fires twice and the above code to get the query shows both queries.

Is there no way to have the dependency for a specific query and not the entire table? I thought I read somewhere you set it up for a specific query, where clause and all.

答:
Oracle change notification monitors the objects not queries. Any change on the table new record inserted, updated or deleted, new column added, renamed/dropped. Thats the reason why you are seeing notifications 2 times.

One way is to call the stored procedures instead of queries. Accept only 1 notification. Notification event e.info tells you what operation it is either insert/ update/ delete. So you can write an if condition to only respond to insert notifications and based on that you can call the appropriate sp or query.

Hope this helps.


问:
JavascriptException in Selenium WebDriver
I tried to execute java script in selenium webdriver. The script is stored in a string variable. And variable is passed to exexuteScript() method. While running the script I got javascriptexception. The code, I executed is given below,

```<code>String js="<html>\r\n" +
                "<head>\r\n" +
                "    <link rel=\"stylesheet\" href=\"https://js.arcgis.com/3.18/dijit/themes/tundra/tundra.css\">\r\n" +
                "    <link rel=\"stylesheet\" href=\"https://js.arcgis.com/3.18/esri/css/esri.css\"> \r\n" +
                "   <script src=\"https://js.arcgis.com/3.31/\"></script>\r\n" +
                "   <script>\r\n" +
                "   var map;\r\n" +
                "   var width = 123.26;\r\n" +
                "   var height = 126.5;\r\n" +
                "   require([\"esri/map\",\"esri/geometry/Point\", \"esri/SpatialReference\",\"esri/geometry/Extent\",\"esri/geometry/screenUtils\"],function(Map,Point,SpatialReference,Extent,screenUtils){\r\n" +
                "       map = new Map(\"mapDiv\",{\r\n" +
                "           basemap: \"streets\",\r\n" +
                "           center: [-95.249, 38.954],\r\n" +
                "           zoom: 5,\r\n" +
                "           slider: false\r\n" +
                "       });\r\n" +
                "       //alert(point);\r\n" +
                "       \r\n" +
                "       var mappoint=new Point(-118.15, 33.80, new SpatialReference({ wkid: 4326 }));\r\n" +
                "       console.log(mappoint);\r\n" +
                "       \r\n" +
                "       var extent = new esri.geometry.Extent({\r\n" +
                "           \"xmin\":-122.68,\"ymin\":45.53,\"xmax\":-122.45,\"ymax\":45.6,\r\n" +
                "           \"spatialReference\":{\"wkid\":4326}\r\n" +
                "       });\r\n" +
                "       console.log(extent);\r\n" +
                "       var sp = esri.geometry.toScreenPoint(extent,width,height,mappoint);\r\n" +
                "       console.log(sp);\r\n" +
                "   });\r\n" +
                "   </script>\r\n" +
                "   </head>\r\n" +
                "  <body>\r\n" +
                "    <div id=\"mapDiv\"></div>\r\n" +
                "    </div>\r\n" +
                "  </body>\r\n" +
                "</html>\r\n" +
                "\r\n" +
                "";
         JavascriptExecutor executor = (JavascriptExecutor)driver;
        executor.executeScript(js);
</code>```

The error message I got is given below,

```<code>Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: Unexpected token '<'
  (Session info: chrome=79.0.3945.130)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-6H32JSB', ip: '10.8.2.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 79.0.3945.130, chrome: {chromedriverVersion: 78.0.3904.105 (60e2d8774a81..., userDataDir: C:\Users\user\AppData\Local...}, goog:chromeOptions: {debuggerAddress: localhost:54082}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 7c8b20fbb56364eb89ed96357cca06c4
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:489)
    at esrimap.ClickOnanyLocation.main(ClickOnanyLocation.java:85)
</code>```

Please support me to solve this issue.

答:
In order to create a new page with javascript as you want you need create the page first (the DOM) and pass your variable:

```<code>String page = "window.open('').document.write(" + js + ")";
</code>```

And then :

```<code>executor.executeScript(page);
</code>```

Body:
I tried to execute java script in selenium webdriver. The script is stored in a string variable. And variable is passed to exexuteScript() method. While running the script I got javascriptexception. The code, I executed is given below,

String js="\r\n" +
                "\r\n" +
                "    <link rel=\"stylesheet\" href=\"https://js.arcgis.com/3.18/dijit/themes/tundra/tundra.css\">\r\n" +
                "    <link rel=\"stylesheet\" href=\"https://js.arcgis.com/3.18/esri/css/esri.css\"> \r\n" +
                "   \r\n" +
                "   \r\n" +
                "   \r\n" +
                "  \r\n" +
                "

\r\n" +
                "
\r\n" +
                "  \r\n" +
                "\r\n" +
                "\r\n" +
                "";
         JavascriptExecutor executor = (JavascriptExecutor)driver;
        executor.executeScript(js);

The error message I got is given below,

Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: Unexpected token '<'
  (Session info: chrome=79.0.3945.130)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-6H32JSB', ip: '10.8.2.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 79.0.3945.130, chrome: {chromedriverVersion: 78.0.3904.105 (60e2d8774a81..., userDataDir: C:\Users\user\AppData\Local...}, goog:chromeOptions: {debuggerAddress: localhost:54082}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 7c8b20fbb56364eb89ed96357cca06c4
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:489)
    at esrimap.ClickOnanyLocation.main(ClickOnanyLocation.java:85)

Please support me to solve this issue.

Body:
In order to create a new page with javascript as you want you need create the page first (the DOM) and pass your variable:

String page = "window.open('').document.write(" + js + ")";

And then :

executor.executeScript(page);