问:
Resize about center on a QGraphicsItem proportional to mouse speed?
I am sorry for repetitively asking questions regarding pyqt, but the limited resources on it force me to.

I have been trying to implement a resize function for my circle shape, that is an extension of QGraphicsItem, which has an ellipse and a centered text. I am able to resize my shape as desired, but the shape takes a while to catch up to the mouse, i.e on switching directions the circle continues to increase but takes a while to switch directions, moreover the circle resizes with an anchor at the top left corner of the bounding rect.

See this question for a bit of code background

def updateHandlesPos(self):
        s = self.handleSize
        b = self.boundingRect()
        self.handles[self.handleTopLeft] = QRectF(b.left(), b.top(), s, s)
        self.handles[self.handleTopMiddle] = QRectF(b.center().x() - s / 2, b.top(), s, s)
        self.handles[self.handleTopRight] = QRectF(b.right() - s, b.top(), s, s)
        self.handles[self.handleMiddleLeft] = QRectF(b.left(), b.center().y() - s / 2, s, s)
        self.handles[self.handleMiddleRight] = QRectF(b.right() - s, b.center().y() - s / 2, s, s)
        self.handles[self.handleBottomLeft] = QRectF(b.left(), b.bottom() - s, s, s)
        self.handles[self.handleBottomMiddle] = QRectF(b.center().x() - s / 2, b.bottom() - s, s, s)
        self.handles[self.handleBottomRight] = QRectF(b.right() - s, b.bottom() - s, s, s)

    def interactiveResize(self, mousePos):
        self.prepareGeometryChange()
        if self.handleSelected in [self.handleTopLeft,
                                   self.handleTopRight,
                                   self.handleBottomLeft,
                                   self.handleBottomRight,
                                   self.handleTopMiddle,
                                   self.handleBottomMiddle,
                                   self.handleMiddleLeft,
                                   self.handleMiddleRight]:
            self.radius += (mousePos.y() + mousePos.x() + self.mousePressPos.x() - self.mousePressPos.y())/64
            self.setPos(self.x(),self.y())
        self.update()
        self.updateHandlesPos()
```

答:
Since the OP has not provided an MRE then I have created an example from scratch. The logic is to track the changes of the items and according to that calculate the new geometry and establish the new position of the other items.

from PyQt5 import QtWidgets, QtGui, QtCore

class GripItem(QtWidgets.QGraphicsPathItem):
    circle = QtGui.QPainterPath()
    circle.addEllipse(QtCore.QRectF(-5, -5, 10, 10))
    square = QtGui.QPainterPath()
    square.addRect(QtCore.QRectF(-10, -10, 20, 20))

    def __init__(self, annotation_item, index):
        super(GripItem, self).__init__()
        self.m_annotation_item = annotation_item
        self.m_index = index

        self.setPath(GripItem.circle)
        self.setBrush(QtGui.QColor("green"))
        self.setPen(QtGui.QPen(QtGui.QColor("green"), 2))
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setAcceptHoverEvents(True)
        self.setZValue(11)
        self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))

    def hoverEnterEvent(self, event):
        self.setPath(GripItem.square)
        self.setBrush(QtGui.QColor("red"))
        super(GripItem, self).hoverEnterEvent(event)

    def hoverLeaveEvent(self, event):
        self.setPath(GripItem.circle)
        self.setBrush(QtGui.QColor("green"))
        super(GripItem, self).hoverLeaveEvent(event)

    def mouseReleaseEvent(self, event):
        self.setSelected(False)
        super(GripItem, self).mouseReleaseEvent(event)

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.ItemPositionChange and self.isEnabled():
            self.m_annotation_item.movePoint(self.m_index, value)
        return super(GripItem, self).itemChange(change, value)

class DirectionGripItem(GripItem):
    def __init__(self, annotation_item, direction=QtCore.Qt.Horizontal, parent=None):
        super(DirectionGripItem, self).__init__(annotation_item, parent)
        self._direction = direction

    @property
    def direction(self):
        return self._direction

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.ItemPositionChange and self.isEnabled():
            p = QtCore.QPointF(self.pos())
            if self.direction == QtCore.Qt.Horizontal:
                p.setX(value.x())
            elif self.direction == QtCore.Qt.Vertical:
                p.setY(value.y())
            self.m_annotation_item.movePoint(self.m_index, p)
            return p
        return super(DirectionGripItem, self).itemChange(change, value)

class CircleAnnotation(QtWidgets.QGraphicsEllipseItem):
    def __init__(self, radius=1, parent=None):
        super(CircleAnnotation, self).__init__(parent)
        self.setZValue(11)
        self.m_items = []

        self.setPen(QtGui.QPen(QtGui.QColor("green"), 4))

        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges, True)

        self.setAcceptHoverEvents(True)

        self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))

        self._radius = radius
        self.update_rect()

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, r):
        if r <= 0:
            raise ValueError("radius must be positive")
        self._radius = r
        self.update_rect()
        self.add_grip_items()
        self.update_items_positions()

    def update_rect(self):
        rect = QtCore.QRectF(0, 0, 2 * self.radius, 2 * self.radius)
        rect.moveCenter(self.rect().center())
        self.setRect(rect)

    def add_grip_items(self):
        if self.scene() and not self.m_items:
            for i, (direction) in enumerate(
                (
                    QtCore.Qt.Vertical,
                    QtCore.Qt.Horizontal,
                    QtCore.Qt.Vertical,
                    QtCore.Qt.Horizontal,
                )
            ):
                item = DirectionGripItem(self, direction, i)
                self.scene().addItem(item)
                self.m_items.append(item)

    def movePoint(self, i, p):
        if 0 <= i < min(4, len(self.m_items)):
            item_selected = self.m_items[i]
            lp = self.mapFromScene(p)
            self._radius = (lp - self.rect().center()).manhattanLength()
            k = self.indexOf(lp)
            if k is not None:
                self.m_items = [item for item in self.m_items if not item.isSelected()]
                self.m_items.insert(k, item_selected)
                self.update_items_positions([k])
                self.update_rect()

    def update_items_positions(self, index_no_updates=None):
        index_no_updates = index_no_updates or []
        for i, (item, direction) in enumerate(
            zip(
                self.m_items,
                (
                    QtCore.Qt.Vertical,
                    QtCore.Qt.Horizontal,
                    QtCore.Qt.Vertical,
                    QtCore.Qt.Horizontal,
                ),
            ),
        ):
            item.m_index = i
            if i not in index_no_updates:
                pos = self.mapToScene(self.point(i))
                item = self.m_items[i]
                item._direction = direction
                item.setEnabled(False)
                item.setPos(pos)
                item.setEnabled(True)

    def indexOf(self, p):
        for i in range(4):
            if p == self.point(i):
                return i

    def point(self, index):
        if 0 <= index < 4:
            return [
                QtCore.QPointF(0, -self.radius),
                QtCore.QPointF(self.radius, 0),
                QtCore.QPointF(0, self.radius),
                QtCore.QPointF(-self.radius, 0),
            ][index]

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.ItemPositionHasChanged:
            self.update_items_positions()
            return
        if change == QtWidgets.QGraphicsItem.ItemSceneHasChanged:
            self.add_grip_items()
            self.update_items_positions()
            return
        return super(CircleAnnotation, self).itemChange(change, value)

    def hoverEnterEvent(self, event):
        self.setBrush(QtGui.QColor(255, 0, 0, 100))
        super(CircleAnnotation, self).hoverEnterEvent(event)

    def hoverLeaveEvent(self, event):
        self.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush))
        super(CircleAnnotation, self).hoverLeaveEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    scene = QtWidgets.QGraphicsScene()
    view = QtWidgets.QGraphicsView(scene)
    view.setRenderHints(QtGui.QPainter.Antialiasing)
    item = CircleAnnotation()
    item.radius = 100
    scene.addItem(item)
    view.showMaximized()

    sys.exit(app.exec_())
```


来源: stackexchange

问:
I have a jQuery quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made
I have a quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made. I want the 6 question results to appear even if some of them are incorrect. I hate to repeat the same code 6 times.

https://designaire.com/test1/health.html

