问:
In PyQt, is it possible to detach tabs from a QTabWidget?
Many professional applications (such as web browsers) give the user the ability to detach tabs from a tab bar.  Surprisingly, Qt4 does not provide this functionality.  Some might say that this functionality is provided by using tabified QDockWidgets.  However, it could also be argued that QDockWidgets implementation makes it look unprofessional and un-intuitive to users.</p>

答:
I found a partially working C++ example in this post on the Qt Centre forum.  It was incomplete and buggy.  However, I was able to use it as reference and a starting point to create my own DetachableTabWidget using PyQt.  Since I haven't been able to find any other fully functional examples of this in PyQt, I wanted to post this here.  Maybe it will be useful to someone.

I wouldn't call it perfect, so I am definitely open to any suggestions for improvement.

EDIT1

The previous iteration had some serious flaws that I did not discover until I tried to use it in a real-world application.  I used QDialog for the detached tabs which meant that they could not be minimized or maximized like a typical window.  I also had them parented by the tab host which meant that the detached tabs were always on top of the tab host.  The following is my new version that uses QMainWindow for the detached tabs.

EDIT2

As stated in Qt's documentation, QDrag.exec_() behaves differently between Windows and Linux.  This caused the iteration I posted for EDIT1 to loose the ability to move (reorder) tabs in Linux.  I made a small fix to this iteration so that it now works on both Windows and Linux.  I also updated the comments to reflect the swap from QDialog to QMainWindow.

EDIT3

I added a removeTabByName(name) function that will remove a tab by name, even if it is detached.

I added the ability to reattach a tab by dragging it back into the tab bar area.  If it is dropped on another tab, it will be inserted into that position.  If it is dropped beside the tab bar, it is appended as the last tab.  If all tabs are detached, then dropping the detached tab anywhere in the DetachableTabWidget will re-attach the tab.

```<code>from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal, pyqtSlot

##
# The DetachableTabWidget adds additional functionality to Qt's QTabWidget that allows it
# to detach and re-attach tabs.
#
# Additional Features:
#   Detach tabs by
#     dragging the tabs away from the tab bar
#     double clicking the tab
#   Re-attach tabs by
#     dragging the detached tab's window into the tab bar
#     closing the detached tab's window
#   Remove tab (attached or detached) by name
#
# Modified Features:
#   Re-ordering (moving) tabs by dragging was re-implemented
#
class DetachableTabWidget(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self, parent)

        self.tabBar = self.TabBar(self)
        self.tabBar.onDetachTabSignal.connect(self.detachTab)
        self.tabBar.onMoveTabSignal.connect(self.moveTab)
        self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)

        self.setTabBar(self.tabBar)

        # Used to keep a reference to detached tabs since their QMainWindow
        # does not have a parent
        self.detachedTabs = {}

        # Close all detached tabs if the application is closed explicitly
        QtGui.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable

    ##
    #  The default movable functionality of QTabWidget must remain disabled
    #  so as not to conflict with the added features
    def setMovable(self, movable):
        pass

    ##
    #  Move a tab from one position (index) to another
    #
    #  @param    fromIndex    the original index location of the tab
    #  @param    toIndex      the new index location of the tab
    @pyqtSlot(int, int)
    def moveTab(self, fromIndex, toIndex):
        widget = self.widget(fromIndex)
        icon = self.tabIcon(fromIndex)
        text = self.tabText(fromIndex)

        self.removeTab(fromIndex)
        self.insertTab(toIndex, widget, icon, text)
        self.setCurrentIndex(toIndex)

    ##
    #  Detach the tab by removing it's contents and placing them in
    #  a DetachedTab window
    #
    #  @param    index    the index location of the tab to be detached
    #  @param    point    the screen position for creating the new DetachedTab window
    @pyqtSlot(int, QtCore.QPoint)
    def detachTab(self, index, point):

        # Get the tab content
        name = self.tabText(index)
        icon = self.tabIcon(index)
        if icon.isNull():
            icon = self.window().windowIcon()
        contentWidget = self.widget(index)

        try:
            contentWidgetRect = contentWidget.frameGeometry()
        except AttributeError:
            return

        # Create a new detached tab window
        detachedTab = self.DetachedTab(name, contentWidget)
        detachedTab.setWindowModality(QtCore.Qt.NonModal)
        detachedTab.setWindowIcon(icon)
        detachedTab.setGeometry(contentWidgetRect)
        detachedTab.onCloseSignal.connect(self.attachTab)
        detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
        detachedTab.move(point)
        detachedTab.show()

        # Create a reference to maintain access to the detached tab
        self.detachedTabs[name] = detachedTab

    ##
    #  Re-attach the tab by removing the content from the DetachedTab window,
    #  closing it, and placing the content back into the DetachableTabWidget
    #
    #  @param    contentWidget    the content widget from the DetachedTab window
    #  @param    name             the name of the detached tab
    #  @param    icon             the window icon for the detached tab
    #  @param    insertAt         insert the re-attached tab at the given index
    def attachTab(self, contentWidget, name, icon, insertAt=None):

        # Make the content widget a child of this widget
        contentWidget.setParent(self)

        # Remove the reference
        del self.detachedTabs[name]

        # Create an image from the given icon (for comparison)
        if not icon.isNull():
            try:
                tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
                tabIconImage = tabIconPixmap.toImage()
            except IndexError:
                tabIconImage = None
        else:
            tabIconImage = None

        # Create an image of the main window icon (for comparison)
        if not icon.isNull():
            try:
                windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
                windowIconImage = windowIconPixmap.toImage()
            except IndexError:
                windowIconImage = None
        else:
            windowIconImage = None

        # Determine if the given image and the main window icon are the same.
        # If they are, then do not add the icon to the tab
        if tabIconImage == windowIconImage:
            if insertAt == None:
                index = self.addTab(contentWidget, name)
            else:
                index = self.insertTab(insertAt, contentWidget, name)
        else:
            if insertAt == None:
                index = self.addTab(contentWidget, icon, name)
            else:
                index = self.insertTab(insertAt, contentWidget, icon, name)

        # Make this tab the current tab
        if index > -1:
            self.setCurrentIndex(index)

    ##
    #  Remove the tab with the given name, even if it is detached
    #
    #  @param    name    the name of the tab to be removed
    def removeTabByName(self, name):

        # Remove the tab if it is attached
        attached = False
        for index in xrange(self.count()):
            if str(name) == str(self.tabText(index)):
                self.removeTab(index)
                attached = True
                break

        # If the tab is not attached, close it's window and
        # remove the reference to it
        if not attached:
            for key in self.detachedTabs:
                if str(name) == str(key):
                    self.detachedTabs[key].onCloseSignal.disconnect()
                    self.detachedTabs[key].close()
                    del self.detachedTabs[key]
                    break

    ##
    #  Handle dropping of a detached tab inside the DetachableTabWidget
    #
    #  @param    name     the name of the detached tab
    #  @param    index    the index of an existing tab (if the tab bar
    #                     determined that the drop occurred on an
    #                     existing tab)
    #  @param    dropPos  the mouse cursor position when the drop occurred
    @QtCore.pyqtSlot(QtCore.QString, int, QtCore.QPoint)
    def detachedTabDrop(self, name, index, dropPos):

        # If the drop occurred on an existing tab, insert the detached
        # tab at the existing tab's location
        if index > -1:

            # Create references to the detached tab's content and icon
            contentWidget = self.detachedTabs[name].contentWidget
            icon = self.detachedTabs[name].windowIcon()

            # Disconnect the detached tab's onCloseSignal so that it
            # does not try to re-attach automatically
            self.detachedTabs[name].onCloseSignal.disconnect()

            # Close the detached
            self.detachedTabs[name].close()

            # Re-attach the tab at the given index
            self.attachTab(contentWidget, name, icon, index)

        # If the drop did not occur on an existing tab, determine if the drop
        # occurred in the tab bar area (the area to the side of the QTabBar)
        else:

            # Find the drop position relative to the DetachableTabWidget
            tabDropPos = self.mapFromGlobal(dropPos)

            # If the drop position is inside the DetachableTabWidget...
            if self.rect().contains(tabDropPos):

                # If the drop position is inside the tab bar area (the
                # area to the side of the QTabBar) or there are not tabs
                # currently attached...
                if tabDropPos.y() < self.tabBar.height() or self.count() == 0:

                    # Close the detached tab and allow it to re-attach
                    # automatically
                    self.detachedTabs[name].close()

    ##
    #  Close all tabs that are currently detached.
    def closeDetachedTabs(self):
        listOfDetachedTabs = []

        for key in self.detachedTabs:
            listOfDetachedTabs.append(self.detachedTabs[key])

        for detachedTab in listOfDetachedTabs:
            detachedTab.close()

    ##
    #  When a tab is detached, the contents are placed into this QMainWindow.  The tab
    #  can be re-attached by closing the dialog or by dragging the window into the tab bar
    class DetachedTab(QtGui.QMainWindow):
        onCloseSignal = pyqtSignal(QtGui.QWidget, QtCore.QString, QtGui.QIcon)
        onDropSignal = pyqtSignal(QtCore.QString, QtCore.QPoint)

        def __init__(self, name, contentWidget):
            QtGui.QMainWindow.__init__(self, None)

            self.setObjectName(name)
            self.setWindowTitle(name)

            self.contentWidget = contentWidget
            self.setCentralWidget(self.contentWidget)
            self.contentWidget.show()

            self.windowDropFilter = self.WindowDropFilter()
            self.installEventFilter(self.windowDropFilter)
            self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)

        ##
        #  Handle a window drop event
        #
        #  @param    dropPos    the mouse cursor position of the drop
        @QtCore.pyqtSlot(QtCore.QPoint)
        def windowDropSlot(self, dropPos):
            self.onDropSignal.emit(self.objectName(), dropPos)

        ##
        #  If the window is closed, emit the onCloseSignal and give the
        #  content widget back to the DetachableTabWidget
        #
        #  @param    event    a close event
        def closeEvent(self, event):
            self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())

        ##
        #  An event filter class to detect a QMainWindow drop event
        class WindowDropFilter(QtCore.QObject):
            onDropSignal = pyqtSignal(QtCore.QPoint)

            def __init__(self):
                QtCore.QObject.__init__(self)
                self.lastEvent = None

            ##
            #  Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
            #  event that immediately follows a Move event
            #
            #  @param    obj    the object that generated the event
            #  @param    event  the current event
            def eventFilter(self, obj, event):

                # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
                if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:

                    # Determine the position of the mouse cursor and emit it with the
                    # onDropSignal
                    mouseCursor = QtGui.QCursor()
                    dropPos = mouseCursor.pos()
                    self.onDropSignal.emit(dropPos)
                    self.lastEvent = event.type()
                    return True

                else:
                    self.lastEvent = event.type()
                    return False

    ##
    #  The TabBar class re-implements some of the functionality of the QTabBar widget
    class TabBar(QtGui.QTabBar):
        onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
        onMoveTabSignal = pyqtSignal(int, int)
        detachedTabDropSignal = pyqtSignal(QtCore.QString, int, QtCore.QPoint)

        def __init__(self, parent=None):
            QtGui.QTabBar.__init__(self, parent)

            self.setAcceptDrops(True)
            self.setElideMode(QtCore.Qt.ElideRight)
            self.setSelectionBehaviorOnRemove(QtGui.QTabBar.SelectLeftTab)

            self.dragStartPos = QtCore.QPoint()
            self.dragDropedPos = QtCore.QPoint()
            self.mouseCursor = QtGui.QCursor()
            self.dragInitiated = False

        ##
        #  Send the onDetachTabSignal when a tab is double clicked
        #
        #  @param    event    a mouse double click event
        def mouseDoubleClickEvent(self, event):
            event.accept()
            self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())

        ##
        #  Set the starting position for a drag event when the mouse button is pressed
        #
        #  @param    event    a mouse press event
        def mousePressEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                self.dragStartPos = event.pos()

            self.dragDropedPos.setX(0)
            self.dragDropedPos.setY(0)

            self.dragInitiated = False

            QtGui.QTabBar.mousePressEvent(self, event)

        ##
        #  Determine if the current movement is a drag.  If it is, convert it into a QDrag.  If the
        #  drag ends inside the tab bar, emit an onMoveTabSignal.  If the drag ends outside the tab
        #  bar, emit an onDetachTabSignal.
        #
        #  @param    event    a mouse move event
        def mouseMoveEvent(self, event):

            # Determine if the current movement is detected as a drag
            if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtGui.QApplication.startDragDistance()):
                self.dragInitiated = True

            # If the current movement is a drag initiated by the left button
            if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):

                # Stop the move event
                finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
                QtGui.QTabBar.mouseMoveEvent(self, finishMoveEvent)

                # Convert the move event into a drag
                drag = QtGui.QDrag(self)
                mimeData = QtCore.QMimeData()
                mimeData.setData('action', 'application/tab-detach')
                drag.setMimeData(mimeData)

                # Create the appearance of dragging the tab content
                pixmap = QtGui.QPixmap.grabWindow(self.parentWidget().currentWidget().winId())
                targetPixmap = QtGui.QPixmap(pixmap.size())
                targetPixmap.fill(QtCore.Qt.transparent)
                painter = QtGui.QPainter(targetPixmap)
                painter.setOpacity(0.85)
                painter.drawPixmap(0, 0, pixmap)
                painter.end()
                drag.setPixmap(targetPixmap)

                # Initiate the drag
                dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)

                # For Linux:  Here, drag.exec_() will not return MoveAction on Linux.  So it
                #             must be set manually
                if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
                    dropAction = QtCore.Qt.MoveAction

                # If the drag completed outside of the tab bar, detach the tab and move
                # the content to the current cursor position
                if dropAction == QtCore.Qt.IgnoreAction:
                    event.accept()
                    self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())

                # Else if the drag completed inside the tab bar, move the selected tab to the new position
                elif dropAction == QtCore.Qt.MoveAction:
                    if not self.dragDropedPos.isNull():
                        event.accept()
                        self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
            else:
                QtGui.QTabBar.mouseMoveEvent(self, event)

        ##
        #  Determine if the drag has entered a tab position from another tab position
        #
        #  @param    event    a drag enter event
        def dragEnterEvent(self, event):
            mimeData = event.mimeData()
            formats = mimeData.formats()

            if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
                event.acceptProposedAction()

            QtGui.QTabBar.dragMoveEvent(self, event)

        ##
        #  Get the position of the end of the drag
        #
        #  @param    event    a drop event
        def dropEvent(self, event):
            self.dragDropedPos = event.pos()
            QtGui.QTabBar.dropEvent(self, event)

        ##
        #  Determine if the detached tab drop event occurred on an existing tab,
        #  then send the event to the DetachableTabWidget
        def detachedTabDrop(self, name, dropPos):

            tabDropPos = self.mapFromGlobal(dropPos)

            index = self.tabAt(tabDropPos)

            self.detachedTabDropSignal.emit(name, index, dropPos)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

    mainWindow = QtGui.QMainWindow()
    tabWidget = DetachableTabWidget()

    tab1 = QtGui.QLabel('Test Widget 1')
    tabWidget.addTab(tab1, 'Tab1')

    tab2 = QtGui.QLabel('Test Widget 2')
    tabWidget.addTab(tab2, 'Tab2')

    tab3 = QtGui.QLabel('Test Widget 3')
    tabWidget.addTab(tab3, 'Tab3')

    tabWidget.show()
    mainWindow.setCentralWidget(tabWidget)
    mainWindow.show()

    try:
        exitStatus = app.exec_()
        print 'Done...'
        sys.exit(exitStatus)
    except:
        pass
</code>```

Shortcomings

Unlike a web browser, closing a window (detached tab) will always reattach it to the tab bar.  In the future I would like to add an option to be able to close the window instead of reattaching.

I still need to add a method for getting a reference to a detached tab from outside of the widget.

Bugs

Any help with these would be greatly appreciated.

On very rare occasions, the drag event is not detected as a drag when removing a tab by dragging.  This is rare enough that I haven't spent much time on it.

Sometimes when a tab is detached, the QMainWindow that holds the detached tab will not generate the NonClientAreaMouseMove event.  The only way to make it start generating this event again is for the QMainWindow to loose and regain focus.  I'm not sure if this is a bug on my end or not.

Body:
I found a partially working C++ example in this post on the Qt Centre forum.  It was incomplete and buggy.  However, I was able to use it as reference and a starting point to create my own DetachableTabWidget using PyQt.  Since I haven't been able to find any other fully functional examples of this in PyQt, I wanted to post this here.  Maybe it will be useful to someone.

I wouldn't call it perfect, so I am definitely open to any suggestions for improvement.

EDIT1

The previous iteration had some serious flaws that I did not discover until I tried to use it in a real-world application.  I used QDialog for the detached tabs which meant that they could not be minimized or maximized like a typical window.  I also had them parented by the tab host which meant that the detached tabs were always on top of the tab host.  The following is my new version that uses QMainWindow for the detached tabs.

EDIT2

As stated in Qt's documentation, QDrag.exec_() behaves differently between Windows and Linux.  This caused the iteration I posted for EDIT1 to loose the ability to move (reorder) tabs in Linux.  I made a small fix to this iteration so that it now works on both Windows and Linux.  I also updated the comments to reflect the swap from QDialog to QMainWindow.

EDIT3

I added a removeTabByName(name) function that will remove a tab by name, even if it is detached.

I added the ability to reattach a tab by dragging it back into the tab bar area.  If it is dropped on another tab, it will be inserted into that position.  If it is dropped beside the tab bar, it is appended as the last tab.  If all tabs are detached, then dropping the detached tab anywhere in the DetachableTabWidget will re-attach the tab.

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal, pyqtSlot