```<code><script>
    $(function() {
          $('.exp').hide();
          $('.wrong').hide();
          $('input[name="test"]').on('click', function() {
            var el = $(this);
            if (el.val() == 'ans') {
              el.parents('.q').nextAll('.exp').first().show();
              el.parents('.q').nextAll('.wrong').first().hide();
              $('.wrong').hide();
            } else {
              el.parents('.q').nextAll('.wrong').first().show();
              el.parents('.q').nextAll('.exp').first().hide();
            }
          })
        });
    </script>
</code>```

```<code>    <form class="q">
    1. Janelle is excitedly telling her friend Reina how her job interview went. Reina keeps texting her boyfriend.
      <div class="answer">
    <input name="test" type="radio" value="inc" />
    Respect
    <input name="test" type="radio" value="ans" />
    Disrespect
    </div>
    </form>
    <div class="exp">★ Good Job!</div>
    <div class="wrong">Take another look at the examples in this lesson.</div></div>
</code>```

答:
You have a condition which hides all the elements with the wrong answers, just get rid of it.

```<code><script>
    $(function() {
          $('.exp').hide();
          $('.wrong').hide();
          $('input[name="test"]').on('click', function() {
            var el = $(this);
            if (el.val() == 'ans') {
              el.parents('.q').nextAll('.exp').first().show();
              el.parents('.q').nextAll('.wrong').first().hide();
              $('.wrong').hide(); // => remove this line
            } else {
              el.parents('.q').nextAll('.wrong').first().show();
              el.parents('.q').nextAll('.exp').first().hide();
            }
          })
        });
    </script>
</code>```

Example : https://jsfiddle.net/L0u798by/

ContentLicense: CC BY-SA 4.0

Body:
I have a quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made. I want the 6 question results to appear even if some of them are incorrect. I hate to repeat the same code 6 times.

https://designaire.com/test1/health.html

    <form class="q">
    1. Janelle is excitedly telling her friend Reina how her job interview went. Reina keeps texting her boyfriend.

    <input name="test" type="radio" value="inc" />
    Respect
    <input name="test" type="radio" value="ans" />
    Disrespect

    </form>

★ Good Job!

Take another look at the examples in this lesson.

Body:
You have a condition which hides all the elements with the wrong answers, just get rid of it.

<script>
    $(function() {
          $('.exp').hide();
          $('.wrong').hide();
          $('input[name="test"]').on('click', function() {
            var el = $(this);
            if (el.val() == 'ans') {
              el.parents('.q').nextAll('.exp').first().show();
              el.parents('.q').nextAll('.wrong').first().hide();
              $('.wrong').hide(); // => remove this line
            } else {
              el.parents('.q').nextAll('.wrong').first().show();
              el.parents('.q').nextAll('.exp').first().hide();
            }
          })
        });
    </script>

Example : https://jsfiddle.net/L0u798by/


问:
How can I stringify and destringify a Function in Dart?
Basically, I need to store a Function and fetch the same Function using a file. jsonEncode/Decode doesn't work (because stringification fails) and I can't find any other way to do this. The Function class doesn't have a parameters/body getter, so I don't even know how to implement my own logic.

functionEncode(Function x);
functionDecode(Function x); // How do I implement these?

Function x = (int x) {return x * 2;};

void main() {
   String encoded = functionEncode(x);
   Function decoded = functionDecode(x);
   assert(decoded == x); //passes
}
```

Does anyone know how I might be able to stringify/destringify a Function? Is this even possible?

答:
What you are asking for is essentially the ability to run arbitrary code (in the form of stringified functions) during runtime. This is technically possible to do, but it's a roundabout way, and is demonstrated in an article on iiro.dev:

final code = 'void main() { print("Hello World"); }';
final uri = Uri.dataFromString(code, mimeType: 'application/dart');
await Isolate.spawnUri(uri, [], null);
```

(The full article can be found here.)

There are several caveats to doing this, however. First, it only works when your program is running in JIT mode, so if you compile your Dart program into an AOT-compiled stand-alone program, it just plain will not work. (In Flutter, this means it only works when the app is running in debug mode rather than release mode.)

Second, running this code falls under the same umbrella as using eval in Javascript, in that it is not only error-prone but is also a h u g e security risk. If you put this code in an app and publish the app, you are essentially installing a backdoor into people's phones that allows someone to run any code they want. There is no real way to restrict or sandbox this feature, so it will always be a security concern to such an extent that your app will always house the possibility of becoming trojan-horse malware.

So basically, the answer to your question is the same as if someone were asking how to use eval. And the answer is always the same: YOU DON'T.

Body:
Basically, I need to store a Function and fetch the same Function using a file. jsonEncode/Decode doesn't work (because stringification fails) and I can't find any other way to do this. The Function class doesn't have a parameters/body getter, so I don't even know how to implement my own logic.

functionEncode(Function x);
functionDecode(Function x); // How do I implement these?

Function x = (int x) {return x * 2;};

void main() {
   String encoded = functionEncode(x);
   Function decoded = functionDecode(x);
   assert(decoded == x); //passes
}

Does anyone know how I might be able to stringify/destringify a Function? Is this even possible?

Body:
What you are asking for is essentially the ability to run arbitrary code (in the form of stringified functions) during runtime. This is technically possible to do, but it's a roundabout way, and is demonstrated in an article on iiro.dev:

final code = 'void main() { print("Hello World"); }';
final uri = Uri.dataFromString(code, mimeType: 'application/dart');
await Isolate.spawnUri(uri, [], null);

(The full article can be found here.)

There are several caveats to doing this, however. First, it only works when your program is running in JIT mode, so if you compile your Dart program into an AOT-compiled stand-alone program, it just plain will not work. (In Flutter, this means it only works when the app is running in debug mode rather than release mode.)

Second, running this code falls under the same umbrella as using eval in Javascript, in that it is not only error-prone but is also a h u g e security risk. If you put this code in an app and publish the app, you are essentially installing a backdoor into people's phones that allows someone to run any code they want. There is no real way to restrict or sandbox this feature, so it will always be a security concern to such an extent that your app will always house the possibility of becoming trojan-horse malware.

So basically, the answer to your question is the same as if someone were asking how to use eval. And the answer is always the same: YOU DON'T.


问:
Is GOTO considered harmless when jumping to cleanup at the end of function?
The goto statement has been examined at great length in several SO discussions (see this and that), and I certainly don't want to revive those heated debates.

Instead, I'd like to concentrate on a single use case of gotos and discuss its value and possible alternatives.

Consider the following code snippet, which is common in (at least my own) FSMs:

```<code>while (state = next_state()) {
        switch (state) {
                case foo:
                        /* handle foo, and finally: */
                        if (error) goto cleanup;
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) goto cleanup;
                        break;
                /* ...other cases... */
        }
}

return ok;

cleanup:
/* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
return error;
</code>```

Swapping out the cleanup stuff in a separate function just in order to save the gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos wherever possible.

My question: is my code example considered good style?

If not, are there feasible alternatives available?

Please adhere to the specific usage of goto described above. I don't want to delve into yet another discussion about the general use of goto.

答: The use of goto to cleanup the code by breaking multiple nesting for loop is very convenient, instead of setting flags and checking it in each nesting. For example, if you are unable to open a file and you discover it deep in a nesting, you can simply goto the cleanup segment and close the files and free resources. You can see such goto examples in the coreutilities tools sources.

Body:
The goto statement has been examined at great length in several SO discussions (see this and that), and I certainly don't want to revive those heated debates.

Instead, I'd like to concentrate on a single use case of gotos and discuss its value and possible alternatives.

Consider the following code snippet, which is common in (at least my own) FSMs:

while (state = next_state()) {
        switch (state) {
                case foo:
                        /* handle foo, and finally: */
                        if (error) goto cleanup;
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) goto cleanup;
                        break;
                /* ...other cases... */
        }
}

return ok;