##
# The DetachableTabWidget adds additional functionality to Qt's QTabWidget that allows it
# to detach and re-attach tabs.
#
# Additional Features:
#   Detach tabs by
#     dragging the tabs away from the tab bar
#     double clicking the tab
#   Re-attach tabs by
#     dragging the detached tab's window into the tab bar
#     closing the detached tab's window
#   Remove tab (attached or detached) by name
#
# Modified Features:
#   Re-ordering (moving) tabs by dragging was re-implemented
#
class DetachableTabWidget(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self, parent)

        self.tabBar = self.TabBar(self)
        self.tabBar.onDetachTabSignal.connect(self.detachTab)
        self.tabBar.onMoveTabSignal.connect(self.moveTab)
        self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)

        self.setTabBar(self.tabBar)

        # Used to keep a reference to detached tabs since their QMainWindow
        # does not have a parent
        self.detachedTabs = {}

        # Close all detached tabs if the application is closed explicitly
        QtGui.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable

    ##
    #  The default movable functionality of QTabWidget must remain disabled
    #  so as not to conflict with the added features
    def setMovable(self, movable):
        pass

    ##
    #  Move a tab from one position (index) to another
    #
    #  @param    fromIndex    the original index location of the tab
    #  @param    toIndex      the new index location of the tab
    @pyqtSlot(int, int)
    def moveTab(self, fromIndex, toIndex):
        widget = self.widget(fromIndex)
        icon = self.tabIcon(fromIndex)
        text = self.tabText(fromIndex)

        self.removeTab(fromIndex)
        self.insertTab(toIndex, widget, icon, text)
        self.setCurrentIndex(toIndex)

    ##
    #  Detach the tab by removing it's contents and placing them in
    #  a DetachedTab window
    #
    #  @param    index    the index location of the tab to be detached
    #  @param    point    the screen position for creating the new DetachedTab window
    @pyqtSlot(int, QtCore.QPoint)
    def detachTab(self, index, point):

        # Get the tab content
        name = self.tabText(index)
        icon = self.tabIcon(index)
        if icon.isNull():
            icon = self.window().windowIcon()
        contentWidget = self.widget(index)

        try:
            contentWidgetRect = contentWidget.frameGeometry()
        except AttributeError:
            return

        # Create a new detached tab window
        detachedTab = self.DetachedTab(name, contentWidget)
        detachedTab.setWindowModality(QtCore.Qt.NonModal)
        detachedTab.setWindowIcon(icon)
        detachedTab.setGeometry(contentWidgetRect)
        detachedTab.onCloseSignal.connect(self.attachTab)
        detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
        detachedTab.move(point)
        detachedTab.show()

        # Create a reference to maintain access to the detached tab
        self.detachedTabs[name] = detachedTab

    ##
    #  Re-attach the tab by removing the content from the DetachedTab window,
    #  closing it, and placing the content back into the DetachableTabWidget
    #
    #  @param    contentWidget    the content widget from the DetachedTab window
    #  @param    name             the name of the detached tab
    #  @param    icon             the window icon for the detached tab
    #  @param    insertAt         insert the re-attached tab at the given index
    def attachTab(self, contentWidget, name, icon, insertAt=None):

        # Make the content widget a child of this widget
        contentWidget.setParent(self)

        # Remove the reference
        del self.detachedTabs[name]

        # Create an image from the given icon (for comparison)
        if not icon.isNull():
            try:
                tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
                tabIconImage = tabIconPixmap.toImage()
            except IndexError:
                tabIconImage = None
        else:
            tabIconImage = None

        # Create an image of the main window icon (for comparison)
        if not icon.isNull():
            try:
                windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
                windowIconImage = windowIconPixmap.toImage()
            except IndexError:
                windowIconImage = None
        else:
            windowIconImage = None

        # Determine if the given image and the main window icon are the same.
        # If they are, then do not add the icon to the tab
        if tabIconImage == windowIconImage:
            if insertAt == None:
                index = self.addTab(contentWidget, name)
            else:
                index = self.insertTab(insertAt, contentWidget, name)
        else:
            if insertAt == None:
                index = self.addTab(contentWidget, icon, name)
            else:
                index = self.insertTab(insertAt, contentWidget, icon, name)

        # Make this tab the current tab
        if index > -1:
            self.setCurrentIndex(index)

    ##
    #  Remove the tab with the given name, even if it is detached
    #
    #  @param    name    the name of the tab to be removed
    def removeTabByName(self, name):

        # Remove the tab if it is attached
        attached = False
        for index in xrange(self.count()):
            if str(name) == str(self.tabText(index)):
                self.removeTab(index)
                attached = True
                break

        # If the tab is not attached, close it's window and
        # remove the reference to it
        if not attached:
            for key in self.detachedTabs:
                if str(name) == str(key):
                    self.detachedTabs[key].onCloseSignal.disconnect()
                    self.detachedTabs[key].close()
                    del self.detachedTabs[key]
                    break

    ##
    #  Handle dropping of a detached tab inside the DetachableTabWidget
    #
    #  @param    name     the name of the detached tab
    #  @param    index    the index of an existing tab (if the tab bar
    #                     determined that the drop occurred on an
    #                     existing tab)
    #  @param    dropPos  the mouse cursor position when the drop occurred
    @QtCore.pyqtSlot(QtCore.QString, int, QtCore.QPoint)
    def detachedTabDrop(self, name, index, dropPos):

        # If the drop occurred on an existing tab, insert the detached
        # tab at the existing tab's location
        if index > -1:

            # Create references to the detached tab's content and icon
            contentWidget = self.detachedTabs[name].contentWidget
            icon = self.detachedTabs[name].windowIcon()

            # Disconnect the detached tab's onCloseSignal so that it
            # does not try to re-attach automatically
            self.detachedTabs[name].onCloseSignal.disconnect()

            # Close the detached
            self.detachedTabs[name].close()

            # Re-attach the tab at the given index
            self.attachTab(contentWidget, name, icon, index)

        # If the drop did not occur on an existing tab, determine if the drop
        # occurred in the tab bar area (the area to the side of the QTabBar)
        else:

            # Find the drop position relative to the DetachableTabWidget
            tabDropPos = self.mapFromGlobal(dropPos)

            # If the drop position is inside the DetachableTabWidget...
            if self.rect().contains(tabDropPos):

                # If the drop position is inside the tab bar area (the
                # area to the side of the QTabBar) or there are not tabs
                # currently attached...
                if tabDropPos.y() < self.tabBar.height() or self.count() == 0:

                    # Close the detached tab and allow it to re-attach
                    # automatically
                    self.detachedTabs[name].close()

    ##
    #  Close all tabs that are currently detached.
    def closeDetachedTabs(self):
        listOfDetachedTabs = []

        for key in self.detachedTabs:
            listOfDetachedTabs.append(self.detachedTabs[key])

        for detachedTab in listOfDetachedTabs:
            detachedTab.close()

    ##
    #  When a tab is detached, the contents are placed into this QMainWindow.  The tab
    #  can be re-attached by closing the dialog or by dragging the window into the tab bar
    class DetachedTab(QtGui.QMainWindow):
        onCloseSignal = pyqtSignal(QtGui.QWidget, QtCore.QString, QtGui.QIcon)
        onDropSignal = pyqtSignal(QtCore.QString, QtCore.QPoint)

        def __init__(self, name, contentWidget):
            QtGui.QMainWindow.__init__(self, None)

            self.setObjectName(name)
            self.setWindowTitle(name)

            self.contentWidget = contentWidget
            self.setCentralWidget(self.contentWidget)
            self.contentWidget.show()

            self.windowDropFilter = self.WindowDropFilter()
            self.installEventFilter(self.windowDropFilter)
            self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)

        ##
        #  Handle a window drop event
        #
        #  @param    dropPos    the mouse cursor position of the drop
        @QtCore.pyqtSlot(QtCore.QPoint)
        def windowDropSlot(self, dropPos):
            self.onDropSignal.emit(self.objectName(), dropPos)

        ##
        #  If the window is closed, emit the onCloseSignal and give the
        #  content widget back to the DetachableTabWidget
        #
        #  @param    event    a close event
        def closeEvent(self, event):
            self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())

        ##
        #  An event filter class to detect a QMainWindow drop event
        class WindowDropFilter(QtCore.QObject):
            onDropSignal = pyqtSignal(QtCore.QPoint)

            def __init__(self):
                QtCore.QObject.__init__(self)
                self.lastEvent = None

            ##
            #  Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
            #  event that immediately follows a Move event
            #
            #  @param    obj    the object that generated the event
            #  @param    event  the current event
            def eventFilter(self, obj, event):

                # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
                if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:

                    # Determine the position of the mouse cursor and emit it with the
                    # onDropSignal
                    mouseCursor = QtGui.QCursor()
                    dropPos = mouseCursor.pos()
                    self.onDropSignal.emit(dropPos)
                    self.lastEvent = event.type()
                    return True

                else:
                    self.lastEvent = event.type()
                    return False

    ##
    #  The TabBar class re-implements some of the functionality of the QTabBar widget
    class TabBar(QtGui.QTabBar):
        onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
        onMoveTabSignal = pyqtSignal(int, int)
        detachedTabDropSignal = pyqtSignal(QtCore.QString, int, QtCore.QPoint)

        def __init__(self, parent=None):
            QtGui.QTabBar.__init__(self, parent)

            self.setAcceptDrops(True)
            self.setElideMode(QtCore.Qt.ElideRight)
            self.setSelectionBehaviorOnRemove(QtGui.QTabBar.SelectLeftTab)

            self.dragStartPos = QtCore.QPoint()
            self.dragDropedPos = QtCore.QPoint()
            self.mouseCursor = QtGui.QCursor()
            self.dragInitiated = False

        ##
        #  Send the onDetachTabSignal when a tab is double clicked
        #
        #  @param    event    a mouse double click event
        def mouseDoubleClickEvent(self, event):
            event.accept()
            self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())

        ##
        #  Set the starting position for a drag event when the mouse button is pressed
        #
        #  @param    event    a mouse press event
        def mousePressEvent(self, event):
            if event.button() == QtCore.Qt.LeftButton:
                self.dragStartPos = event.pos()

            self.dragDropedPos.setX(0)
            self.dragDropedPos.setY(0)

            self.dragInitiated = False

            QtGui.QTabBar.mousePressEvent(self, event)

        ##
        #  Determine if the current movement is a drag.  If it is, convert it into a QDrag.  If the
        #  drag ends inside the tab bar, emit an onMoveTabSignal.  If the drag ends outside the tab
        #  bar, emit an onDetachTabSignal.
        #
        #  @param    event    a mouse move event
        def mouseMoveEvent(self, event):

            # Determine if the current movement is detected as a drag
            if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtGui.QApplication.startDragDistance()):
                self.dragInitiated = True

            # If the current movement is a drag initiated by the left button
            if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):

                # Stop the move event
                finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
                QtGui.QTabBar.mouseMoveEvent(self, finishMoveEvent)

                # Convert the move event into a drag
                drag = QtGui.QDrag(self)
                mimeData = QtCore.QMimeData()
                mimeData.setData('action', 'application/tab-detach')
                drag.setMimeData(mimeData)

                # Create the appearance of dragging the tab content
                pixmap = QtGui.QPixmap.grabWindow(self.parentWidget().currentWidget().winId())
                targetPixmap = QtGui.QPixmap(pixmap.size())
                targetPixmap.fill(QtCore.Qt.transparent)
                painter = QtGui.QPainter(targetPixmap)
                painter.setOpacity(0.85)
                painter.drawPixmap(0, 0, pixmap)
                painter.end()
                drag.setPixmap(targetPixmap)

                # Initiate the drag
                dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)

                # For Linux:  Here, drag.exec_() will not return MoveAction on Linux.  So it
                #             must be set manually
                if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
                    dropAction = QtCore.Qt.MoveAction

                # If the drag completed outside of the tab bar, detach the tab and move
                # the content to the current cursor position
                if dropAction == QtCore.Qt.IgnoreAction:
                    event.accept()
                    self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())

                # Else if the drag completed inside the tab bar, move the selected tab to the new position
                elif dropAction == QtCore.Qt.MoveAction:
                    if not self.dragDropedPos.isNull():
                        event.accept()
                        self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
            else:
                QtGui.QTabBar.mouseMoveEvent(self, event)

        ##
        #  Determine if the drag has entered a tab position from another tab position
        #
        #  @param    event    a drag enter event
        def dragEnterEvent(self, event):
            mimeData = event.mimeData()
            formats = mimeData.formats()

            if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
                event.acceptProposedAction()

            QtGui.QTabBar.dragMoveEvent(self, event)

        ##
        #  Get the position of the end of the drag
        #
        #  @param    event    a drop event
        def dropEvent(self, event):
            self.dragDropedPos = event.pos()
            QtGui.QTabBar.dropEvent(self, event)

        ##
        #  Determine if the detached tab drop event occurred on an existing tab,
        #  then send the event to the DetachableTabWidget
        def detachedTabDrop(self, name, dropPos):

            tabDropPos = self.mapFromGlobal(dropPos)

            index = self.tabAt(tabDropPos)

            self.detachedTabDropSignal.emit(name, index, dropPos)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

    mainWindow = QtGui.QMainWindow()
    tabWidget = DetachableTabWidget()

    tab1 = QtGui.QLabel('Test Widget 1')
    tabWidget.addTab(tab1, 'Tab1')

    tab2 = QtGui.QLabel('Test Widget 2')
    tabWidget.addTab(tab2, 'Tab2')

    tab3 = QtGui.QLabel('Test Widget 3')
    tabWidget.addTab(tab3, 'Tab3')

    tabWidget.show()
    mainWindow.setCentralWidget(tabWidget)
    mainWindow.show()

    try:
        exitStatus = app.exec_()
        print 'Done...'
        sys.exit(exitStatus)
    except:
        pass