cleanup:
/* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
return error;

Swapping out the cleanup stuff in a separate function just in order to save the gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos wherever possible.

My question: is my code example considered good style?

If not, are there feasible alternatives available?

Please adhere to the specific usage of goto described above. I don't want to delve into yet another discussion about the general use of goto.

ContentLicense: CC BY-SA 3.0


问:
running 2 equivalent pieces of Python 3.7.6 code using the PIL library in a Jupyter notebook BUT getting different results
I am running 2 Python 3.7.6 scripts that rely on the PIL library in a Jupyter notebook and getting different results and I cannot determine why.  I believe the two pieces should be equivalent and the output identical.  Can someone tell me why the second block is not generating the same output as the first?

In essence, the code should do the same thing, split an image into its RGB color channels, multiply each channel by one of 3 different intensities, and then merge the channels back into a composite image.  Here is the source image:

The only difference between the two code blocks is that in one I do the split within the innermost for loop and in the other, I do the split outside the for loops, copy the result to a variable and then assign the copy within the innermost loop.

In the first section I call the image split function within the innermost loop in the first segment and assign it to an image tuple variable:

img_tmp = image.split()

in the second, I call it outside the outer loop and assign it to an image tuple variable, and then assign that variable to a second variable within the innermost loop to reset the value every time through.

```<code>source = image.split()
...
for ...:
    for ...:
        img_tmp = source
</code>```

1st code block (working correctly):

```<code>import PIL
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

# read image and convert to RGB
image=Image.open("readonly/msi_recruitment.gif")
image=image.convert('RGB')

# read True Type font
fnt=ImageFont.truetype("readonly/fanwood-webfont.ttf", size=50)

# source = image.split()

# initialize key constants and variables
R,G,B = 0,1,2
intensity = [0.1, 0.5, 0.9]
images = []
images_meta = []
banner_height = 70
banner_margin = 10
txt_color = 'rgb(255,255,255)' # white

# build a list of 9 images, 3 for each color channel with the appropriate color intensity
for channel in [R,G,B]:

    # multiply each channel by appropriate color intensity factor
    for i_factor in intensity:
#       img_tmp = source # split the original image into 3 separate channels (images) with 1 for each color
        img_tmp = image.split()
        img_band = img_tmp[channel].point(lambda x: x*i_factor) # multiply the channel color by the intensity factor
        img_tmp[channel].paste(img_band) # replace the selected channel image with its color corrected version
        img_out = Image.merge(image.mode, img_tmp) #  merge all 3 channels back into one image
        images.append(img_out)  # add the updated image to the list
        images_meta.append('channel {} intensity {}'.format(channel, i_factor))  # update the metadata

# create a contact sheet of 3 rows with one row per color channel displaying
# an image with 3 different color intensities

first_image=images[0]
contact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3,first_image.height*3 + banner_height*3))
x=0
y=0

# initialize the drawing context with the contact sheet as background
banner = ImageDraw.Draw(contact_sheet)

for i,img in enumerate(images):

    # Lets paste the current image into the contact sheet
    contact_sheet.paste(img, (x, y) )

    # now draw the text and create a banner below the corresponding image
    banner.text((x, y + first_image.height + banner_margin), images_meta[i], font=fnt, fill=txt_color)

    # Now we update our X position. If it is going to be the width of the image, then we set it to 0
    # and update Y as well to point to the next "line" of the contact sheet.
    if x+first_image.width == contact_sheet.width:
        x=0
        y=y+first_image.height + banner_height
    else:
        x=x+first_image.width

# resize and display the contact sheet
contact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) ))
display(contact_sheet)

contact_sheet.save('assignment_1.pdf')
</code>```

resulting picture:

2nd code block (runs, but does not process the image correctly):

```<code>import PIL
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

# read image and convert to RGB
image=Image.open("readonly/msi_recruitment.gif")
image=image.convert('RGB')

# read True Type font
fnt=ImageFont.truetype("readonly/fanwood-webfont.ttf", size=50)

source = image.split()

# initialize key constants and variables
R,G,B = 0,1,2
intensity = [0.1, 0.5, 0.9]
images = []
images_meta = []
banner_height = 70
banner_margin = 10
txt_color = 'rgb(255,255,255)' # white

# build a list of 9 images, 3 for each color channel with the appropriate color intensity
for channel in [R,G,B]:

    # multiply each channel by appropriate color intensity factor
    for i_factor in intensity:
        img_tmp = source # split the original image into 3 separate channels (images) with 1 for each color
        img_band = img_tmp[channel].point(lambda x: x*i_factor) # multiply the channel color by the intensity factor
        img_tmp[channel].paste(img_band) # replace the selected channel image with its color corrected version
        img_out = Image.merge(image.mode, img_tmp) #  merge all 3 channels back into one image
        images.append(img_out)  # add the updated image to the list
        images_meta.append('channel {} intensity {}'.format(channel, i_factor))  # update the metadata

# create a contact sheet of 3 rows with one row per color channel displaying
# an image with 3 different color intensities

first_image=images[0]
contact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3,first_image.height*3 + banner_height*3))
x=0
y=0

# initialize the drawing context with the contact sheet as background
banner = ImageDraw.Draw(contact_sheet)

for i,img in enumerate(images):

    # Lets paste the current image into the contact sheet
    contact_sheet.paste(img, (x, y) )

    # now draw the text and create a banner below the corresponding image
    banner.text((x, y + first_image.height + banner_margin), images_meta[i], font=fnt, fill=txt_color)

    # Now we update our X position. If it is going to be the width of the image, then we set it to 0
    # and update Y as well to point to the next "line" of the contact sheet.
    if x+first_image.width == contact_sheet.width:
        x=0
        y=y+first_image.height + banner_height
    else:
        x=x+first_image.width

# resize and display the contact sheet
contact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) ))
display(contact_sheet)

contact_sheet.save('assignment_1.pdf')```
```

答:
Brifly: Python doesn't duplicate list/tuple when you assign to new variable.

In second version when you assign

```<code> img_tmp = source
</code>```

then Pythond doesn't create copy of data but only alias to original one. So when you change img_tmp then you also change source and in next loop you work with modified version, not original.

You need

```<code> import copy

 img_tmp = copy.deepcopy(source)
</code>```

or (because it is tuple with 3 arrays)

```<code> img_tmp = (source[0].copy(), source[1].copy(), source[2].copy())
</code>```

Body:
I am running 2 Python 3.7.6 scripts that rely on the PIL library in a Jupyter notebook and getting different results and I cannot determine why.  I believe the two pieces should be equivalent and the output identical.  Can someone tell me why the second block is not generating the same output as the first?

In essence, the code should do the same thing, split an image into its RGB color channels, multiply each channel by one of 3 different intensities, and then merge the channels back into a composite image.  Here is the source image:

The only difference between the two code blocks is that in one I do the split within the innermost for loop and in the other, I do the split outside the for loops, copy the result to a variable and then assign the copy within the innermost loop.

In the first section I call the image split function within the innermost loop in the first segment and assign it to an image tuple variable:

img_tmp = image.split()

in the second, I call it outside the outer loop and assign it to an image tuple variable, and then assign that variable to a second variable within the innermost loop to reset the value every time through.

source = image.split()
...
for ...:
    for ...:
        img_tmp = source

1st code block (working correctly):

import PIL
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

# read image and convert to RGB
image=Image.open("readonly/msi_recruitment.gif")
image=image.convert('RGB')

# read True Type font
fnt=ImageFont.truetype("readonly/fanwood-webfont.ttf", size=50)

# source = image.split()

# initialize key constants and variables
R,G,B = 0,1,2
intensity = [0.1, 0.5, 0.9]
images = []
images_meta = []
banner_height = 70
banner_margin = 10
txt_color = 'rgb(255,255,255)' # white

# build a list of 9 images, 3 for each color channel with the appropriate color intensity
for channel in [R,G,B]:

    # multiply each channel by appropriate color intensity factor
    for i_factor in intensity:
#       img_tmp = source # split the original image into 3 separate channels (images) with 1 for each color
        img_tmp = image.split()
        img_band = img_tmp[channel].point(lambda x: x*i_factor) # multiply the channel color by the intensity factor
        img_tmp[channel].paste(img_band) # replace the selected channel image with its color corrected version
        img_out = Image.merge(image.mode, img_tmp) #  merge all 3 channels back into one image
        images.append(img_out)  # add the updated image to the list
        images_meta.append('channel {} intensity {}'.format(channel, i_factor))  # update the metadata

# create a contact sheet of 3 rows with one row per color channel displaying
# an image with 3 different color intensities

first_image=images[0]
contact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3,first_image.height*3 + banner_height*3))
x=0
y=0

# initialize the drawing context with the contact sheet as background
banner = ImageDraw.Draw(contact_sheet)

for i,img in enumerate(images):

    # Lets paste the current image into the contact sheet
    contact_sheet.paste(img, (x, y) )

    # now draw the text and create a banner below the corresponding image
    banner.text((x, y + first_image.height + banner_margin), images_meta[i], font=fnt, fill=txt_color)

    # Now we update our X position. If it is going to be the width of the image, then we set it to 0
    # and update Y as well to point to the next "line" of the contact sheet.
    if x+first_image.width == contact_sheet.width:
        x=0
        y=y+first_image.height + banner_height
    else:
        x=x+first_image.width

# resize and display the contact sheet
contact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) ))
display(contact_sheet)

contact_sheet.save('assignment_1.pdf')

resulting picture:

2nd code block (runs, but does not process the image correctly):

import PIL
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

# read image and convert to RGB
image=Image.open("readonly/msi_recruitment.gif")
image=image.convert('RGB')

# read True Type font
fnt=ImageFont.truetype("readonly/fanwood-webfont.ttf", size=50)

source = image.split()

# initialize key constants and variables
R,G,B = 0,1,2
intensity = [0.1, 0.5, 0.9]
images = []
images_meta = []
banner_height = 70
banner_margin = 10
txt_color = 'rgb(255,255,255)' # white

# build a list of 9 images, 3 for each color channel with the appropriate color intensity
for channel in [R,G,B]:

    # multiply each channel by appropriate color intensity factor
    for i_factor in intensity:
        img_tmp = source # split the original image into 3 separate channels (images) with 1 for each color
        img_band = img_tmp[channel].point(lambda x: x*i_factor) # multiply the channel color by the intensity factor
        img_tmp[channel].paste(img_band) # replace the selected channel image with its color corrected version
        img_out = Image.merge(image.mode, img_tmp) #  merge all 3 channels back into one image
        images.append(img_out)  # add the updated image to the list
        images_meta.append('channel {} intensity {}'.format(channel, i_factor))  # update the metadata

# create a contact sheet of 3 rows with one row per color channel displaying
# an image with 3 different color intensities

first_image=images[0]
contact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3,first_image.height*3 + banner_height*3))
x=0
y=0

# initialize the drawing context with the contact sheet as background
banner = ImageDraw.Draw(contact_sheet)

for i,img in enumerate(images):

    # Lets paste the current image into the contact sheet
    contact_sheet.paste(img, (x, y) )

    # now draw the text and create a banner below the corresponding image
    banner.text((x, y + first_image.height + banner_margin), images_meta[i], font=fnt, fill=txt_color)

    # Now we update our X position. If it is going to be the width of the image, then we set it to 0
    # and update Y as well to point to the next "line" of the contact sheet.
    if x+first_image.width == contact_sheet.width:
        x=0
        y=y+first_image.height + banner_height
    else:
        x=x+first_image.width

# resize and display the contact sheet
contact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) ))
display(contact_sheet)

contact_sheet.save('assignment_1.pdf')```

Body:
Brifly: Python doesn't duplicate list/tuple when you assign to new variable.

In second version when you assign

 img_tmp = source

then Pythond doesn't create copy of data but only alias to original one. So when you change img_tmp then you also change source and in next loop you work with modified version, not original.

You need

 import copy

 img_tmp = copy.deepcopy(source)

or (because it is tuple with 3 arrays)

 img_tmp = (source[0].copy(), source[1].copy(), source[2].copy())


问:
I can't start a virtualenv from a shell script
The script is to open a new terminal and access a directory, activate the virtual environment inside him, and then run my service within that environment:

```<code>#!/bin/bash
gnome-terminal -- bash -c "cd mydirectory/project && source ~/myenv/bin/activate && python3 run.py runserver; exec bash"
</code>```

But when you run it, don't activate the environment. The other commands works.

答:
You can create a shell file ~/mydirectory/project/runserver.sh as :

```<code>cd $HOME/mydirectory/project
source ~/myenv/bin/activate
python3 run.py runserver
</code>```

Then run:

```<code>gnome-terminal -- bash --rcfile ~/mydirectory/project/runserver.sh
</code>```

Body:
The script is to open a new terminal and access a directory, activate the virtual environment inside him, and then run my service within that environment:

#!/bin/bash
gnome-terminal -- bash -c "cd mydirectory/project && source ~/myenv/bin/activate && python3 run.py runserver; exec bash"

But when you run it, don't activate the environment. The other commands works.

Body:
You can create a shell file ~/mydirectory/project/runserver.sh as :

cd $HOME/mydirectory/project
source ~/myenv/bin/activate
python3 run.py runserver

Then run:

gnome-terminal -- bash --rcfile ~/mydirectory/project/runserver.sh


问:
ElasticSearch Terms Aggregation not working with custom Analyzer and Pattern Tokenizer
I am trying the Terms Aggregation for the first time and there seems to be an issue with the custom pattern tokenizer I am using.

Here is the Mapping:

```<code>{
  "mappings": {
    "properties": {
      "contentItemType": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        },
        "analyzer": "patternAnalyzer"
      },
      "theme": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        },
        "analyzer": "patternAnalyzer"
      }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "patternAnalyzer": {
          "tokenizer": "patternTokenizer"
        }
      },
      "tokenizer": {
        "patternTokenizer": {
          "type": "pattern",
          "pattern": ";"
        }
      }
    }
  }
}
</code>```

When I am trying to search with the aggregation API http://my_server/index_name/_search here is the result:

```<code>{
  "aggregations": {
    "group_by_contentItemType": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Correspondence; Reports",
          "doc_count": 3
        },
        {
          "key": "Correspondence",
          "doc_count": 2
        },
        {
          "key": "Meeting Minutes; Administrative Records; Reports",
          "doc_count": 2
        },
        {
          "key": "Correspondence; Legal and Treaty Material; Reports",
          "doc_count": 1
        },
        {
          "key": "Correspondence; Memoranda",
          "doc_count": 1
        },
        {
          "key": "Memoranda",
          "doc_count": 1
        },
        {
          "key": "Reports",
          "doc_count": 1
        }
      ]
    },
    "group_by_theme": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "International Relations",
          "doc_count": 2
        },
        {
          "key": "Key Events; Dissent; Dissent; Resistance; Human Rights",
          "doc_count": 2
        },
        {
          "key": "Border Security and Migration; Key Events",
          "doc_count": 1
        },
        {
          "key": "Border Security and Migration; Second World War Aftermath",
          "doc_count": 1
        },
        {
          "key": "Domestic Politics",
          "doc_count": 1
        },
        {
          "key": "Domestic Politics; Border Security and Migration",
          "doc_count": 1
        },
        {
          "key": "Economics and Trade; International Relations",
          "doc_count": 1
        },
        {
          "key": "Embassy and Consulate Administration; Industry and Agriculture; International Relations",
          "doc_count": 1
        },
        {
          "key": "Populations and Social Policy; Second World War Aftermath; International Relations",
          "doc_count": 1
        }
      ]
    }
  }
}
</code>```

As you can see the issue with the aggregation. I have been stuck on this problem for quite a few days. I have seen so many examples and all but still not able to solve this issue.
Please help. Thanks in Advance!!!

EDIT!!!
Here is the full mapping after @CatalinM answer:

```<code>{
    "local_cwee": {
        "mappings": {
            "dynamic": "false",
            "properties": {
                "author": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "commentaries": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "contentDateEndMonth": {
                    "type": "integer"
                },
                "contentDateEndSpecified": {
                    "type": "boolean"
                },
                "contentDateEndYear": {
                    "type": "integer"
                },
                "contentDateMonth": {
                    "type": "integer"
                },
                "contentDateMonthSpecified": {
                    "type": "boolean"
                },
                "contentDateStartMonth": {
                    "type": "integer"
                },
                "contentDateStartSpecified": {
                    "type": "boolean"
                },
                "contentDateStartYear": {
                    "type": "integer"
                },
                "contentDateYear": {
                    "type": "integer"
                },
                "contentDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "contentItemType": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "contentItemTypeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "contentTitle": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "copyrightNotices": {
                    "type": "nested",
                    "properties": {
                        "imageName": {
                            "type": "text",
                            "fields": {
                                "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        },
                        "text": {
                            "type": "text",
                            "fields": {
                                "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        }
                    }
                },
                "countries": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "country": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "coverDateEndMonth": {
                    "type": "integer"
                },
                "coverDateEndSpecified": {
                    "type": "boolean"
                },
                "coverDateEndYear": {
                    "type": "integer"
                },
                "coverDateMonth": {
                    "type": "integer"
                },
                "coverDateMonthSpecified": {
                    "type": "boolean"
                },
                "coverDateStartMonth": {
                    "type": "integer"
                },
                "coverDateStartSpecified": {
                    "type": "boolean"
                },
                "coverDateStartYear": {
                    "type": "integer"
                },
                "coverDateYear": {
                    "type": "integer"
                },
                "displayName": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "documentDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "documentLevel": {
                    "type": "integer"
                },
                "keyEvents": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "language": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languageFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languages": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languagesFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "moduleNumber": {
                    "type": "integer"
                },
                "notes": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "pageTranscript": {
                    "type": "text",
                    "term_vector": "with_positions",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    },
                    "analyzer": "whiteSpaceAnalyzer"
                },
                "people": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationDate": {
                    "type": "integer"
                },
                "publicationDateEndMonth": {
                    "type": "integer"
                },
                "publicationDateEndSpecified": {
                    "type": "boolean"
                },
                "publicationDateEndYear": {
                    "type": "integer"
                },
                "publicationDateMonth": {
                    "type": "integer"
                },
                "publicationDateMonthSpecified": {
                    "type": "boolean"
                },
                "publicationDateStartMonth": {
                    "type": "integer"
                },
                "publicationDateStartSpecified": {
                    "type": "boolean"
                },
                "publicationDateStartYear": {
                    "type": "integer"
                },
                "publicationDateYear": {
                    "type": "integer"
                },
                "publicationDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationId": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationIdFacet": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationTitle": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationType": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationTypeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationYear": {
                    "type": "integer"
                },
                "publisherName": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publisherNameFacet": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                }
                "subject": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectAreas": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectAreasFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectCountries": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectCountriesFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectKeyword": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectKeywordFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subthemeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subthemes": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "theme": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "themeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "themes": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                }
            }
        }
    }
}
</code>```

答:
Using your custom tokenizer, the tokens in the text field are "Correspondence", "Meeting Minutes", "Administrative Records", ..etc. So i don't think you need the keyword field.

To make aggregations work on the text field, you'll have to add "fielddata": true in the mapping. This is by default disabled because aggregations on large text fields are not wanted, but in your case the tokens are exactly the values you want to aggregate on.

here's the simplified configuration

```<code>{
  "mappings": {
    "properties": {
      "contentItemType": {
        "type": "text",
        "fielddata": true,
        "analyzer": "patternAnalyzer"
      }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "patternAnalyzer": {
          "tokenizer": "patternTokenizer"
        }
      },
      "tokenizer": {
        "patternTokenizer": {
          "type": "pattern",
          "pattern": ";"
        }
      }
    }
  }
}
</code>```

the query:

```<code>{
  "aggregations" : {
      "test" : {
          "terms" : { "field" : "contentItemType" }
      }
  }
}
</code>```

and result:

```<code>"aggregations": {
    "test": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": " Administrative Records",
                "doc_count": 1
            },
            {
                "key": "Meeting Minutes",
                "doc_count": 1
            },
            {
                "key": " Reports",
                "doc_count": 1
            }
        ]
    }
}
</code>```

Body:
I am trying the Terms Aggregation for the first time and there seems to be an issue with the custom pattern tokenizer I am using.

Here is the Mapping:

{
  "mappings": {
    "properties": {
      "contentItemType": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        },
        "analyzer": "patternAnalyzer"
      },
      "theme": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        },
        "analyzer": "patternAnalyzer"
      }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "patternAnalyzer": {
          "tokenizer": "patternTokenizer"
        }
      },
      "tokenizer": {
        "patternTokenizer": {
          "type": "pattern",
          "pattern": ";"
        }
      }
    }
  }
}

When I am trying to search with the aggregation API http://my_server/index_name/_search here is the result:

{
  "aggregations": {
    "group_by_contentItemType": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Correspondence; Reports",
          "doc_count": 3
        },
        {
          "key": "Correspondence",
          "doc_count": 2
        },
        {
          "key": "Meeting Minutes; Administrative Records; Reports",
          "doc_count": 2
        },
        {
          "key": "Correspondence; Legal and Treaty Material; Reports",
          "doc_count": 1
        },
        {
          "key": "Correspondence; Memoranda",
          "doc_count": 1
        },
        {
          "key": "Memoranda",
          "doc_count": 1
        },
        {
          "key": "Reports",
          "doc_count": 1
        }
      ]
    },
    "group_by_theme": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "International Relations",
          "doc_count": 2
        },
        {
          "key": "Key Events; Dissent; Dissent; Resistance; Human Rights",
          "doc_count": 2
        },
        {
          "key": "Border Security and Migration; Key Events",
          "doc_count": 1
        },
        {
          "key": "Border Security and Migration; Second World War Aftermath",
          "doc_count": 1
        },
        {
          "key": "Domestic Politics",
          "doc_count": 1
        },
        {
          "key": "Domestic Politics; Border Security and Migration",
          "doc_count": 1
        },
        {
          "key": "Economics and Trade; International Relations",
          "doc_count": 1
        },
        {
          "key": "Embassy and Consulate Administration; Industry and Agriculture; International Relations",
          "doc_count": 1
        },
        {
          "key": "Populations and Social Policy; Second World War Aftermath; International Relations",
          "doc_count": 1
        }
      ]
    }
  }
}

As you can see the issue with the aggregation. I have been stuck on this problem for quite a few days. I have seen so many examples and all but still not able to solve this issue.
Please help. Thanks in Advance!!!

EDIT!!!
Here is the full mapping after @CatalinM answer:

{
    "local_cwee": {
        "mappings": {
            "dynamic": "false",
            "properties": {
                "author": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "commentaries": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "contentDateEndMonth": {
                    "type": "integer"
                },
                "contentDateEndSpecified": {
                    "type": "boolean"
                },
                "contentDateEndYear": {
                    "type": "integer"
                },
                "contentDateMonth": {
                    "type": "integer"
                },
                "contentDateMonthSpecified": {
                    "type": "boolean"
                },
                "contentDateStartMonth": {
                    "type": "integer"
                },
                "contentDateStartSpecified": {
                    "type": "boolean"
                },
                "contentDateStartYear": {
                    "type": "integer"
                },
                "contentDateYear": {
                    "type": "integer"
                },
                "contentDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "contentItemType": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "contentItemTypeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "contentTitle": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "copyrightNotices": {
                    "type": "nested",
                    "properties": {
                        "imageName": {
                            "type": "text",
                            "fields": {
                                "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        },
                        "text": {
                            "type": "text",
                            "fields": {
                                "keyword": {
                                    "type": "keyword",
                                    "ignore_above": 256
                                }
                            }
                        }
                    }
                },
                "countries": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "country": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "coverDateEndMonth": {
                    "type": "integer"
                },
                "coverDateEndSpecified": {
                    "type": "boolean"
                },
                "coverDateEndYear": {
                    "type": "integer"
                },
                "coverDateMonth": {
                    "type": "integer"
                },
                "coverDateMonthSpecified": {
                    "type": "boolean"
                },
                "coverDateStartMonth": {
                    "type": "integer"
                },
                "coverDateStartSpecified": {
                    "type": "boolean"
                },
                "coverDateStartYear": {
                    "type": "integer"
                },
                "coverDateYear": {
                    "type": "integer"
                },
                "displayName": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "documentDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "documentLevel": {
                    "type": "integer"
                },
                "keyEvents": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "language": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languageFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languages": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "languagesFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "moduleNumber": {
                    "type": "integer"
                },
                "notes": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "pageTranscript": {
                    "type": "text",
                    "term_vector": "with_positions",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    },
                    "analyzer": "whiteSpaceAnalyzer"
                },
                "people": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationDate": {
                    "type": "integer"
                },
                "publicationDateEndMonth": {
                    "type": "integer"
                },
                "publicationDateEndSpecified": {
                    "type": "boolean"
                },
                "publicationDateEndYear": {
                    "type": "integer"
                },
                "publicationDateMonth": {
                    "type": "integer"
                },
                "publicationDateMonthSpecified": {
                    "type": "boolean"
                },
                "publicationDateStartMonth": {
                    "type": "integer"
                },
                "publicationDateStartSpecified": {
                    "type": "boolean"
                },
                "publicationDateStartYear": {
                    "type": "integer"
                },
                "publicationDateYear": {
                    "type": "integer"
                },
                "publicationDoi": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationId": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationIdFacet": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationTitle": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "publicationType": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationTypeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publicationYear": {
                    "type": "integer"
                },
                "publisherName": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "publisherNameFacet": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                }
                "subject": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectAreas": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectAreasFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectCountries": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectCountriesFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectKeyword": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subjectKeywordFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subthemeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "subthemes": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "theme": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "themeFacets": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                },
                "themes": {
                    "type": "text",
                    "analyzer": "patternAnalyzer",
                    "fielddata": true
                }
            }
        }
    }
}

Body:
Using your custom tokenizer, the tokens in the text field are "Correspondence", "Meeting Minutes", "Administrative Records", ..etc. So i don't think you need the keyword field.

To make aggregations work on the text field, you'll have to add "fielddata": true in the mapping. This is by default disabled because aggregations on large text fields are not wanted, but in your case the tokens are exactly the values you want to aggregate on.

here's the simplified configuration

{
  "mappings": {
    "properties": {
      "contentItemType": {
        "type": "text",
        "fielddata": true,
        "analyzer": "patternAnalyzer"
      }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "patternAnalyzer": {
          "tokenizer": "patternTokenizer"
        }
      },
      "tokenizer": {
        "patternTokenizer": {
          "type": "pattern",
          "pattern": ";"
        }
      }
    }
  }
}

the query:

{
  "aggregations" : {
      "test" : {
          "terms" : { "field" : "contentItemType" }
      }
  }
}

and result:

"aggregations": {
    "test": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": " Administrative Records",
                "doc_count": 1
            },
            {
                "key": "Meeting Minutes",
                "doc_count": 1
            },
            {
                "key": " Reports",
                "doc_count": 1
            }
        ]
    }
}


问:
CSS: How to center the snackbar horizontally?
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

```<code><div id="snackbar">Some very very very very very very long text some message..</div>
</code>```

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.

答:
I placed snackbar inside a flex container to place it in center. You can read more about flexbox layout from this article: A Complete Guide to Flexbox | CSS-Tricks.

.snackbar-root {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.snackbar {
  max-width: 100%;
  padding: 15px;
  background: #333;
  color: white;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="snackbar-root">
  <div class="snackbar">Here goes short message</div>
  <div class="snackbar">Here goes some loooooooooooooooooooooooooooooooooooong messsssssssssssssssssssage</div>
</div></code>```

Body:
I am using a simple snackbar code from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar). It works OK but for long message it starts to move off the horizontal center, for example.

Some very very very very very very long text some message..

I try to fix it by removing "margin-left" and also "left", and only setting "margin: 0 auto" but it doesn't work.

Body:
I placed snackbar inside a flex container to place it in center. You can read more about flexbox layout from this article: A Complete Guide to Flexbox | CSS-Tricks.

.snackbar-root {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.snackbar {
  max-width: 100%;
  padding: 15px;
  background: #333;
  color: white;
  font-family: sans-serif;
}

<div class="snackbar-root">
  <div class="snackbar">Here goes short message</div>
  <div class="snackbar">Here goes some loooooooooooooooooooooooooooooooooooong messsssssssssssssssssssage</div>
</div>


问:
How to add many controls to a Windows Forms Tab?
so i've been searching the net, and I've found some code to add controls to a tab, but I need to add many controls to the  new tab.

Here is what I've got:
A new player tab, that acesses the database and adds a new player, with all the data.
4 Player tabs, with a combobox in the bottom, on FormLoad or a new player is created, this box is updated with all the current palyers in the database, upon selecting one, all his data is displyed.

What I want to do is remove the 4 tabs and add a button on the new player tab, with a combobox to select players and a button to confirm, when the button is pressed, it should generate a new tab, exactly like the 4 old ones.

there is by any chance a way to hide from the user one of the old 4 tabs and every time I create a new one, copy all controls from the hidden one?

Edit: where is the code I've found for adding controls:

```<code>    Button button1 = new Button();

    button1.Location = new Point(20, 10);
    button1.Text = "Click Me";

    tabPage1.Controls.Add(button1)
</code>```

but what i want is like:

```<code>new tab tabx = sampletab
tabcontrol.tabs.add(tabx);
</code>```

But this only copies the title, not the controls

答: I probably would create a UserControl handling a single player's data. Then you only have to add a single control to each new tab.

Body:
so i've been searching the net, and I've found some code to add controls to a tab, but I need to add many controls to the  new tab.

Here is what I've got:
A new player tab, that acesses the database and adds a new player, with all the data.
4 Player tabs, with a combobox in the bottom, on FormLoad or a new player is created, this box is updated with all the current palyers in the database, upon selecting one, all his data is displyed.

What I want to do is remove the 4 tabs and add a button on the new player tab, with a combobox to select players and a button to confirm, when the button is pressed, it should generate a new tab, exactly like the 4 old ones.

there is by any chance a way to hide from the user one of the old 4 tabs and every time I create a new one, copy all controls from the hidden one?

Edit: where is the code I've found for adding controls:

    Button button1 = new Button();

    button1.Location = new Point(20, 10);
    button1.Text = "Click Me";

    tabPage1.Controls.Add(button1)

but what i want is like:

new tab tabx = sampletab
tabcontrol.tabs.add(tabx);

But this only copies the title, not the controls


问:
Possible workaround for async negedge reset?
I'd like to have a register with async reset signal, like following:

```<code>always @(posedge clk or negedge rst_n)
begin
    if(!rst_n)
        out <= 1'b0
    else
        out <= in
end
</code>```

I have tried class AsyncReset() and withReset(). However, the generated code uses a posedge reset and the variable of AsyncReset() does not accept !.

Is there any workaround for this?

答:
I thought Jack's quick comment about avoiding glitches deserved a longer explanation.

Using an asynchronous reset creates a second timing arc in the design, from the reset to the end flop.  The reset signal can be asserted at any time but needs to be de-asserted synchronous to the clock otherwise the flop can become metastable.

A common technique to do this is to use a reset synchronizer.

https://scastie.scala-lang.org/hutch31/EPozcu39QBOmaB5So6fyeA/13

The synchronizer shown in the above code is coded directly in Verilog as I do not know a way to keep the FIRRTL optimizer from pruning through constant optimization.  The logic downstream of the reset sync can be either sync or async reset.

Body:
I'd like to have a register with async reset signal, like following:

always @(posedge clk or negedge rst_n)
begin
    if(!rst_n)
        out <= 1'b0
    else
        out <= in
end

I have tried class AsyncReset() and withReset(). However, the generated code uses a posedge reset and the variable of AsyncReset() does not accept !.

Is there any workaround for this?


问:
Missing Python.h while trying to compile a C extension module
I'm following this tutorial on how to extend Python with C\C++ code.

The section named "Building the extension module with GCC for Microsoft Windows" fails for me with the following error:

```<code>fatal error: Python.h: No such file or directory
</code>```

The section named "Building the extension module using Microsoft Visual C++" also fails with a similar error:

```<code>fatal error C1083: Cannot open include file: 'Python.h': No such file or directory
</code>```

What should I do to solve this?

答:
The Python official documentation has already made it clear. Check it out here

The header files are typically installed with Python. On Unix, these are located in the directories prefix/include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where prefix is the installation directory specified to the installer.

To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place the parent directories on the search path and then use #include ; this will break on multi-platform builds since the platform independent headers under prefix include the platform specific headers from exec_prefix.

And they have provided a convenient way to get the correct cflags that we should pass to compiler. here

So for example, here is what I got after running the command

```<code>root@36fd2072c90a:/# /usr/bin/python3-config --cflags
-I/usr/include/python3.5m -I/usr/include/python3.5m  -Wno-unused-result -Wsign-compare -g -fstack-protector-strong -Wformat -Werror=format-security  -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
</code>```

Pass those flags to the compiler, and it will work.

ContentLicense: CC BY-SA 2.5

Body:
I'm following this tutorial on how to extend Python with C\C++ code.

The section named "Building the extension module with GCC for Microsoft Windows" fails for me with the following error:

fatal error: Python.h: No such file or directory

The section named "Building the extension module using Microsoft Visual C++" also fails with a similar error:

fatal error C1083: Cannot open include file: 'Python.h': No such file or directory

What should I do to solve this?

Body:
The Python official documentation has already made it clear. Check it out here

The header files are typically installed with Python. On Unix, these are located in the directories prefix/include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where prefix is the installation directory specified to the installer.

To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place the parent directories on the search path and then use #include ; this will break on multi-platform builds since the platform independent headers under prefix include the platform specific headers from exec_prefix.

And they have provided a convenient way to get the correct cflags that we should pass to compiler. here

So for example, here is what I got after running the command

root@36fd2072c90a:/# /usr/bin/python3-config --cflags
-I/usr/include/python3.5m -I/usr/include/python3.5m  -Wno-unused-result -Wsign-compare -g -fstack-protector-strong -Wformat -Werror=format-security  -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

Pass those flags to the compiler, and it will work.


问:
Create one nested object with two objects from dictionary
I'm not sure if the title of my question is the right description to the issue I'm facing.

I'm reading the following table of data from a spreadsheet and passing it as a dataframe:

```<code>Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8
</code>```

I need to transform this table of data to json following a specific schema.

I'm trying to get the following output:

```<code>{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': '8'}}
</code>```

So far I'm able to get the global and spec objects but I'm not sure how I should combine them to get the expected output above.

I wrote this:

```<code>for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            global = row.to_dict()
            spec = row.to_dict()

            del(global['Value'])
            del(spec['Name'])
            del(spec['Description'])
            print("global:", global)
            print("spec:", spec)
</code>```

with the following output:

```<code>global: {'Name': 'bar', 'Description': 'foofoo'}
spec: {'Value': '8'}
</code>```

How can I combine these two objects to get to the desired output?

答:
Try this and see if it works faster: slow speed might be due to iterrows. I suggest you move the iteration to the dictionary after exporting from the dataframe.

```<code>    Name    Description Value
0   foo foobar  5
1   baz foobaz  4
2   bar foofoo  8

#Export dataframe to dictionar, using the 'index' option
M = df.to_dict('index')

r = {}
q = []

#iterating through the dictionary items(key,value pair)
for i,j in M.items():

    #assign value to key 'global'

    r['global'] = j

    #popitem() works similarly to pop in list,
    #take out the last item
     #and remove it from parent dictionary
     #this nests the spec key, inside the global key

    r['global']['spec'] = dict([j.popitem()])

    #this ensures the dictionaries already present are not overriden
    #you could use copy or deep.copy to ensure same state

    q.append(dict(r))

{'global': {'Name': 'foo', 'Description': 'foobar', 'spec': {'Value': 5}}}
{'global': {'Name': 'baz', 'Description': 'foobaz', 'spec': {'Value': 4}}}
{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': 8}}}
</code>```

dict popitem

Body:
I'm not sure if the title of my question is the right description to the issue I'm facing.

I'm reading the following table of data from a spreadsheet and passing it as a dataframe:

Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8

I need to transform this table of data to json following a specific schema.

I'm trying to get the following output:

{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': '8'}}

So far I'm able to get the global and spec objects but I'm not sure how I should combine them to get the expected output above.

I wrote this:

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            global = row.to_dict()
            spec = row.to_dict()

            del(global['Value'])
            del(spec['Name'])
            del(spec['Description'])
            print("global:", global)
            print("spec:", spec)

with the following output:

global: {'Name': 'bar', 'Description': 'foofoo'}
spec: {'Value': '8'}

How can I combine these two objects to get to the desired output?

Body:
Try this and see if it works faster: slow speed might be due to iterrows. I suggest you move the iteration to the dictionary after exporting from the dataframe.

    Name    Description Value
0   foo foobar  5
1   baz foobaz  4
2   bar foofoo  8

#Export dataframe to dictionar, using the 'index' option
M = df.to_dict('index')

r = {}
q = []

#iterating through the dictionary items(key,value pair)
for i,j in M.items():

    #assign value to key 'global'

    r['global'] = j

    #popitem() works similarly to pop in list,
    #take out the last item
     #and remove it from parent dictionary
     #this nests the spec key, inside the global key

    r['global']['spec'] = dict([j.popitem()])

    #this ensures the dictionaries already present are not overriden
    #you could use copy or deep.copy to ensure same state

    q.append(dict(r))

{'global': {'Name': 'foo', 'Description': 'foobar', 'spec': {'Value': 5}}}
{'global': {'Name': 'baz', 'Description': 'foobaz', 'spec': {'Value': 4}}}
{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': 8}}}

dict popitem


问:
Cypress: How to wait and then read innertext of an element that will only appear somewhere between 30 seconds to 120 seconds
I have a requirement whereby once I sign-up for a user registration my ID gets generated in the back-end and the web page shows that ID nearly after somewhere between 30 seconds to 120 seconds.

So when I use:

```<code>cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
})
</code>```

I may not have it just after the sign-up is complete, so I need to wait in a loop check every 10 seconds or so until the User Id is displayed as part of the selector 'header > p'

Tried different looping logics etc., incl. wait and check, but due to async nature of the requests the variable scoping is not working for me, hence tried cy.wrap('false').as('found') and then tried to use that in cy.get(this.found), but once that i need to chain that into .then.

So is there an easy way to store a global variable value using command.js perhaps? Which I can update in

```<code>while(!variableFound) {
cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
    if(text.length > 0) {
        variableFound = true
    } else {
        variableFound = false
    }
})
}
</code>```

Finally tried the following code from a forum, even when User Id is available inside header>p tag it keeps failing to identify that.

```<code>    let found = false
    let count=0
    while (!found) {

        const nonExistent = Cypress.$('header > p')

        // this is always evaluating to 0 even when p is become available and contains has the text
        cy.log("Length: " + nonExistent.length)

        if (!nonExistent.length) {
            cy.visit("/profile/")
            found = false
            count=count+1
            cy.wait(5000)
            cy.visit("/dashboard/")

            if(count==18) {
                found = true
                cy.log('Element not found after 18 attempts.Exit from loop!!!')
            }
        } else {
            found = true
            cy.get('header > p').invoke('text').then((useridtext) => {
                cy.log("User Id: " + useridtext)
            })
        }
    }
</code>```

Any advise is sincerely appreciated. Many thanks.

答:
Thanks to both @RichardMatsen and Arnon Axelrod, below is the recursive function that works for me.

```<code>/* Recursive function */
function getEnvironment() {
    function getEnvironmentInternal(retires) {
        if (retires == 0) {
            throw "text didn't appear after the specified retires";
        }
        return cy.get('header > p').invoke('text').then(text => {
            if(text) {
                 return cy.wrap(text);
            }

            cy.wait(10000);
            cy.reload();
            return getEnvironmentInternal(retires-1);
        });
    }
    return getEnvironmentInternal(12);
 }