Shortcomings

Unlike a web browser, closing a window (detached tab) will always reattach it to the tab bar.  In the future I would like to add an option to be able to close the window instead of reattaching.

I still need to add a method for getting a reference to a detached tab from outside of the widget.

Bugs

Any help with these would be greatly appreciated.

On very rare occasions, the drag event is not detected as a drag when removing a tab by dragging.  This is rare enough that I haven't spent much time on it.

Sometimes when a tab is detached, the QMainWindow that holds the detached tab will not generate the NonClientAreaMouseMove event.  The only way to make it start generating this event again is for the QMainWindow to loose and regain focus.  I'm not sure if this is a bug on my end or not.


来源: stackexchange

问:
N-tier architecture with WCF and ASP.NET session state problem
I'm developing one of my personal projects and I found some problem.

It's an n-tier architecture:

Framework.

WCF Framework service.

ASP.NET control that connects to the WCF Framework services in the server-side.

ASP.NET client hosting that control.

WCF service is in ASP.NET compatibility mode.

What's the problem? Each request is in a different session. I found that because stored values for sessions are reseted in each request, as I stated before.

I've two questions then:

1) - Someway obvious but I want a confirmation - Does the fact of calling WCF Framework services in server-side mean that the session is for the server and not per client?

2) Is first question fact the reason of getting a new session after each request?

In the end, I'm about of disabling ASP.NET compatibility mode for that WCF Framework service and develop my own session state management, which isn't a hard task, but I'm not a friend of reinventing wheels.

Thank you in advance.

答:
WCF's default instantiation mode is Per-Call: the service call objects exist during each client call. When the client call ends WCF calls IDisposable.Dispose. Instantiation type can be set like:

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyWCFService : IMyWCFContract....
</code>```

There are two more instantiation types: Per-Session Services and Shareable Services.

You should use Per-Session for your project, so you can set your WCF service:

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyWCFService : IMyWCFContract....
</code>```

you can find more details on the MSDN
good luck

ContentLicense: CC BY-SA 2.5

Body:
WCF's default instantiation mode is Per-Call: the service call objects exist during each client call. When the client call ends WCF calls IDisposable.Dispose. Instantiation type can be set like:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyWCFService : IMyWCFContract....

There are two more instantiation types: Per-Session Services and Shareable Services.

You should use Per-Session for your project, so you can set your WCF service:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyWCFService : IMyWCFContract....

you can find more details on the MSDN
good luck


问:
AJAX TabContainer not showing up in IE
I'm using AJAX Control Toolkit v15.1, asp.net v4.5.1 vs.net 2012 VB code.  Everything is up-to-date.
I'm using the tabcontainer tool from the AJAX toolkit.  And when I run my web app in localhost mode, everything works fine in Chrome and IE.

I publish my code to my IIS web server & view it in Chrome.  Runs great!  Very happy!  But I must test it in IE so I fire up IE 11.
When IE 11 launches only the top part of my web app loads.  The bottom 75%, which houses the tabcontainer and 11 tabs, does not show up.

I've been reading about changing asp:Scriptmanager
 to ajaxToolkit:toolkitScriptManager (which doesn't work by the way.  It doesn't recognize that tag at all.  Immediately throws an error!  I think that may have been a fix 4+ years ago because that's when that fix was posted but does not apply today.)

Here is my code on what I think would be of value in troubleshooting:
(in my .aspx file)

```<code><%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1"  %>
</code>```

The beginning of my tabcontainer code:

```<code>        <cc1:TabContainer ID="tabContainer" runat="server" Width="1723px" Height="568px" AutoPostBack="true" ActiveTabIndex="7">
            <cc1:TabPanel ID="BackupSchedule" runat="server" >
                <HeaderTemplate>
                    <asp:Label ID="Label3" runat="server" Text="Backup Job Schedule" />
                </HeaderTemplate>
</code>```

I'd rather not force people to use Chrome.  That's the easy way out.  I'd rather fix this and not have to worry about it.

答:
I am aware that this is an old thread. I was having the same issues and found that going into IE11 and amending the compatibility View Setting adding the current website ticking both the  Display Intranet Site in Compatibility View and Use Microsoft compatibility list. Closing the setting then reopening and un-ticking then removing the website from the list will bring up the tabs in the same way Chrome and FF does.

Hope this helps?

ContentLicense: CC BY-SA 3.0

Title: AJAX TabContainer not showing up in IE

Body:
I'm using AJAX Control Toolkit v15.1, asp.net v4.5.1 vs.net 2012 VB code.  Everything is up-to-date.
I'm using the tabcontainer tool from the AJAX toolkit.  And when I run my web app in localhost mode, everything works fine in Chrome and IE.

I publish my code to my IIS web server & view it in Chrome.  Runs great!  Very happy!  But I must test it in IE so I fire up IE 11.
When IE 11 launches only the top part of my web app loads.  The bottom 75%, which houses the tabcontainer and 11 tabs, does not show up.

I've been reading about changing asp:Scriptmanager
 to ajaxToolkit:toolkitScriptManager (which doesn't work by the way.  It doesn't recognize that tag at all.  Immediately throws an error!  I think that may have been a fix 4+ years ago because that's when that fix was posted but does not apply today.)

Here is my code on what I think would be of value in troubleshooting:
(in my .aspx file)

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1"  %>

The beginning of my tabcontainer code:

        <cc1:TabContainer ID="tabContainer" runat="server" Width="1723px" Height="568px" AutoPostBack="true" ActiveTabIndex="7">
            <cc1:TabPanel ID="BackupSchedule" runat="server" >
                <HeaderTemplate>
                    <asp:Label ID="Label3" runat="server" Text="Backup Job Schedule" />
                </HeaderTemplate>

I'd rather not force people to use Chrome.  That's the easy way out.  I'd rather fix this and not have to worry about it.


问:
Nesting a http request inside list of promises
I have a service function that returns a list of promises:

```<code>getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

, which I'm calling inside my controller:

```<code>validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}
</code>```

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

答:
If I understood yours needs you should first get the charts response and then use that response to call the other webservices, so something like this should work:</p>

```<code>validateUser() {
    this.getData({})
        .then(function (response) {
            // response containing 'userInfo' and 'userTopArtists'
            console.log(arguments);
        });
}

getData(user) {
    const me = this;
    return me.$http.get('https://jsonplaceholder.typicode.com/users')
        .then(function (charts) {
            return me.$q.all({
                // use charts as param for other calls...
                userInfo: me.$http.get('https://jsonplaceholder.typicode.com/users'),
                userTopArtists: me.$http.get('https://jsonplaceholder.typicode.com/users')
            });
        })
        .catch(err => {
            me.$q.reject('Error' + err.status);
        });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a service function that returns a list of promises:

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

, which I'm calling inside my controller:

validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

Body:
If I understood yours needs you should first get the charts response and then use that response to call the other webservices, so something like this should work:

validateUser() {
    this.getData({})
        .then(function (response) {
            // response containing 'userInfo' and 'userTopArtists'
            console.log(arguments);
        });
}

getData(user) {
    const me = this;
    return me.$http.get('https://jsonplaceholder.typicode.com/users')
        .then(function (charts) {
            return me.$q.all({
                // use charts as param for other calls...
                userInfo: me.$http.get('https://jsonplaceholder.typicode.com/users'),
                userTopArtists: me.$http.get('https://jsonplaceholder.typicode.com/users')
            });
        })
        .catch(err => {
            me.$q.reject('Error' + err.status);
        });
}


问:
Chrome extension stops working after a while. Response is undefined
I have this strange bug with a chrome extension, that is supposed to communicate between content script and background page. It seems to work for a while, but suddenly it stops working. The only way to get it to work again is to uninstall the extension and reinstall it. This happens to both the version on the chrome store, and my local developer version. (Reloading the developer version does not fix the issue.)

The relevant part is:

```<code>chrome.pageAction.onClicked.addListener(function (tab) {
    chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
        //response is undefined at this point
    });
});
</code>```

I see from inspecting the page that the content script is indeed injected into the relevant page, but the code inside the listener never run:

```<code>chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  //never runs this code
});
</code>```

You can find the installed version here: https://chrome.google.com/webstore/detail/hi-res-cover-art-grabber/oiagpaldkopdbolnebgjlmihmejjkaji
And the full sourcecode here:
https://github.com/MrMamen/CoverGrabber/tree/master/chrome

答:
All of your JavaScript in your background.js is in a chrome.runtime.onInstalled.addListener event which only gets called on install and on updates, so it isn't called when you reopen your browser.

You'll want to make sure to register your events outside of this or else your extension will only register the events when you uninstall and reinstall your extension as you mentioned.

Body:
I have this strange bug with a chrome extension, that is supposed to communicate between content script and background page. It seems to work for a while, but suddenly it stops working. The only way to get it to work again is to uninstall the extension and reinstall it. This happens to both the version on the chrome store, and my local developer version. (Reloading the developer version does not fix the issue.)

The relevant part is:

chrome.pageAction.onClicked.addListener(function (tab) {
    chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
        //response is undefined at this point
    });
});

I see from inspecting the page that the content script is indeed injected into the relevant page, but the code inside the listener never run:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  //never runs this code
});

You can find the installed version here: https://chrome.google.com/webstore/detail/hi-res-cover-art-grabber/oiagpaldkopdbolnebgjlmihmejjkaji
And the full sourcecode here:
https://github.com/MrMamen/CoverGrabber/tree/master/chrome


问:
Subprocedure call in VHDL
I have two nested procedures, where the "main" procedure
makes use of "subproc" to accumulates a result in variables
t0 and t1, which is then returned at the end. This should all
be computed in one clock cycle, and the circuit more or less
just consists of simple logic gates (xor, or, and). When I try
to describe the circuit as below I get the following error:

```<code>Acutal (variable t0) for formal "a" is not a signal
</code>```

That makes sense as the subprocure requires signals as input,
but I wanna pass it a variable during the main procedure. Is
there a simple way to circumvent this problem with casting for
example?

Thanks

```<code>procedure subproc
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal c : in  std_logic_vector(31 downto 0);
  signal d : in  std_logic_vector(31 downto 0);
  signal e : out std_logic_vector(31 downto 0);
  signal f : out std_logic_vector(31 downto 0)
)
is
  variable x : std_logic_vector(31 downto 0);
  variable y : std_logic_vector(31 downto 0);
begin

  x := (others => '0');
  y := (others => '0');

  for i in 0 to 31 loop
      x(i) := (a(i) xor b(i)) and (c(i) xor d(i));
      y(i) := (a(i) xor b(i)) or ((d(i) xor c(i)) xor b(i));
  end loop;

  e <= x(31 downto 0);
  f <= y(31 downto 0);

end;

procedure main
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal r : out std_logic_vector(31 downto 0)
)
is
  variable res : std_logic_vector(31 downto 0);
  variable t0, t1 : std_logic_vector(31 downto 0);
  constant c : std_logic_vector(31 downto 0) := X"fedcba90";
  constant d : std_logic_vector(31 downto 0) := X"7654321f";
begin

  t0 := (others => '0');
  t1 := (others => '0');

  for i in 0 to 31 loop
    if ( (c(i) = '0') && (d(i) = '1') ) then
       subproc( t0, t1,
                a, b, t0, t1 );
    end if;
  end loop;

  r <= t0;
end;
</code>```

答:
First off, your "if" clause is written in C-style. You want to say:

```<code>if (c(i) = '0') and (d(i) = '1') then
</code>```

But the problem really is that you describe the procedure as taking SIGNALs as arguments. If you want the results to be assigned to variables, you need to declare a different procedure signature:

```<code>procedure subproc (
signal a : in  std_logic_vector(31 downto 0);
signal b : in  std_logic_vector(31 downto 0);
signal c : in  std_logic_vector(31 downto 0);
signal d : in  std_logic_vector(31 downto 0);
variable e : out std_logic_vector(31 downto 0);
variable f : out std_logic_vector(31 downto 0))
</code>```

But then, you also need to change all assignments to e and f, so that they are variable assignments:

```<code>e := x(31 downto 0);
</code>```

Title: Subprocedure call in VHDL

Body:
I have two nested procedures, where the "main" procedure
makes use of "subproc" to accumulates a result in variables
t0 and t1, which is then returned at the end. This should all
be computed in one clock cycle, and the circuit more or less
just consists of simple logic gates (xor, or, and). When I try
to describe the circuit as below I get the following error:

Acutal (variable t0) for formal "a" is not a signal

That makes sense as the subprocure requires signals as input,
but I wanna pass it a variable during the main procedure. Is
there a simple way to circumvent this problem with casting for
example?

Thanks

procedure subproc
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal c : in  std_logic_vector(31 downto 0);
  signal d : in  std_logic_vector(31 downto 0);
  signal e : out std_logic_vector(31 downto 0);
  signal f : out std_logic_vector(31 downto 0)
)
is
  variable x : std_logic_vector(31 downto 0);
  variable y : std_logic_vector(31 downto 0);
begin

  x := (others => '0');
  y := (others => '0');

  for i in 0 to 31 loop
      x(i) := (a(i) xor b(i)) and (c(i) xor d(i));
      y(i) := (a(i) xor b(i)) or ((d(i) xor c(i)) xor b(i));
  end loop;

  e <= x(31 downto 0);
  f <= y(31 downto 0);

end;

procedure main
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal r : out std_logic_vector(31 downto 0)
)
is
  variable res : std_logic_vector(31 downto 0);
  variable t0, t1 : std_logic_vector(31 downto 0);
  constant c : std_logic_vector(31 downto 0) := X"fedcba90";
  constant d : std_logic_vector(31 downto 0) := X"7654321f";
begin

  t0 := (others => '0');
  t1 := (others => '0');

  for i in 0 to 31 loop
    if ( (c(i) = '0') && (d(i) = '1') ) then
       subproc( t0, t1,
                a, b, t0, t1 );
    end if;
  end loop;

  r <= t0;
end;

Body:
First off, your "if" clause is written in C-style. You want to say:

if (c(i) = '0') and (d(i) = '1') then

But the problem really is that you describe the procedure as taking SIGNALs as arguments. If you want the results to be assigned to variables, you need to declare a different procedure signature:

procedure subproc (
signal a : in  std_logic_vector(31 downto 0);
signal b : in  std_logic_vector(31 downto 0);
signal c : in  std_logic_vector(31 downto 0);
signal d : in  std_logic_vector(31 downto 0);
variable e : out std_logic_vector(31 downto 0);
variable f : out std_logic_vector(31 downto 0))

But then, you also need to change all assignments to e and f, so that they are variable assignments:

e := x(31 downto 0);


问:
Creating navigation bar with categories in magento
I am creating  a Magento shop , right now shop have no navigation bar. I want to add a navigation bar on the top of the page using the categories hierarchy I created. Or just tell me how to create a navigation manually or add it through some widget. Please.</p>

答:
If your using Luma Theme (the default magento2 theme), the top navigation should automatically appear after you create your categories. You can check the following guide: http://docs.magento.com/m2/ce/user_guide/catalog/navigation-top.html

If you want to create custom navigation you can check this page:
http://icecubedigital.com/blog/how-to-create-a-cms-page-in-magento-2-and-add-its-link-to-top-navigation-menu/


问:
Datepicker doesn't work after ajax reload page
I have a problem with jquery Datapicker, i read here a lot of solution and test but anythings is work for me.
I explain my situation, i have a main page call index with this page a select a first container, in this container there are more element; When you select a item the index page call a another page for visualize the result in table form and you can select a filter for see only some data. I use datapicker for select the day.
When i select one item for the first time datapicker work but when i select another item datapicker stop working and trow this:

```<code>Uncaught TypeError: Cannot read property 'initialized' of undefined
    at HTMLDocument.eval (eval at <anonymous> (jquery-1.12.4.js:349), <anonymous>:20:21)
    at fire (jquery-1.12.4.js:3232)
    at Object.add [as done] (jquery-1.12.4.js:3291)
    at jQuery.fn.init.jQuery.fn.ready (jquery-1.12.4.js:3542)
    at eval (eval at <anonymous> (jquery-1.12.4.js:349), <anonymous>:14:14)
    at eval (<anonymous>)
    at jquery-1.12.4.js:349
    at Function.globalEval (jquery-1.12.4.js:350)
    at domManip (jquery-1.12.4.js:6089)
    at jQuery.fn.init.append (jquery-1.12.4.js:6269)
</code>```

This is how i call the datapicker:

```<code>$( ".datepickerINF" ).datepicker({ dateFormat: 'yy-mm-dd' });
$( ".datepickerSUP" ).datepicker({ dateFormat: 'yy-mm-dd' });
</code>```

I try to destroy this picker in the beginning then recreate them but doesn't work!
Can someone help me? Thanks.
In the first image datapicker work then, when i select another item doesn't work anymore!

EDIT:
Here the code of the main page:

```<code><?php
    if(isset($_POST['choice'])){

        $bottone=$_POST['choice'];

        $query = mysql_query("SHOW TABLES;");    //This is the query for take the DB table
        if($query ==FALSE) {
            die();
        }
        if(mysql_num_rows($query)){

            $select= '<p class="selectTable">Select the Table<br/><select name="select" id="test" class="selectionTable">';  //Create the menu with the table of the DB.
            $select.= "<option>------</option>";
            while($rs=mysql_fetch_array($query)){
                $name=$rs[0];
                $nameTable="";
                $element=explode('_',$name);
                //echo $bottone;
                //print_r($element);
                if($element[0]==$bottone){
                        unset($element[0]);
                        $nameTable=$nameTable." ".$element[1];
                        $i=2;
                        while($i<=(count($element))){
                            $nameTable=$nameTable."_".$element[$i];
                            $i++;
                        }
                        $select.='<option value="'.$name.'">'.$nameTable.'</option>';
                        $nameTable="";
                }
              }
        }

    $select.='</select></p>';
    echo $select;
    }
    ?>
</div>
<br/><br/>
<div class="val" id="val" align="center"></div>
 <script>
  $(function() { /* Prepare the script */

  $("#test").change(function(){ /* This event start when change the voice of the select */
    var tabella = $(this).val(); /* Take the string value from the table */
    if((tabella.localeCompare("------"))==0){
        alert("This is a default element, please select a table");
    }else{
        var dataString = "tabella="+tabella; /* save the result in a variable  */

        $.ajax({ /* Call ajax */
            type: "POST", /* How send the value */
            url: "value.php", /* This is the page where i send the value*/
            data: dataString, /* This is the value */
            success: function(result){ /* Take the data result */
                $("#val").html(result); /* Write the data in the div. */
                $("#val").show();
            }
            });
        }

    });
  });
</script>
</code>```