/* Usage */
getEnvironment().then(text => {
    cy.log("User Id: " + text);
});
</code>```

As at Nov 2020, this problem may be solved with Test Retries.

Body:
I have a requirement whereby once I sign-up for a user registration my ID gets generated in the back-end and the web page shows that ID nearly after somewhere between 30 seconds to 120 seconds.

So when I use:

cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
})

I may not have it just after the sign-up is complete, so I need to wait in a loop check every 10 seconds or so until the User Id is displayed as part of the selector 'header > p'

Tried different looping logics etc., incl. wait and check, but due to async nature of the requests the variable scoping is not working for me, hence tried cy.wrap('false').as('found') and then tried to use that in cy.get(this.found), but once that i need to chain that into .then.

So is there an easy way to store a global variable value using command.js perhaps? Which I can update in

while(!variableFound) {
cy.get('header > p').invoke('text').then('text' => {
    cy.log("User Id: " + text)
    if(text.length > 0) {
        variableFound = true
    } else {
        variableFound = false
    }
})
}

Finally tried the following code from a forum, even when User Id is available inside header>p tag it keeps failing to identify that.

    let found = false
    let count=0
    while (!found) {

        const nonExistent = Cypress.$('header > p')

        // this is always evaluating to 0 even when p is become available and contains has the text
        cy.log("Length: " + nonExistent.length)

        if (!nonExistent.length) {
            cy.visit("/profile/")
            found = false
            count=count+1
            cy.wait(5000)
            cy.visit("/dashboard/")

            if(count==18) {
                found = true
                cy.log('Element not found after 18 attempts.Exit from loop!!!')
            }
        } else {
            found = true
            cy.get('header > p').invoke('text').then((useridtext) => {
                cy.log("User Id: " + useridtext)
            })
        }
    }

Any advise is sincerely appreciated. Many thanks.

Body:
Thanks to both @RichardMatsen and Arnon Axelrod, below is the recursive function that works for me.

/* Recursive function */
function getEnvironment() {
    function getEnvironmentInternal(retires) {
        if (retires == 0) {
            throw "text didn't appear after the specified retires";
        }
        return cy.get('header > p').invoke('text').then(text => {
            if(text) {
                 return cy.wrap(text);
            }

            cy.wait(10000);
            cy.reload();
            return getEnvironmentInternal(retires-1);
        });
    }
    return getEnvironmentInternal(12);
 }

/* Usage */
getEnvironment().then(text => {
    cy.log("User Id: " + text);
});

As at Nov 2020, this problem may be solved with Test Retries.


问:
Can't read data that send from controller to view by foreach
The $results that send to the view is undefined

```<code>public function action(){
        // if($this->input->post('data_action'))
        // {
        //  $data_action = $this->input->post('data_action');
        //  if($data_action=="fetch_all")
        //  {
                $api_url = "https://jsonplaceholder.typicode.com/users";

                $process = curl_init($api_url); //your API url
                curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
                $return = curl_exec($process);
                curl_close($process);
                $results=json_decode($return);
                //finally print your API response

                $this->load->view('masterPartner',$results);
                //print_r($result);
            //  }
            // }
</code>```

and this is the view

```<code><?php foreach($results as $result)
                      { ?>
                        <tr>
                        <th scope="row"><?php echo $result->id ?></th>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td><a class="btn btn-success " style="margin-right:5px"href="/Crudview/index.php/edit-partner" role="button">Edit</a><a class="btn btn-danger" href="/Crudview/index.php/viewApi" role="button">Delete</a>
                        </tr>
                        <?php } ?>
</code>```

the first error

A PHP Error was encountered Severity: Notice

Message: Undefined variable: results

Filename: views/masterPartner.php

Line Number: 115

Second error

A PHP Error was encountered Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/masterPartner.php

Line Number: 115

答:
It is because $results does not exist in the view. It is expecting $results to be passed in via an array.

To pass that in you would need to change your current code

From

```<code>$results=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$results);
</code>```

To

```<code>$data['results']=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$data);
</code>```

So now $results is accessible in your view.

Body:
The $results that send to the view is undefined

public function action(){
        // if($this->input->post('data_action'))
        // {
        //  $data_action = $this->input->post('data_action');
        //  if($data_action=="fetch_all")
        //  {
                $api_url = "https://jsonplaceholder.typicode.com/users";

                $process = curl_init($api_url); //your API url
                curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
                $return = curl_exec($process);
                curl_close($process);
                $results=json_decode($return);
                //finally print your API response

                $this->load->view('masterPartner',$results);
                //print_r($result);
            //  }
            // }

and this is the view

<?php foreach($results as $result)
                      { ?>

                        <?php echo $result->id ?>

                        EditDelete

                        <?php } ?>

the first error

A PHP Error was encountered Severity: Notice

Message: Undefined variable: results

Filename: views/masterPartner.php

Line Number: 115

Second error

A PHP Error was encountered Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/masterPartner.php

Line Number: 115

Body:
It is because $results does not exist in the view. It is expecting $results to be passed in via an array.

To pass that in you would need to change your current code

From

$results=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$results);

To

$data['results']=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$data);

So now $results is accessible in your view.


问:
Office Interop Excel in a worker thread?
I'm exporting data form my C# application to an Excel file using Office Interop. Everything works fine, but the exports can be quite large and take some time to complete. I've searched around on the web and MSDN but haven't found much on running Interop calls in a thread. Are there any reasons I shouldn't put the export to Excel functionality into a background worker thread?</p>

答: So long as you're only calling into the Excel application from one thread, I don't expect that you would have any problems. I have written an application that automates Excel on a background worker thread in the same way you describe.</p>


问:
Check if Two Values Share a Row Anywhere on an Entire Sheet in Excel
I need to return a Boolean (or count) if two values share 1 row (or more) on an entire page.

The two values could be in any order on that row.
They are not neatly organized in static, predictable columns.

So if we have cells containing:

```<code>abc 111 ghi
ghi 222 abc
jlk 333 xyz
</code>```

I want it to return "true" (or 2, since there are 2 shared rows) when I check for "abc AND ghi".
Similarly, a check for "jlk AND xyz" would return 1/true.

But if I was to check for "111 and 222" it would return 0/False, because they do not share a row.

I've found good support for sumproduct() and countifs() methods to do this, but the techniques were difficult to adapt to an entire page that does not have information organized in predictable columns.

答:
You can use following array formula:

```<code>{=SUM(--(MMULT(($A$1:$D$3=$F$2)+($A$1:$D$3=$G$2),TRANSPOSE(COLUMN($A$1:$D$1)^0))>1))}
</code>```

Array formula after editing is confirmed by pressing ctrl + shift + enter

Edit 2:

To count only if both values are in the same row regardless of number.

```<code>{=SUM(--(MMULT(--($A$1:$D$3=$F$2);TRANSPOSE(COLUMN($A$1:$D$1)^0))>0)*(MMULT(--($A$1:$D$3=$G$2);TRANSPOSE(COLUMN($A$1:$D$1)^0))>0))}
</code>```

Body:
I need to return a Boolean (or count) if two values share 1 row (or more) on an entire page.

The two values could be in any order on that row.
They are not neatly organized in static, predictable columns.

So if we have cells containing:

abc 111 ghi
ghi 222 abc
jlk 333 xyz

I want it to return "true" (or 2, since there are 2 shared rows) when I check for "abc AND ghi".
Similarly, a check for "jlk AND xyz" would return 1/true.

But if I was to check for "111 and 222" it would return 0/False, because they do not share a row.

I've found good support for sumproduct() and countifs() methods to do this, but the techniques were difficult to adapt to an entire page that does not have information organized in predictable columns.

Body:
You can use following array formula:

{=SUM(--(MMULT(($A$1:$D$3=$F$2)+($A$1:$D$3=$G$2),TRANSPOSE(COLUMN($A$1:$D$1)^0))>1))}

Array formula after editing is confirmed by pressing ctrl + shift + enter

Edit 2:

To count only if both values are in the same row regardless of number.

{=SUM(--(MMULT(--($A$1:$D$3=$F$2);TRANSPOSE(COLUMN($A$1:$D$1)^0))>0)*(MMULT(--($A$1:$D$3=$G$2);TRANSPOSE(COLUMN($A$1:$D$1)^0))>0))}