and here the code of the other page (the datapicker part):

```<code> <?php
    $filter="<div class='selector' id='selector'><p>Date: <input type='text' class='datepickerINF'>";
            //echo $filter;
            /*$filter= "<div class='selector' id='selector'>Filter start day: year <input id='dateYearStart' style='width:40px'/>";
            $filter.= " month (01-12) <input id='dateMonthStart' style='width:40px'/> day (01-31) <input id='dateDayStart' style='width:40px'/></br>";*/
            $filter.= "Time: <select id='hourLow'>";
            $filter.= "<option selected='selected'>------</option>";
            for($i=0;$i<24;$i++) {
                if($i<10) {$filter.= "<option value=0".$i.":00:00>"."0".$i.":00:00</option>";}
                else {$filter.= "<option value=".$i.":00:00>".$i.":00:00</option>";}
            }
            $filter.= "</select></p>";/*
            $filter.= "Filter End day: year <input id='dateYearEnd' style='width:40px'/>";
            $filter.= " month (01-12) <input id='dateMonthEnd' style='width:40px'/> day (01-31) <input id='dateDayEnd' style='width:40px'/></br>";*/
            $filter.="<p>Date: <input type='text' class='datepickerSUP'>";
            $filter.= "Time: <select id='hourHight'>";
            $filter.= "<option selected='selected'>------</option>";
            for($i=0;$i<24;$i++) {
                if($i<10) {$filter.= "<option value=0".$i.":00:00>"."0".$i.":00:00</option>";}
                else {$filter.= "<option value=".$i.":00:00>".$i.":00:00</option>";}
            }
            $filter.= "</select><br/></p>
                If you leave the default value for the hour (default: '------')<br/> you will take all the day (from 00:00:00 to 23:59:59).
                </br>";

            $filter.="<button id='filterSend'>Filter Results</button></div>";

            echo $filter;
            $exCSV="<div id='ex' class='ex'><button id='exportCSV' >Export CSV</button><br/></div>";
            echo $exCSV;
        }

    ?>
 $(document).ready(function() {

    /* Initialise the date picker. */
    applyDatepicker(".datepickerINF");
    applyDatepicker(".datepickerSUP");
    ...

    function applyDatepicker(elem) {
        $( elem ).datepicker({ dateFormat: 'yy-mm-dd' });

    }
</script>
</code>```

When the main page load the second of course datepicker work but when i change table and reload the page it compare the error.

答:
First thing you need to understand that ajax does not reload a page. Ajax just do the work and return to the same page.
As you didnt put the code of ajax calling, the problem is not clear.
One thing to try is call datepicker again after ajax call. But that is a bad solution.</p>

Body:
I have a problem with jquery Datapicker, i read here a lot of solution and test but anythings is work for me.
I explain my situation, i have a main page call index with this page a select a first container, in this container there are more element; When you select a item the index page call a another page for visualize the result in table form and you can select a filter for see only some data. I use datapicker for select the day.
When i select one item for the first time datapicker work but when i select another item datapicker stop working and trow this:

Uncaught TypeError: Cannot read property 'initialized' of undefined
    at HTMLDocument.eval (eval at <anonymous> (jquery-1.12.4.js:349), <anonymous>:20:21)
    at fire (jquery-1.12.4.js:3232)
    at Object.add [as done] (jquery-1.12.4.js:3291)
    at jQuery.fn.init.jQuery.fn.ready (jquery-1.12.4.js:3542)
    at eval (eval at <anonymous> (jquery-1.12.4.js:349), <anonymous>:14:14)
    at eval (<anonymous>)
    at jquery-1.12.4.js:349
    at Function.globalEval (jquery-1.12.4.js:350)
    at domManip (jquery-1.12.4.js:6089)
    at jQuery.fn.init.append (jquery-1.12.4.js:6269)

This is how i call the datapicker:

$( ".datepickerINF" ).datepicker({ dateFormat: 'yy-mm-dd' });
$( ".datepickerSUP" ).datepicker({ dateFormat: 'yy-mm-dd' });

I try to destroy this picker in the beginning then recreate them but doesn't work!
Can someone help me? Thanks.
In the first image datapicker work then, when i select another item doesn't work anymore!

EDIT:
Here the code of the main page:

<?php
    if(isset($_POST['choice'])){

        $bottone=$_POST['choice'];

        $query = mysql_query("SHOW TABLES;");    //This is the query for take the DB table
        if($query ==FALSE) {
            die();
        }
        if(mysql_num_rows($query)){

            $select= '
Select the Table
<select name="select" id="test" class="selectionTable">';  //Create the menu with the table of the DB.
            $select.= "<option>------</option>";
            while($rs=mysql_fetch_array($query)){
                $name=$rs[0];
                $nameTable="";
                $element=explode('_',$name);
                //echo $bottone;
                //print_r($element);
                if($element[0]==$bottone){
                        unset($element[0]);
                        $nameTable=$nameTable." ".$element[1];
                        $i=2;
                        while($i<=(count($element))){
                            $nameTable=$nameTable."_".$element[$i];
                            $i++;
                        }
                        $select.='<option value="'.$name.'">'.$nameTable.'</option>';
                        $nameTable="";
                }
              }
        }

    $select.='</select>
';
    echo $select;
    }
    ?>

and here the code of the other page (the datapicker part):

 <?php
    $filter="

Date: <input type='text' class='datepickerINF'>";
            //echo $filter;
            /*$filter= "
Filter start day: year <input id='dateYearStart' style='width:40px'/>";
            $filter.= " month (01-12) <input id='dateMonthStart' style='width:40px'/> day (01-31) <input id='dateDayStart' style='width:40px'/>
";*/
            $filter.= "Time: <select id='hourLow'>";
            $filter.= "<option selected='selected'>------</option>";
            for($i=0;$i<24;$i++) {
                if($i<10) {$filter.= "<option value=0".$i.":00:00>"."0".$i.":00:00</option>";}
                else {$filter.= "<option value=".$i.":00:00>".$i.":00:00</option>";}
            }
            $filter.= "</select>
";/*
            $filter.= "Filter End day: year <input id='dateYearEnd' style='width:40px'/>";
            $filter.= " month (01-12) <input id='dateMonthEnd' style='width:40px'/> day (01-31) <input id='dateDayEnd' style='width:40px'/>
";*/
            $filter.="
Date: <input type='text' class='datepickerSUP'>";
            $filter.= "Time: <select id='hourHight'>";
            $filter.= "<option selected='selected'>------</option>";
            for($i=0;$i<24;$i++) {
                if($i<10) {$filter.= "<option value=0".$i.":00:00>"."0".$i.":00:00</option>";}
                else {$filter.= "<option value=".$i.":00:00>".$i.":00:00</option>";}
            }
            $filter.= "</select>

                If you leave the default value for the hour (default: '------')
 you will take all the day (from 00:00:00 to 23:59:59).

";

            $filter.="<button id='filterSend'>Filter Results</button>
";

            echo $filter;
            $exCSV="
<button id='exportCSV' >Export CSV</button>

";
            echo $exCSV;
        }

    ?>
 $(document).ready(function() {

    /* Initialise the date picker. */
    applyDatepicker(".datepickerINF");
    applyDatepicker(".datepickerSUP");
    ...

    function applyDatepicker(elem) {
        $( elem ).datepicker({ dateFormat: 'yy-mm-dd' });

    }
</script>

When the main page load the second of course datepicker work but when i change table and reload the page it compare the error.


问:
How to perform square root without using math module?
I want to find the square root of a number without using the math module,as i need to call the function some 20k times and dont want to slow down the execution by linking to the math module each time the function is called

Is there any faster and easier way for finding square root?

答:
Python code snippet for computing square. It first makes an initial guess, and if the guess is not good enough it iterates until we have a good guess</p>

```<code>def gen_square_root_v1(number, epsilon):

   #boundary condition check

   if number == '1':
      return 1

   elif number <= 0:
      print('this computes square root for positive numbers only' )

   else:
      pass

   prev_estimate = number/2

   while True:

       #each itearation, calculate a new estimate
       new_estimate = (prev_estimate + number/prev_estimate)/2

       #Alternatively can use if abs(new_estimate - prev_estimate) < epsilon:

       #check the difference between  square of new_estimate and number
       if abs(new_estimate * new_estimate - number) < epsilon:
         return prev_estimate

     #if guess is not good enough, use it to make the next guess
     prev_estimate = new_estimate

#call the function
print(gen_square_root_v1(16,1e-5))
</code>```

Body:
Python code snippet for computing square. It first makes an initial guess, and if the guess is not good enough it iterates until we have a good guess

def gen_square_root_v1(number, epsilon):

   #boundary condition check

   if number == '1':
      return 1

   elif number <= 0:
      print('this computes square root for positive numbers only' )

   else:
      pass

   prev_estimate = number/2

   while True:

       #each itearation, calculate a new estimate
       new_estimate = (prev_estimate + number/prev_estimate)/2

       #Alternatively can use if abs(new_estimate - prev_estimate) < epsilon:

       #check the difference between  square of new_estimate and number
       if abs(new_estimate * new_estimate - number) < epsilon:
         return prev_estimate

     #if guess is not good enough, use it to make the next guess
     prev_estimate = new_estimate

#call the function
print(gen_square_root_v1(16,1e-5))


问:
header not aligning with columns when scrollable enabled JSF Primefaces 6.0
I am developing web using PrimeFaces 6.0 components. On

 component when we set scrollable="true" option, columns headers alignment goes wrong.

Following is my code snippet:

```<code><p:fieldset legend="Machine Test Match" id="panel233" toggleable="true"  toggleSpeed="500"  >
            <!--<p:panel id="panel233" header=" Machine Test Match" style="height:325px;border: none">-->
            <p:dataTable id="testmatchtable" var="testMatchvalues"   value="#{manufactureBean.listTestMatchata}" filteredValue="#{manufactureBean.filteredManufacture}"  editable="true"
                         styleClass="mystyle" tableStyle="table-layout:auto;width:100% important!;"    rowKey="#{testMatchvalues.testId}"   scrollRows="10" scrollable="true"   scrollHeight="230"  rows="40"  liveScroll="true"       selection="#{manufactureBean.testMatchModel}" selectionMode="single"                         resizableColumns="true"      >

                <p:column headerText="Test ID" filterBy="#{testMatchvalues.testId}" filterMatchMode="contains" style="width:35px">
                    <h:outputText value="#{testMatchvalues.testId}" />
                </p:column>

                <p:column headerText="Test Desc" filterBy="#{testMatchvalues.testDesc}" filterMatchMode="contains" style="width:35px" >
                    <h:outputText value="#{testMatchvalues.testDesc}" />
                </p:column>

                <p:column headerText="Specimen Desc" filterBy="#{testMatchvalues.specimenDesc}" filterMatchMode="contains" style="width:35px" >
                    <h:outputText value="#{testMatchvalues.specimenDesc}" />
                </p:column>
                <p:column headerText="Path Test Desc" filterBy="#{testMatchvalues.pathTestDesc}" filterMatchMode="contains" style="width:35px">
                    <h:outputText value="#{testMatchvalues.pathTestDesc}" />
                </p:column>
                <p:column headerText="Path Param Name"  style="width:35px" filterBy="#{testMatchvalues.parameterName}" filterMatchMode="contains">
                    <h:outputText value="#{testMatchvalues.parameterName}" />
                </p:column>
                <p:column headerText="Additional Factor"  style="width:35px" >
                    <h:outputText value="#{testMatchvalues.additionFactor}" />
                </p:column>
                <p:column headerText="Multiply Factor"  style="width:35px">
                    <h:outputText value="#{testMatchvalues.multiplyFactor}" />
                </p:column>
                <p:column headerText="Machine Host Code"  style="width:35px">
                    <h:outputText value="#{testMatchvalues.machineHostCode}" />
                </p:column>
                <p:column headerText="Active"  style="width:35px">
                    <h:outputText value="#{testMatchvalues.active}" />
                </p:column>
            </p:dataTable>
            <!--</p:panel>-->
        </p:fieldset>
</code>```

Code taken from https://www.primefaces.org/showcase/ui/data/datatable/basic.xhtml

Attached image shows the problem clearly as column headers and data is not aligned properly.

Image link

答: For p:column, width="4%" works for me rather than using '4px'

Body:
I am developing web using PrimeFaces 6.0 components. On

 component when we set scrollable="true" option, columns headers alignment goes wrong.

Following is my code snippet:

            <p:dataTable id="testmatchtable" var="testMatchvalues"   value="#{manufactureBean.listTestMatchata}" filteredValue="#{manufactureBean.filteredManufacture}"  editable="true"
                         styleClass="mystyle" tableStyle="table-layout:auto;width:100% important!;"    rowKey="#{testMatchvalues.testId}"   scrollRows="10" scrollable="true"   scrollHeight="230"  rows="40"  liveScroll="true"       selection="#{manufactureBean.testMatchModel}" selectionMode="single"                         resizableColumns="true"      >

                    <h:outputText value="#{testMatchvalues.testId}" />

                    <h:outputText value="#{testMatchvalues.testDesc}" />

                    <h:outputText value="#{testMatchvalues.specimenDesc}" />

                    <h:outputText value="#{testMatchvalues.pathTestDesc}" />

                    <h:outputText value="#{testMatchvalues.parameterName}" />

                    <h:outputText value="#{testMatchvalues.additionFactor}" />

                    <h:outputText value="#{testMatchvalues.multiplyFactor}" />

                    <h:outputText value="#{testMatchvalues.machineHostCode}" />

                    <h:outputText value="#{testMatchvalues.active}" />

Code taken from https://www.primefaces.org/showcase/ui/data/datatable/basic.xhtml

Attached image shows the problem clearly as column headers and data is not aligned properly.

Image link


问:
AES Encryption of Arabic characters - Objective C
I have an encryption function that gets data and key, with inner iv and returns an encrypted string. I can encrypt every string that contains just English characters but not about Arabic. This is my function. Please help me to find the problem. Thanks
```
-(NSString*)Encrypt:(NSString*)data second:(NSString*)key
    {
        size_t outLength;
        NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
        Byte byte[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; //It`s not valid. The main iv is secret
        NSData *datakey = [NSData dataWithBytes:key.UTF8String length:key.length];
        NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];
        CCCryptorStatus result = CCCrypt( kCCEncrypt
                                        , kCCAlgorithmAES128
                                        , kCCOptionPKCS7Padding
                                        , datakey.bytes
                                        , [datakey length]
                                        , byte
                                        , datadata.bytes
                                        , [datadata length]
                                        , cipherData.mutableBytes
                                        , cipherData.length
                                        , &outLength);</p>

<code>    if (result == kCCSuccess) {
        cipherData.length = outLength;
    }
    else {

    }
    NSData *encryptedData=cipherData;
    NSString *str=[encryptedData base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
    return str;
}
</code>```

答:
The problem is that cipherData is to short. It need to be a block longer than datadata which may (such as in this case) be longer than data.length.

When creating data with utf-8 encoding from a string that contains multiple-byte data such as Arabic, emoji and etc the data will be longer than the string characters.

Incorrect code:

```<code>NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];
</code>```

```
```

Correct code:

```<code>NSData *datadata = [data dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData * cipherData = [NSMutableData dataWithLength: datadata.length + kCCBlockSizeAES128];
</code>```

```
```

Note that misnaming the input string data does not help, it is a string. renaming data -> tex and then ``datadata->data` makes the code more clear. Good naming solves many code problems.

Body:
I have an encryption function that gets data and key, with inner iv and returns an encrypted string. I can encrypt every string that contains just English characters but not about Arabic. This is my function. Please help me to find the problem. Thanks

-(NSString*)Encrypt:(NSString*)data second:(NSString*)key
    {
        size_t outLength;
        NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
        Byte byte[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,}; //It`s not valid. The main iv is secret
        NSData *datakey = [NSData dataWithBytes:key.UTF8String length:key.length];
        NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];
        CCCryptorStatus result = CCCrypt( kCCEncrypt
                                        , kCCAlgorithmAES128
                                        , kCCOptionPKCS7Padding
                                        , datakey.bytes
                                        , [datakey length]
                                        , byte
                                        , datadata.bytes
                                        , [datadata length]
                                        , cipherData.mutableBytes
                                        , cipherData.length
                                        , &outLength);

    if (result == kCCSuccess) {
        cipherData.length = outLength;
    }
    else {

    }
    NSData *encryptedData=cipherData;
    NSString *str=[encryptedData base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
    return str;
}

Body:
The problem is that cipherData is to short. It need to be a block longer than datadata which may (such as in this case) be longer than data.length.

When creating data with utf-8 encoding from a string that contains multiple-byte data such as Arabic, emoji and etc the data will be longer than the string characters.

Incorrect code:

NSMutableData * cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
NSData *datadata = [NSData dataWithBytes:data.UTF8String length:data.length];

Correct code:

NSData *datadata = [data dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData * cipherData = [NSMutableData dataWithLength: datadata.length + kCCBlockSizeAES128];

Note that misnaming the input string data does not help, it is a string. renaming data -> tex and then ``datadata->data` makes the code more clear. Good naming solves many code problems.


问:
Disabled <input> that allows text selection?
Is it possible for a disabled <input> tag to support text selection?

答:
This will depend heavily on the browser. It works fine for me in Chrome and IE8: JSFiddle

Firefox (3.6) seems to be the one browser that doesn't support it. I don't think you can do anything about that.


问:
Add dynamic criteria to a JPA custom Query
I have a complex query(using multiple joins and subqueries) written in HQL which I have used in a Repository class. Similar to one below -

```<code>@Repository
public interface DataRepository extends PagingAndSortingRepository<Data,String> {

    public List<Data> findByService(@Param("service")Service service, Pageable page);

    @Query("SELECT DISTINCT d from Data d "
            +" WHERE (d.working in (SELECT d1 from Data d1 "
                +" JOIN d1.working d1w "
                +" JOIN d1.service s WITH (s in (:serviceList)))"
            +" OR d.cleared IS NOT NULL) AND [..several other CRITERIA]")
    public Page<Data> findForServices(@Param("serviceList")Set<Service> serviceList, Pageable page);
....
</code>```

Now I need to add criteria to it dynamically. These criteria are flexible in number which is holding me from including it into the HQL straightaway. Is it anyhow possible?

Sifting through the internet I have come across solutions for dynamic query. But, I guess they would be working only for cases where I do not have a custom query i.e.- no @Query at the query in the repository.

There was another interesting question I found. But that also suits for a case where you have a single table to query.

I do not want to be switching over to raw SQL queries. How do I solve this?

答:
The mentioned Criteria API with specifications and predicates is a little bit difficult to get used to but it is a good way to handle dynamic conditions.
I don't think it is possible to mix the annotation based query with programmatic query creation. </p>

Body:
I have a complex query(using multiple joins and subqueries) written in HQL which I have used in a Repository class. Similar to one below -

@Repository
public interface DataRepository extends PagingAndSortingRepository<Data,String> {

    public List<Data> findByService(@Param("service")Service service, Pageable page);

    @Query("SELECT DISTINCT d from Data d "
            +" WHERE (d.working in (SELECT d1 from Data d1 "
                +" JOIN d1.working d1w "
                +" JOIN d1.service s WITH (s in (:serviceList)))"
            +" OR d.cleared IS NOT NULL) AND [..several other CRITERIA]")
    public Page<Data> findForServices(@Param("serviceList")Set<Service> serviceList, Pageable page);
....

Now I need to add criteria to it dynamically. These criteria are flexible in number which is holding me from including it into the HQL straightaway. Is it anyhow possible?

Sifting through the internet I have come across solutions for dynamic query. But, I guess they would be working only for cases where I do not have a custom query i.e.- no @Query at the query in the repository.

There was another interesting question I found. But that also suits for a case where you have a single table to query.

I do not want to be switching over to raw SQL queries. How do I solve this?


问:
NSIS convert string into fixed length Code
I have info that I encrypt and would like to convert that to a fixed format

Example String:
IQIphBbUPPQrLdehz1JEB6a3yj4pCuDNhpHPfBAxVuYeDKlaK7mOuB40RxHpdmBVj33iMTk8GZ+/ShJdoWJcUPxlCZXIPue2JgOoGv+LXpvCcL724h7nsxSu2JoltXMm4VZ3HUwCLsOrEP7h6f2Q6ZFBqII43WzHL4f2LRjQIioFD/eE7kcgY104Axlj0Gcw

I would like to convert that into a format like: (0-9 A-Z)
0000-0000-0000-0000-0000-0000-0000

So output would look something like:
0D1Z-52CV-8645-8256-428S-RTG6-452D

Similar to Hex output but at a fixed length.

Is this possible? Note: encrypted string will vary in length.

答:
If you are talking about a one way function/cryptographic hash/message digest then you can just use one of the plug-ins from the NSIS Wiki:

```<code>Crypto::HashData "SHA1" "IQIphBbUPPQrLdehz1JEB6a3yj4pCuDNhpHPfBAxVuYeDKlaK7mOuB40RxHpdmBVj33iMTk8GZ+/ShJdoWJcUPxlCZXIPue2JgOoGv+LXpvCcL724h7nsxSu2JoltXMm4VZ3HUwCLsOrEP7h6f2Q6ZFBqII43WzHL4f2LRjQIioFD/eE7kcgY104Axlj0Gcw"
Pop $0
DetailPrint $0 ; A598CAB0215FFD7E27551515FA3DAF8D5AFD6D27
</code>```

You can format these hex bytes in any way you want:

```<code>Crypto::HashData "MD5" "IQIphBbUPPQrLdehz1JEB6a3yj4pCuDNhpHPfBAxVuYeDKlaK7mOuB40RxHpdmBVj33iMTk8GZ+/ShJdoWJcUPxlCZXIPue2JgOoGv+LXpvCcL724h7nsxSu2JoltXMm4VZ3HUwCLsOrEP7h6f2Q6ZFBqII43WzHL4f2LRjQIioFD/eE7kcgY104Axlj0Gcw"
Pop $0
DetailPrint $0 ; A709E7B1FF62582B7B97632F71912EB8 (MD5 is shorter but less secure)

StrCpy $1 ""
StrCpy $3 0
loop:
StrCpy $2 $0 4 $3
IntOp $3 $3 + 4
StrCmp $2 "" done
StrCpy $1 "$1-$2"
StrLen $2 $2
IntCmpU $2 4 loop done loop
done:
StrCpy $1 $1 "" 1
DetailPrint $1 ; A709-E7B1-FF62-582B-7B97-632F-7191-2EB8
</code>```

If on the other hand you want to get back the original input string then what you want to do is simply not possible. After you have hashed something you can only compare it with other hashes, you cannot (easily) figure out the initial input. There can also be collisions where two different inputs will generate the same output hash (The string "Hello" could in theory have the same hash as a the complete contents of a phone book etc.).

Body:
If you are talking about a one way function/cryptographic hash/message digest then you can just use one of the plug-ins from the NSIS Wiki:

Crypto::HashData "SHA1" "IQIphBbUPPQrLdehz1JEB6a3yj4pCuDNhpHPfBAxVuYeDKlaK7mOuB40RxHpdmBVj33iMTk8GZ+/ShJdoWJcUPxlCZXIPue2JgOoGv+LXpvCcL724h7nsxSu2JoltXMm4VZ3HUwCLsOrEP7h6f2Q6ZFBqII43WzHL4f2LRjQIioFD/eE7kcgY104Axlj0Gcw"
Pop $0
DetailPrint $0 ; A598CAB0215FFD7E27551515FA3DAF8D5AFD6D27

You can format these hex bytes in any way you want:

Crypto::HashData "MD5" "IQIphBbUPPQrLdehz1JEB6a3yj4pCuDNhpHPfBAxVuYeDKlaK7mOuB40RxHpdmBVj33iMTk8GZ+/ShJdoWJcUPxlCZXIPue2JgOoGv+LXpvCcL724h7nsxSu2JoltXMm4VZ3HUwCLsOrEP7h6f2Q6ZFBqII43WzHL4f2LRjQIioFD/eE7kcgY104Axlj0Gcw"
Pop $0
DetailPrint $0 ; A709E7B1FF62582B7B97632F71912EB8 (MD5 is shorter but less secure)

StrCpy $1 ""
StrCpy $3 0
loop:
StrCpy $2 $0 4 $3
IntOp $3 $3 + 4
StrCmp $2 "" done
StrCpy $1 "$1-$2"
StrLen $2 $2
IntCmpU $2 4 loop done loop
done:
StrCpy $1 $1 "" 1
DetailPrint $1 ; A709-E7B1-FF62-582B-7B97-632F-7191-2EB8

If on the other hand you want to get back the original input string then what you want to do is simply not possible. After you have hashed something you can only compare it with other hashes, you cannot (easily) figure out the initial input. There can also be collisions where two different inputs will generate the same output hash (The string "Hello" could in theory have the same hash as a the complete contents of a phone book etc.).


问:
24bit depth buffer with WebGL 1.0
I've found that there's no GL_DEPTH_COMPONENT24_OES renderbuffer storage equivalent in WebGL. But there's WEBGL_depth_texture extension that I can use to make a 24_8 or 32bit depth texture. Are those the DEPTH_COMPONENT24/DEPTH_COMPONENT32 renderbuffer equivalent? It would work the same as the screen buffer?

Is this the reason why they didn't make 24/32bit depth renderbuffer for WebGL?

答:
What the spec doesn't also say about is that DEPTH_STENCIL is just an abstraction. WebGL implementations, especially the older ones, can implement DEPTH_STENCIL by bundling one depth buffer and one stencil buffer under the hood. So a DEPTH_STENCIL renderbuffer can be anything: 16/8(if 24 is not supported), 24/8(with extension) and so on. And the conformance test implies that the depth buffer is at least 16bit.

They came up with this abstraction and didn't even give a simple anatomy of what it is. Just this line pops out of nowhere:

WebGL adds DEPTH_STENCIL renderbuffer

The mailing list archive.

Title: 24bit depth buffer with WebGL 1.0


问:
Run thread in main window for both Windows and Linux
I am creating a game to run inside a GUI (text area, button, menu etc) I've created a GUI with wxpython.  I create a panel inside the main window, which runs a pygame thread.

Problem:

On Windows, the pygame thread runs perfectly inside the main window.  But on Linux, the pygame pop up on a new window. How can I set this such that both windows and Linux run the thread in the main window?

Code:

```<code>class SDLPanel(wx.Panel):
    def __init__(self,parent,ID,tplSize):
        global pygame
        global pygame_init_flag
        wx.Panel.__init__(self, parent, ID, size=tplSize)
        self.Fit()

        if (sys.platform == 'win32'):
            os.environ['SDL_WINDOWID'] = str(self.GetHandle())
            os.environ['SDL_VIDEODRIVER'] = 'windib'
        else:
            os.environ['SDL_VIDEODRIVER'] = 'x11'

        #here is where things change if pygame has already been initialized
        #we need to do so again
        if pygame_init_flag:
            #call pygame.init() on subsaquent windows
            pygame.init()
        else:
            #import if this is the first time
            import pygame
        pygame_init_flag = True #make sure we know that pygame has been imported
        pygame.display.init()
        window = pygame.display.set_mode(tplSize)
        self.thread = SDLThread(window)
        self.thread.Start()

    def __del__(self):
        self.thread.Stop()
        print "thread stoped"
        #very important line, this makes sure that pygame exits before we
        #reinitialize it other wise we get errors
        pygame.quit()
</code>```

答: This is a disclaimer alert, according to https://forums.libsdl.org/viewtopic.php?p=39332, the solution works only with SDL 1.2 and not 2.0.</p>

Body:
I am creating a game to run inside a GUI (text area, button, menu etc) I've created a GUI with wxpython.  I create a panel inside the main window, which runs a pygame thread.

Problem:

On Windows, the pygame thread runs perfectly inside the main window.  But on Linux, the pygame pop up on a new window. How can I set this such that both windows and Linux run the thread in the main window?

Code:

class SDLPanel(wx.Panel):
    def __init__(self,parent,ID,tplSize):
        global pygame
        global pygame_init_flag
        wx.Panel.__init__(self, parent, ID, size=tplSize)
        self.Fit()

        if (sys.platform == 'win32'):
            os.environ['SDL_WINDOWID'] = str(self.GetHandle())
            os.environ['SDL_VIDEODRIVER'] = 'windib'
        else:
            os.environ['SDL_VIDEODRIVER'] = 'x11'

        #here is where things change if pygame has already been initialized
        #we need to do so again
        if pygame_init_flag:
            #call pygame.init() on subsaquent windows
            pygame.init()
        else:
            #import if this is the first time
            import pygame
        pygame_init_flag = True #make sure we know that pygame has been imported
        pygame.display.init()
        window = pygame.display.set_mode(tplSize)
        self.thread = SDLThread(window)
        self.thread.Start()

    def __del__(self):
        self.thread.Stop()
        print "thread stoped"
        #very important line, this makes sure that pygame exits before we
        #reinitialize it other wise we get errors
        pygame.quit()