问:
GLIBC malloc implementation bookkeeping
I'm trying to understand how exactly glibc's malloc does its bookkeeping on my 64-bit machine.

According to the documentation it stores the actual size(the malloc value plus the bookkepping bytes)  right before the chunk. So I took the following code from here:

```<code>int *a = (int *) malloc(4);
int *b = (int *) malloc(7);
int *c = (int *) malloc(1);
int *d = (int *) malloc(32);
int *e = (int *) malloc(4);

printf("0x%x\n", a);
printf("0x%x\n", b);
printf("0x%x\n", c);
printf("0x%x\n", d);
printf("0x%x\n", e);

printf("a[-1] = %d, a[-2] = %d\n", a[-1], a[-2]);
printf("b[-1] = %d, b[-2] = %d\n", b[-1], b[-2]);
printf("c[-1] = %d, c[-2] = %d\n", c[-1], c[-2]);
printf("d[-1] = %d, d[-2] = %d\n", d[-1], d[-2]);
printf("e[-1] = %d, e[-2] = %d\n", e[-1], e[-2]);
</code>```

which yields:

```<code>0xfca042a0
0xfca042c0
0xfca042e0
0xfca04300
0xfca04330

a[-1] = 0, a[-2] = 33 // letter[-2] is how much memory malloc has actually allocated
b[-1] = 0, b[-2] = 33
c[-1] = 0, c[-2] = 33
d[-1] = 0, d[-2] = 49
e[-1] = 0, e[-2] = 33
</code>```

So you can see that the first three addresses are 32 bytes apart, that makes sense since the smallest chunk malloc allocates is 32 or rather 4 * sizeof(void*). However when I allocate 32 bytes the next chunk is 48 bytes away and not 64, why is that?

And if malloc has allocated 32 and 48 bytes why is it printing 33 and 49 respectively?

答:
The internal glibc representation of a chunk is the following structure:

```<code>struct malloc_chunk {
    INTERNAL_SIZE_T      mchunk_prev_size;  /* Size of previous chunk (if free).  */
    INTERNAL_SIZE_T      mchunk_size;       /* Size in bytes, including overhead. */
    struct malloc_chunk* fd;                /* double links -- used only if free. */
    struct malloc_chunk* bk;
    /* Only used for large blocks: pointer to next larger size.  */
    struct malloc_chunk* fd_nextsize;       /* double links -- used only if free. */
    struct malloc_chunk* bk_nextsize;
};
</code>```

Every field except mchunk_prev_size and mchunk_size is only populated if the chunk is free. Those two fields are right before the user usable buffer. The mchunk_prev_size field holds the size of the previous chunk (only if it's free), while the mchunk_size field always holds the real size of the chunk (which is at least 16 bytes more than the requested size). Furthermore, in order to save space, the mchunk_prev_size field can actually resides inside the previous chunk (since it's free).

Chunks are always aligned to 16 bytes boundaries (i.e., their hexadecimal address always ends with a 0). The minimum allocation size is 16 (requests for smaller sizes are just rounded up to 16), and there always need to be 16 additional bytes for mchunk_prev_size and mchunk_size (8 bytes each).

So now you can probably guess the answer to your first question:

[...] the smallest chunk malloc allocates is 32 or rather 4 * sizeof(void*). However when I allocate 32 bytes the next chunk is 48 bytes away and not 64, why is that?

Well, yes, the smallest chunk size is 32, but the increment is actually 16. You can therefore have any size which is multiple of 16 and is above or equal to 32. If you request a size between 17 and 32 you will get a chunk of 48 bytes (32 of which are usable for user data). Furthermore, the minimum malloc allocation size doesn't have much to do with sizeof(void *), it's more related to sizeof(size_t) really (as your link also notes).

The state of the heap after the allocations in your example is the following:

      +-----------+ 0xfca04290
      | prev size |
      |-----------|
      | size      |
a --> |-----------| 0xfca042a0
      | user data |
      |           |
      +-----------+ 0xfca042b0
      | prev size |
      |-----------|
      | size      |
b --> |-----------| 0xfca042c0
      | user data |
      |           |
      +-----------+ 0xfca042d0
      | prev size |
      |-----------|
      | size      |
c --> |-----------| 0xfca042e0
      | user data |
      |           |
      +-----------+ 0xfca042f0
      | prev size |
      |-----------|
      | size      |
d --> |-----------| 0xfca04300
      | user data |
      |           |
      |           |
      |           |
      +-----------+ 0xfca04320
      | prev size |
      |-----------|
      | size      |
e --> |-----------| 0xfca04330
      | user data |
      |           |
      +-----------+
```
<hr />
<p>One thing that isn't not clear from the above diagram is the fact that, as explained above, <code>mchunk_prev_size</code> can actually reside inside the previous chunk to save space.</p>
<p>To further clarify this, we can also take a look at the heap layout after executing the following code:</p>
<pre class="lang-c prettyprint-override"><code>void *a = malloc(24); // 0x123400a0
void *b = malloc(16); // 0x123400c0
</code>```

For both a and b, the mchunk_size will be 32. The mchunk_prev_size of b will overlap with the last 8 bytes of a. Both chunks will nonetheless be aligned to 16 bytes.

      +-----------------------+ 0x12340090
      | prev size             |
      |-----------------------|
      | size                  |
a --> |-----------------------| 0x123400a0
      | user data             |
      |                       |
      +-----------------------+ 0x123400b0
      | user data / prev size |
      +-----------------------+ 0x123400b8
      | size                  |
b --> |-----------------------| 0x123400c0
      | user data             |
      |                       |
      +-----------------------+ 0x123400d0
```
<p>Without making the <code>mchunk_prev_size</code> field of <code>b</code> overlap with the last 8 bytes of <code>a</code>, in order to keep the alignment of 16 bytes, some empty space would need to be left between the end of <code>a</code> and the start of <code>b</code> (exactly 8 bytes), and this space would be wasted.</p>
<hr />
<p>Now, coming to the second question:</p>
<blockquote>
<p>And if malloc has allocated 32 and 48 bytes why is it printing 33 and 49 respectively?</p>
</blockquote>
<p>Since every chunk must have a size multiple of 16 bytes, the lowest 4 bits of the size (one hexadecimal digit) would remain unused. <code>malloc</code> saves space and uses those to store additional information about the chunk. The last 3 bits are actually flags for <code>malloc</code>'s internal usage. This is explained in source code comments as well:</p>
<pre class="lang-none prettyprint-override"><code>chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             Size of previous chunk, if unallocated (P clear)  |
        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             Size of chunk, in bytes                     |A|M|P| <== flags
  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             User data starts here...                          |
</code>```

Those flag bits A|M|P are:

A: non main arena chunk.

M: chunk is mmaped.

P: previous chunk is in use (i.e. not free).

You can find a more thorough explanation of the above right in the malloc source code.

Since all of your chunks are still in use, in the size field you see size | PREV_IN_USE. Since the "previous in use" (P) is the least significant bit, this has the effect of incrementing the value of the size by 1, so you see 33 instead of 32 for example.

Some additional notes:

Don't cast the return value of malloc.

If you want to inspect the size of a chunk you should use size_t instead of int, like this:

```<code>  void *a = malloc(32);
  size_t *ptr = a;
  size_t chunk_size = ptr[-1] & ~0x7; // Strip the A|M|P flags from the size.
</code>```

Keep in mind that this chunk_size is the internal size of the chunk, not the usable user size (which is 32).

Last but not least: the correct format specifier for pointers for printf is %p, not %x (and it should also already include the leading 0x):

```<code>  printf("%p\n", a);
</code>```

Title: GLIBC malloc implementation bookkeeping

Body:
I'm trying to understand how exactly glibc's malloc does its bookkeeping on my 64-bit machine.

According to the documentation it stores the actual size(the malloc value plus the bookkepping bytes)  right before the chunk. So I took the following code from here:

int *a = (int *) malloc(4);
int *b = (int *) malloc(7);
int *c = (int *) malloc(1);
int *d = (int *) malloc(32);
int *e = (int *) malloc(4);

printf("0x%x\n", a);
printf("0x%x\n", b);
printf("0x%x\n", c);
printf("0x%x\n", d);
printf("0x%x\n", e);

printf("a[-1] = %d, a[-2] = %d\n", a[-1], a[-2]);
printf("b[-1] = %d, b[-2] = %d\n", b[-1], b[-2]);
printf("c[-1] = %d, c[-2] = %d\n", c[-1], c[-2]);
printf("d[-1] = %d, d[-2] = %d\n", d[-1], d[-2]);
printf("e[-1] = %d, e[-2] = %d\n", e[-1], e[-2]);

which yields:

0xfca042a0
0xfca042c0
0xfca042e0
0xfca04300
0xfca04330

a[-1] = 0, a[-2] = 33 // letter[-2] is how much memory malloc has actually allocated
b[-1] = 0, b[-2] = 33
c[-1] = 0, c[-2] = 33
d[-1] = 0, d[-2] = 49
e[-1] = 0, e[-2] = 33

So you can see that the first three addresses are 32 bytes apart, that makes sense since the smallest chunk malloc allocates is 32 or rather 4 * sizeof(void*). However when I allocate 32 bytes the next chunk is 48 bytes away and not 64, why is that?

And if malloc has allocated 32 and 48 bytes why is it printing 33 and 49 respectively?

Body:
The internal glibc representation of a chunk is the following structure:

struct malloc_chunk {
    INTERNAL_SIZE_T      mchunk_prev_size;  /* Size of previous chunk (if free).  */
    INTERNAL_SIZE_T      mchunk_size;       /* Size in bytes, including overhead. */
    struct malloc_chunk* fd;                /* double links -- used only if free. */
    struct malloc_chunk* bk;
    /* Only used for large blocks: pointer to next larger size.  */
    struct malloc_chunk* fd_nextsize;       /* double links -- used only if free. */
    struct malloc_chunk* bk_nextsize;
};

Every field except mchunk_prev_size and mchunk_size is only populated if the chunk is free. Those two fields are right before the user usable buffer. The mchunk_prev_size field holds the size of the previous chunk (only if it's free), while the mchunk_size field always holds the real size of the chunk (which is at least 16 bytes more than the requested size). Furthermore, in order to save space, the mchunk_prev_size field can actually resides inside the previous chunk (since it's free).

Chunks are always aligned to 16 bytes boundaries (i.e., their hexadecimal address always ends with a 0). The minimum allocation size is 16 (requests for smaller sizes are just rounded up to 16), and there always need to be 16 additional bytes for mchunk_prev_size and mchunk_size (8 bytes each).

So now you can probably guess the answer to your first question:

[...] the smallest chunk malloc allocates is 32 or rather 4 * sizeof(void*). However when I allocate 32 bytes the next chunk is 48 bytes away and not 64, why is that?

Well, yes, the smallest chunk size is 32, but the increment is actually 16. You can therefore have any size which is multiple of 16 and is above or equal to 32. If you request a size between 17 and 32 you will get a chunk of 48 bytes (32 of which are usable for user data). Furthermore, the minimum malloc allocation size doesn't have much to do with sizeof(void *), it's more related to sizeof(size_t) really (as your link also notes).

The state of the heap after the allocations in your example is the following:

      +-----------+ 0xfca04290
      | prev size |
      |-----------|
      | size      |
a --> |-----------| 0xfca042a0
      | user data |
      |           |
      +-----------+ 0xfca042b0
      | prev size |
      |-----------|
      | size      |
b --> |-----------| 0xfca042c0
      | user data |
      |           |
      +-----------+ 0xfca042d0
      | prev size |
      |-----------|
      | size      |
c --> |-----------| 0xfca042e0
      | user data |
      |           |
      +-----------+ 0xfca042f0
      | prev size |
      |-----------|
      | size      |
d --> |-----------| 0xfca04300
      | user data |
      |           |
      |           |
      |           |
      +-----------+ 0xfca04320
      | prev size |
      |-----------|
      | size      |
e --> |-----------| 0xfca04330
      | user data |
      |           |
      +-----------+

One thing that isn't not clear from the above diagram is the fact that, as explained above, mchunk_prev_size can actually reside inside the previous chunk to save space.

To further clarify this, we can also take a look at the heap layout after executing the following code:

void *a = malloc(24); // 0x123400a0
void *b = malloc(16); // 0x123400c0

For both a and b, the mchunk_size will be 32. The mchunk_prev_size of b will overlap with the last 8 bytes of a. Both chunks will nonetheless be aligned to 16 bytes.

      +-----------------------+ 0x12340090
      | prev size             |
      |-----------------------|
      | size                  |
a --> |-----------------------| 0x123400a0
      | user data             |
      |                       |
      +-----------------------+ 0x123400b0
      | user data / prev size |
      +-----------------------+ 0x123400b8
      | size                  |
b --> |-----------------------| 0x123400c0
      | user data             |
      |                       |
      +-----------------------+ 0x123400d0

Without making the mchunk_prev_size field of b overlap with the last 8 bytes of a, in order to keep the alignment of 16 bytes, some empty space would need to be left between the end of a and the start of b (exactly 8 bytes), and this space would be wasted.

Now, coming to the second question:

And if malloc has allocated 32 and 48 bytes why is it printing 33 and 49 respectively?

Since every chunk must have a size multiple of 16 bytes, the lowest 4 bits of the size (one hexadecimal digit) would remain unused. malloc saves space and uses those to store additional information about the chunk. The last 3 bits are actually flags for malloc's internal usage. This is explained in source code comments as well:

chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             Size of previous chunk, if unallocated (P clear)  |
        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             Size of chunk, in bytes                     |A|M|P| <== flags
  mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        |             User data starts here...                          |

Those flag bits A|M|P are:

A: non main arena chunk.

M: chunk is mmaped.

P: previous chunk is in use (i.e. not free).

You can find a more thorough explanation of the above right in the malloc source code.

Since all of your chunks are still in use, in the size field you see size | PREV_IN_USE. Since the "previous in use" (P) is the least significant bit, this has the effect of incrementing the value of the size by 1, so you see 33 instead of 32 for example.

Some additional notes:

Don't cast the return value of malloc.

If you want to inspect the size of a chunk you should use size_t instead of int, like this:

  void *a = malloc(32);
  size_t *ptr = a;
  size_t chunk_size = ptr[-1] & ~0x7; // Strip the A|M|P flags from the size.

Keep in mind that this chunk_size is the internal size of the chunk, not the usable user size (which is 32).

Last but not least: the correct format specifier for pointers for printf is %p, not %x (and it should also already include the leading 0x):

  printf("%p\n", a);


来源: stackexchange

问:
How would I get the text of a JLabel (with an icon) explaining what the label is by hovering over the label?
I want to see the text of JLabel when I hover over the label. The text explains what the label does in detail.</p>

答:
You would need to set the text of the tooltip by calling: setToolTipText()

More about tooltips in the tutorial: http://download.oracle.com/javase/tutorial/uiswing/components/tooltip.html

ContentLicense: CC BY-SA 3.0


问:
How to plot a line using Canvas/Matplotlib?
I am trying to plot a line using canvas and matplotlib.

I already have the Figure, and everything else. But when i try to use the command to plot(self.axes.plot()) it does not work.

Does anyone knows what is happening?? Probably there is some detail that i am missing, but i can't find it!!

```<code>import sys
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import pyplot as plt

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Plotting")
        self.setGeometry(50, 50, 700, 700)
        self.UI()
        self.show()

    def UI(self):
        # Cria o canvas para exibição dos entes da estrutura ------------------
        self.dpi = 70
        self.fig = Figure((5.0, 5.0), dpi=self.dpi, frameon=False, tight_layout=True)
        self.canvas = FigureCanvas(self.fig)
        self.axes = self.fig.add_subplot(111)

        # Cria grid de plotagem (axes) ----------------------------------------
        self.load_axes()

        layout = QGridLayout()

        layout.addWidget(self.canvas, 0, 0)

        self.setLayout(layout)

        self.plotar()

    def plotar(self):
        self.axes.clear()
        self.load_axes()
        self.axes.plot([0, 0], [1, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

        # Define a área de plotagem -------------------------------------------
        self.axes.relim()
        # Plota todas as linhas no canvas -------------------------------------
        self.fig.canvas.draw()

    def load_axes(self):
        self.axes.axis('equal')
        self.axes.set_xmargin(.4)
        self.axes.set_ymargin(.4)
        self.axes.autoscale_view(tight=True)
        self.axes.xaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.xaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.yaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.yaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='x', linewidth=0.50, linestyle='-', color='gainsboro')
        self.axes.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='y', linewidth=0.50, linestyle='-', color='gainsboro')

def main():
    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec_())

if __name__=='__main__':
    main()

</code>```

答:
It looks like it's actually drawing fine, no problem, but there is an issue with the ranges that you've specified for the axis.

You've specified:
self.axes.plot([0, 0], [1, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

which means you're asking the x axis to display a range of 0 to 0 and the y axis to display 1 to 1.  Try changing it to this:

self.axes.plot([0, 1], [0, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

That should display your line! :-D

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot a line using canvas and matplotlib.

I already have the Figure, and everything else. But when i try to use the command to plot(self.axes.plot()) it does not work.

Does anyone knows what is happening?? Probably there is some detail that i am missing, but i can't find it!!

import sys
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import pyplot as plt

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Plotting")
        self.setGeometry(50, 50, 700, 700)
        self.UI()
        self.show()

    def UI(self):
        # Cria o canvas para exibição dos entes da estrutura ------------------
        self.dpi = 70
        self.fig = Figure((5.0, 5.0), dpi=self.dpi, frameon=False, tight_layout=True)
        self.canvas = FigureCanvas(self.fig)
        self.axes = self.fig.add_subplot(111)

        # Cria grid de plotagem (axes) ----------------------------------------
        self.load_axes()

        layout = QGridLayout()

        layout.addWidget(self.canvas, 0, 0)

        self.setLayout(layout)

        self.plotar()

    def plotar(self):
        self.axes.clear()
        self.load_axes()
        self.axes.plot([0, 0], [1, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

        # Define a área de plotagem -------------------------------------------
        self.axes.relim()
        # Plota todas as linhas no canvas -------------------------------------
        self.fig.canvas.draw()

    def load_axes(self):
        self.axes.axis('equal')
        self.axes.set_xmargin(.4)
        self.axes.set_ymargin(.4)
        self.axes.autoscale_view(tight=True)
        self.axes.xaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.xaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.yaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.yaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='x', linewidth=0.50, linestyle='-', color='gainsboro')
        self.axes.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='y', linewidth=0.50, linestyle='-', color='gainsboro')

def main():
    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec_())

if __name__=='__main__':
    main()


问:
VBA - looking for solution to my simple dynamic looping sum calculation
I'm a novice trying to learn VBA. I've got a looping question: I have a simple set of numbers that are grouped in rows of three. I'm hoping to sum them up individually in column f. How could I create a dynamic range in order to loop through these to get the totals?

layout and workings are below - I don't think I have my dynamic range formula correct either. Any help is gratefully appreciated:

basic test data

```<code>Sub testing1000b()

Dim rng As Range
Dim lAnswer As Long
Dim lastrow As Long
Dim firstrow As Long

Dim addrow As Long

Range("e:f").ClearContents
addrow = 6
firstrow = Range("b" & addrow).Row
lastrow = Range("b" & firstrow).End(xlDown).Row
Range("b & firstrow" & "b & lastrow") = rng
lAnswer = WorksheetFunction.Sum(rng)
Range("f6").Value = lAnswer

End Sub
</code>```

答:
Sum Up Consecutive Cells

Sub SumConsecutive()

    Const SourceCol As Long = 2
    Const ResultCol As Long = 6
    Const InitialRow As Long = 6
    Const Consecutive As Long = 3

    Dim rng As Range
    Dim FirstRow As Long
    Dim LastRow As Long
    Dim Result As Long
    Dim RowDiff As Long

    Columns(ResultCol).ClearContents

    FirstRow = InitialRow
    LastRow = Cells(FirstRow, SourceCol).End(xlDown).Row
    RowDiff = LastRow - FirstRow

    Do Until RowDiff <> Consecutive - 1
        Set rng = Range(Cells(FirstRow, SourceCol), Cells(LastRow, SourceCol))
        Result = WorksheetFunction.Sum(rng)
        Cells(FirstRow, ResultCol).Value = Result
        FirstRow = Cells(LastRow, SourceCol).End(xlDown).Row
        LastRow = Cells(FirstRow, SourceCol).End(xlDown).Row
        RowDiff = LastRow - FirstRow
    Loop

    MsgBox "Done"

End Sub
```

Body:
I'm a novice trying to learn VBA. I've got a looping question: I have a simple set of numbers that are grouped in rows of three. I'm hoping to sum them up individually in column f. How could I create a dynamic range in order to loop through these to get the totals?

layout and workings are below - I don't think I have my dynamic range formula correct either. Any help is gratefully appreciated:

basic test data

Sub testing1000b()

Dim rng As Range
Dim lAnswer As Long
Dim lastrow As Long
Dim firstrow As Long

Dim addrow As Long

Range("e:f").ClearContents
addrow = 6
firstrow = Range("b" & addrow).Row
lastrow = Range("b" & firstrow).End(xlDown).Row
Range("b & firstrow" & "b & lastrow") = rng
lAnswer = WorksheetFunction.Sum(rng)
Range("f6").Value = lAnswer

End Sub


问:
Overlay Image over view corner
I am attempting to draw the medal overlaying the corner of the score screen shown here

There is an transparent layout holding the buttons and a RelativeLayout (black edge box), which holds the interior box (grey box) that contains the rest of the data. I tried adding the medal to the top left corner of the interior RelativeLayout and giving it negative margins, but that just cuts it off at the edge of the view. Adding it to the transparent layout puts it behind the corner.

How can I force the medal to overlay that corner? I'd prefer to do it in xml if possible, but any suggestions are welcome.

答:
In the xml layout, an element that define after will overlay the element that define before.
So, you could change layout to something like this:</p>

```<code><LinearLayout>

<LinearLayout> <!--grey box --> </LinearLayout>

<ImageView src="medal" android:layout_marginLeft="-250dip"/>
<!-- change the amount of marginLeft to your desire -->

</LinearLayout>
</code>```

Title: Overlay Image over view corner

Body:
In the xml layout, an element that define after will overlay the element that define before.
So, you could change layout to something like this:

<LinearLayout>

<LinearLayout> <!--grey box --> </LinearLayout>

<ImageView src="medal" android:layout_marginLeft="-250dip"/>
<!-- change the amount of marginLeft to your desire -->

</LinearLayout>


问:
Flask/Python - How can I run this python script in Flask and render output in html page
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')
```

<hr>

<p>melhor.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')
</code>```

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')
```

<hr>

<p>indicator.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)
</code>```

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)
```

Thanks for your attention.

答:
Here are some examples for you to follow :

https://www.grizzlypeaksoftware.com/articles?id=1m3W3llyJLy4YS5OpyyxBq

https://scotch.io/tutorials/getting-started-with-flask-a-python-microframework

https://scoutapm.com/blog/python-flask-tutorial-getting-started-with-flask

https://www.liquidweb.com/kb/getting-started-with-flask/

https://github.com/akibrhast/flask_base_template

Basically what you need to learn about is how to create a backend server. In this case using flask. The templating engine that is typically used with flask is called Jinja. Once you make your request call to your data you would want to pass it through to your routes via jinja.

Here is a basic example:

```<code>from flask import Flask, flash, redirect, render_template, request, session, abort,url_for
import os

#from flask_login import login_user, current_user, logout_user, login_required #Optional login imports, need to 'pip install flask_login'

app = Flask(__name__)

@app.route('/')
def index():
  return render_template("base.html")

if __name__ == '__main__':
    app.secret_key = os.urandom(12)
    app.run(debug=True)
</code>```

Body:
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')

melhor.py

import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')

indicator.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)

Thanks for your attention.

Body:
Here are some examples for you to follow :

https://www.grizzlypeaksoftware.com/articles?id=1m3W3llyJLy4YS5OpyyxBq

https://scotch.io/tutorials/getting-started-with-flask-a-python-microframework

https://scoutapm.com/blog/python-flask-tutorial-getting-started-with-flask

https://www.liquidweb.com/kb/getting-started-with-flask/

https://github.com/akibrhast/flask_base_template

Basically what you need to learn about is how to create a backend server. In this case using flask. The templating engine that is typically used with flask is called Jinja. Once you make your request call to your data you would want to pass it through to your routes via jinja.

Here is a basic example:

from flask import Flask, flash, redirect, render_template, request, session, abort,url_for
import os

#from flask_login import login_user, current_user, logout_user, login_required #Optional login imports, need to 'pip install flask_login'

app = Flask(__name__)

@app.route('/')
def index():
  return render_template("base.html")

if __name__ == '__main__':
    app.secret_key = os.urandom(12)
    app.run(debug=True)


问:
Sum is not being defined as a sum
I'm beginning to learn coding on vscode with python and my code is this and it stacks the numbers.

```<code>num1 = input("Enter the first number:")

num2 = input("Enter the second number:")

sum = num1 + num2

print(sum)
</code>```

and my terminal is

```<code>Enter the first number:10

Enter the second number:10
1010
PS C:\Users\Big Chungus\Desktop\python>
</code>```

答:
When you take an input from the user, it takes as a string.

To check the type, do this..

```<code>print(type(num1))
print(type(num2))
</code>```

you will get

```<code><class 'str'>
<class 'str'>
</code>```

Strings cant be added but can be joined, thats why your answer was 1010.

If you want to add then numbers taken from the user, then you will need an int...

```<code>num1 = ("Enter the first number: ")
num2 = ("Enter the second number: ")

sum = int(num1)+int(num2)
print(sum)
</code>```

Title: Sum is not being defined as a sum

Body:
I'm beginning to learn coding on vscode with python and my code is this and it stacks the numbers.

num1 = input("Enter the first number:")

num2 = input("Enter the second number:")

sum = num1 + num2

print(sum)

and my terminal is

Enter the first number:10

Enter the second number:10
1010
PS C:\Users\Big Chungus\Desktop\python>

Body:
When you take an input from the user, it takes as a string.

To check the type, do this..

print(type(num1))
print(type(num2))

you will get

<class 'str'>
<class 'str'>

Strings cant be added but can be joined, thats why your answer was 1010.

If you want to add then numbers taken from the user, then you will need an int...

num1 = ("Enter the first number: ")
num2 = ("Enter the second number: ")

sum = int(num1)+int(num2)
print(sum)


问:
How to deploy a spring web application to an apache web server
So I'm a complete beginner(started programming 4 months ago) so bear with me please, i have this spring web application with an apache tomcat web server auto installed with it, and it's working quite fine in a local host. </p>

<p>I've bought a server a few days ago and installed the apache2 web server on it, and am currently trying to figure out how to configure my spring application to work as the controller handling any request that's sent to the server, but don't seem to find anything. </p>

答: You need to configure a proxy (usually mod_proxy), take a look at this</p>

Body:
So I'm a complete beginner(started programming 4 months ago) so bear with me please, i have this spring web application with an apache tomcat web server auto installed with it, and it's working quite fine in a local host.

I've bought a server a few days ago and installed the apache2 web server on it, and am currently trying to figure out how to configure my spring application to work as the controller handling any request that's sent to the server, but don't seem to find anything.


问:
React Hook to find user
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

```<code>import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>
    </div>
  );
}

export default App;
</code>```

CardList.js

```<code>import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (
    <div>
    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };
  </div> )
}

export default CardList;
</code>```

Card.js

```<code>import React from 'react';
import 'tachyons';

function Card(props) {
  return (
    <div className='bg-light-green dib br3 pa3 ma2 grow shadow-5'>
      <img src={`https://robohash.org/${props.id}`} alt="Robot" />
      <h2>{props.name}</h2>
      <p>{props.email}</p>
    </div>
  );
}

export default Card;
</code>```

答:
In your App.js file, the searchInput is not being set to the state

```<code>import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSearchInput] = useState('');

  function onSearchChange(e) {
    setSearchInput(e.target.value)

  }
    **You can pass the filterRobots in place of robots to get only words passed in the search box**

 const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList robots={filteredRobots}/>
    </div>
  );
}

export default App;
</code>```

In the CardList File

```<code>import React from 'react';
import Card from './Card';

 function CardList({robots}) {
  {
    robots.map((user, i) => {
      return (
        <Card
          key={i}
          id={user[i].id}
          name={user[i].name}
          email={user[i].email}
          />
      );
    })
  }
}

export default CardList;
</code>```

Title: React Hook to find user

Body:
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (

RoboFriends

      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>

  );
}

export default App;

CardList.js

import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (

    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };

 )
}

export default CardList;

Card.js

import React from 'react';
import 'tachyons';

function Card(props) {
  return (

      <img src={`https://robohash.org/${props.id}`} alt="Robot" />

{props.name}

{props.email}

  );
}

export default Card;

Body:
In your App.js file, the searchInput is not being set to the state

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSearchInput] = useState('');

  function onSearchChange(e) {
    setSearchInput(e.target.value)

  }
    **You can pass the filterRobots in place of robots to get only words passed in the search box**

 const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList robots={filteredRobots}/>
    </div>
  );
}

export default App;

In the CardList File

import React from 'react';
import Card from './Card';

 function CardList({robots}) {
  {
    robots.map((user, i) => {
      return (
        <Card
          key={i}
          id={user[i].id}
          name={user[i].name}
          email={user[i].email}
          />
      );
    })
  }
}

export default CardList;


问:
Ionic Capacitor app give me lots of errors
I'm on Windows 10 and I've created a Ionic 5.0.7 app with Capacitor 2.0.0.

I use this command to build app:

```<code>ionic build
</code>```

After, I use this command:

```<code>npx cap sync
</code>```

And, to finish, I use this command to open Android Studio:

```<code>npx cap open android
</code>```

The first problem come during building on Android Studio:

org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

Caused by: org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

And...

java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

Caused by: java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

I've other random errors... It's weird...

答:
This issue has been resolved in Capacitor version 2.1.2.

https://github.com/ionic-team/capacitor/issues/3003

Please update the Capacitor dependencies in package.json to version 2.1.2 and then in Android Studio click the button to sync the project with Gradle.

```<code>"@capacitor/android": "^2.1.2",
"@capacitor/core": "2.1.2",
</code>```

Body:
I'm on Windows 10 and I've created a Ionic 5.0.7 app with Capacitor 2.0.0.

I use this command to build app:

ionic build

After, I use this command:

npx cap sync

And, to finish, I use this command to open Android Studio:

npx cap open android

The first problem come during building on Android Studio:

org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

Caused by: org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

And...

java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

Caused by: java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

I've other random errors... It's weird...

Body:
This issue has been resolved in Capacitor version 2.1.2.

https://github.com/ionic-team/capacitor/issues/3003

Please update the Capacitor dependencies in package.json to version 2.1.2 and then in Android Studio click the button to sync the project with Gradle.

"@capacitor/android": "^2.1.2",
"@capacitor/core": "2.1.2",


问:
How do I determine the number of lines of text that will fit into a browser window
I want to display enough lines of text to fill the current size of the browser window.
Also, I'd like to update the value if the browser window changes size. Does javascript have the equivalent of SIGWINCH?

Thanks

答: I am not familiar with SIGWINCH, so I can't say there is no equivalent. What I do know is that you can't simply have javascript return the amount of text lines left on a page. This is simply because every font has (/ can have) a different height. What you need to do is 1) fetch a user's window height, 2) generate a span or div with a piece of text in it (the whole character set would be most conclusive, if you have enough width), 3) fetch the height of that div/ span to determine the height of the font 4) remove the sample span/ div 5) divide and floor the window height by the font height. And when the user changes the window's dimension, do the whole procedure again (window size changes can be noticed through the window.onresize even listener). You can of course save yourself some time by storing the font height after you have determined it the first time, though depending on how you write your function, that shouldn't really matter.</p>


问:
Firebase RTDB Flutter app: Multiple Databases
So, I am using the Blaze plan in Firebase and I have multiple realtime databases. I was wondering how I can connect to a specific one through my Flutter app.

FirebaseDatabase.instance.reference(); connects me to the default database, but how can I connect to another one?

答:
Using FirebaseDatabase.instance is just a shorthand notation to getting the default FirebaseApp instance, which is typically auto-initialized from the values in your google-services.json/google-services.info.plist

You can explicitly initialize a FirebaseApp with configuration data in your code. A snippet of the relevant code from an app I happen to be working on:

```<code>  final FirebaseApp  app = await FirebaseApp.configure(
    name: "defaultAppName",
    options: Platform.isIOS
        ? const FirebaseOptions(
            googleAppID: '....',
            gcmSenderID: '...',
            databaseURL: '...',
          )
        : const FirebaseOptions(
            googleAppID: '...',
            apiKey: '...',
            databaseURL: '...',
          ),
  );*/
  FirebaseDatabase(app: app).setPersistenceEnabled(true);
  FirebaseDatabase(app: app).reference().child("/rounds/r1").orderByValue().onChildAdded.forEach((event) => {
    print(event.snapshot.value)
  });
</code>```

Body:
Using FirebaseDatabase.instance is just a shorthand notation to getting the default FirebaseApp instance, which is typically auto-initialized from the values in your google-services.json/google-services.info.plist

You can explicitly initialize a FirebaseApp with configuration data in your code. A snippet of the relevant code from an app I happen to be working on:

  final FirebaseApp  app = await FirebaseApp.configure(
    name: "defaultAppName",
    options: Platform.isIOS
        ? const FirebaseOptions(
            googleAppID: '....',
            gcmSenderID: '...',
            databaseURL: '...',
          )
        : const FirebaseOptions(
            googleAppID: '...',
            apiKey: '...',
            databaseURL: '...',
          ),
  );*/
  FirebaseDatabase(app: app).setPersistenceEnabled(true);
  FirebaseDatabase(app: app).reference().child("/rounds/r1").orderByValue().onChildAdded.forEach((event) => {
    print(event.snapshot.value)
  });


问:
Including this file causes a bunch of unknown type errors [C]
Including main.h in stm32f4xx_hal_uart.h causes issues --> usart_app.h:14:22: error: unknown type name 'USART_Handle_t'; did you mean 'DMA_Handle_t'? -- mainly related to unknown types.

Aren't there easy ways around figuring out issues specific to file includes? cause it's annoying

I suspect stm32f4xx_dma.h is causing trouble since it's being called in main.h and stm32f4xx_hal_uart.h but I wonder wouldn't header guard take care of the 'loop`?

here's what i sort of have:

```<code>// --- main.h ---
#include "stm32f4xx_hal.h"
#include "mcp9808.h"
#include "usart_app.h"
#include "stm32f4xx_dma.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

// --- stm32f4xx_hal_uart.h ---"
#include <stdint.h>
#include "stdbool.h"
#include "../Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_rcc.h"
#include "stm32f4xx_dma.h"
#include "main.h" // ... adding this causes issues !!

typedef struct {
    USART_TypeDef *pUSARTx;
    USART_Config_t USART_Config;
    USART_State USART_State;
    char *txBuffer;
    char *rxBuffer;
    uint8_t txLength;
    uint8_t rxLength;
    uint8_t rxSize;
    uint8_t dmaTransfer;
    uint8_t dmaReception;
    DMA_Handle_t *dmaRx;
    DMA_Handle_t *dmaTx;
} USART_Handle_t;

// --- stm32f4xx_dma.h ---
#include "stm32f401xe.h"
#include "stm32f4xx_hal.h"```
```

答:
…  I wonder wouldn't header guard take care of the 'loop`?

What header guard? The file contents you show in the question do not have header guards.

If there are header guards, then the problem is that including main.h in stm32f4xx_hal_uart.h causes it to include usart_app.h, and usart_app.h needs the USART_Handle_t defined in stm32f4xx_hal_uart.h, so it includes stm32f4xx_hal_uart.h, but the earlier processing is already past the header guard in stm32f4xx_hal_uart.h, so the guard skips the body of stm32f4xx_hal_uart.h when usart_app.h includes it, so USART_Handle_t is not defined.

To fix that, do not include main.h in stm32f4xx_hal_uart.h.

Body:
Including main.h in stm32f4xx_hal_uart.h causes issues --> usart_app.h:14:22: error: unknown type name 'USART_Handle_t'; did you mean 'DMA_Handle_t'? -- mainly related to unknown types.

Aren't there easy ways around figuring out issues specific to file includes? cause it's annoying

I suspect stm32f4xx_dma.h is causing trouble since it's being called in main.h and stm32f4xx_hal_uart.h but I wonder wouldn't header guard take care of the 'loop`?

here's what i sort of have:

// --- main.h ---
#include "stm32f4xx_hal.h"
#include "mcp9808.h"
#include "usart_app.h"
#include "stm32f4xx_dma.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

// --- stm32f4xx_hal_uart.h ---"
#include <stdint.h>
#include "stdbool.h"
#include "../Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_rcc.h"
#include "stm32f4xx_dma.h"
#include "main.h" // ... adding this causes issues !!

typedef struct {
    USART_TypeDef *pUSARTx;
    USART_Config_t USART_Config;
    USART_State USART_State;
    char *txBuffer;
    char *rxBuffer;
    uint8_t txLength;
    uint8_t rxLength;
    uint8_t rxSize;
    uint8_t dmaTransfer;
    uint8_t dmaReception;
    DMA_Handle_t *dmaRx;
    DMA_Handle_t *dmaTx;
} USART_Handle_t;

// --- stm32f4xx_dma.h ---
#include "stm32f401xe.h"
#include "stm32f4xx_hal.h"```


问:
How to undo javascript function
I have a function like so which toggles my dropdown menu.

```<code><div class="module widget-handle mobile-toggle right visible-sm visible-xs">
  <a id="mobile-nav" href="#">
    <div class="container1" onclick="myFunction(this)">
      <div class="bar1"></div>
      <div class="bar2"></div>
      <div class="bar3"></div>.
    </div>
  </a>
</div>
<script>
  function myFunction(x) {
    x.classList.toggle('change');
    document.body.style.overflow ='hidden'
  }
</script>
</code>```

The last part of it

```<code>document.body.style.overflow = 'hidden'
</code>```

Keeps the page from overflowing at the top when the dropdown menu is open. The problem is that when I click on my menu bars, whilst the overflow disappears, clicking on the bars again reveals the page but locks it due to the overflow being hidden.

I'd like to undo

```<code>document.body.style.overflow = 'hidden'
</code>```

When the menu is closed and the closest I've got to understanding it is the function doBack. Can I somehow add doBack to my existing function?

Mobile page here

It's a WordPress site and the javascript above toggles the dropdown by pressing on the bars. In order to extend the dropdown, I made the class collapse bigger, like so.

```<code>@media (max-width: 768px) {
  .collapse {
    position: absolute;
    height: 775px;
    background-color: white;
    z-index: 99999 !important;
    top: 75px;
    left: -50px;
    line-height: 10px;
  }
}
</code>```

HTML:

```<code><div class="module-group right">
  <div class="module left">
    <div class="collapse navbar-collapse navbar-ex1-collapse">
      <ul id="menu" class="menu">
        <li id="menu-item-15050" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-15050 dropdown">
          <a title="Contact" href="url">Contact
            <ul role="menu" class="dropdow n-menu">
            </ul>
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

</code>```

答:
You can simply add a new CSS class:

```<code>.body-overflow {
  overflow: hidden;
}
</code>```

and in your javascript function add another .classList.toggle() but this time on the body:

```<code>function myFunction(x) {
  x.classList.toggle('change');
  document.body.classList.toggle('body-overflow');
}
</code>```

Title: How to undo javascript function

Body:
I have a function like so which toggles my dropdown menu.

.

The last part of it

document.body.style.overflow = 'hidden'

Keeps the page from overflowing at the top when the dropdown menu is open. The problem is that when I click on my menu bars, whilst the overflow disappears, clicking on the bars again reveals the page but locks it due to the overflow being hidden.

I'd like to undo

document.body.style.overflow = 'hidden'

When the menu is closed and the closest I've got to understanding it is the function doBack. Can I somehow add doBack to my existing function?

Mobile page here

It's a WordPress site and the javascript above toggles the dropdown by pressing on the bars. In order to extend the dropdown, I made the class collapse bigger, like so.

@media (max-width: 768px) {
  .collapse {
    position: absolute;
    height: 775px;
    background-color: white;
    z-index: 99999 !important;
    top: 75px;
    left: -50px;
    line-height: 10px;
  }
}

HTML:

          Contact

Body:
You can simply add a new CSS class:

.body-overflow {
  overflow: hidden;
}

and in your javascript function add another .classList.toggle() but this time on the body:

function myFunction(x) {
  x.classList.toggle('change');
  document.body.classList.toggle('body-overflow');
}


问:
Filter Strings Using Ternary operator
I need to know why my option1 works and option2 doesn't.
I am not after a list comprehension solution or alternative answer.

Option1 :This works and gives [23, 23, 34] which is what I expected

```<code>list(filter(lambda x: True if x>9 else False, [1,23,23,34]))
</code>```

Option2 doesnt work.Please note I have multiple strings to check against along list

```<code>list(filter(lambda x: True if x in ('red', 'oh') else False, ['fred', 'john', 'Nick']))
</code>```

Expected output from option2 is:

```<code>['fred', 'john']
</code>```

答:
```<code>True if x in ('red', 'oh') else False
</code>```

Look at x. If x is "Fred", x is not in "red" ("red" is in "Fred")
You want the opposite.

```<code>True if 'red' in x or 'oh' in x else False
</code>```

The total line is

```<code>list(filter(lambda x: True if 'red' in x or 'oh' in x else False, ['fred', 'john', 'Nick']))
</code>```

While not pretty, this is how you can do it with any number of strings:

names = ['fred', 'john', 'nick']
subs = ['red', 'oh']
list(filter(lambda x: True if any([y in x for y in subs]) else False, names))
```

Title: Filter Strings Using Ternary operator

Body:
I need to know why my option1 works and option2 doesn't.
I am not after a list comprehension solution or alternative answer.

Option1 :This works and gives [23, 23, 34] which is what I expected

list(filter(lambda x: True if x>9 else False, [1,23,23,34]))

Option2 doesnt work.Please note I have multiple strings to check against along list

list(filter(lambda x: True if x in ('red', 'oh') else False, ['fred', 'john', 'Nick']))

Expected output from option2 is:

['fred', 'john']

Body:
True if x in ('red', 'oh') else False

Look at x. If x is "Fred", x is not in "red" ("red" is in "Fred")
You want the opposite.

True if 'red' in x or 'oh' in x else False

The total line is

list(filter(lambda x: True if 'red' in x or 'oh' in x else False, ['fred', 'john', 'Nick']))

While not pretty, this is how you can do it with any number of strings:

names = ['fred', 'john', 'nick']
subs = ['red', 'oh']
list(filter(lambda x: True if any([y in x for y in subs]) else False, names))


问:
Nested XML data AWS Glue
We have some data in this format:

```<code><doc>
  <event timestamp="20200529032100">
    <row attr="test" id="3">data</row>
    <row attr="gfds" id="6">data</row>
    <row attr="sadf" id="8">data</row>
  </event>
</doc>
</code>```

We want to extract the data in each row, but the timestamp at the same time. We are trying to do this with an AWS ETL job and CSV as output.

We tried to add a classifier for row, but then we don't get the timestamp. When we try to add a classifier for event, we get the timestamp, but after the etl job, the fields extracted from row only shows up for events with only one row-entry inside it. For the ones with multiple row-entries, there is only one row in the resulting CSV, and the fields we try to extract from row are empty, instead of getting the same number of csv rows, as there are row entries, which is what we want.

Is this possible to solve with AWS Glue, or is this something we have to create on our own?

答:
We had a similar situation and weren't able to build a table using just a custom classifier. We wrote a job that read the XML into a dataframe using the schema that we specified, then used the explode method to pivot nested elements into their own rows.

Note that you'll need to add the spark_xml jar as a dependent jar for your job (or dev endpoint if you're developing in a notebook) as described in https://towardsdatascience.com/use-aws-glue-and-or-databricks-spark-xml-to-process-xml-data-21eaef390fda.

Rough outline of what you should try in your job:

Define a schema for the structure of the element that represents the rows you will read into the data frame initially. In your example, if you want one row per event, define a schema for your event element that includes the row element as an array type. Something like:

```<code>    mySchema = StructType(
        [StructField('_timestamp',LongType(),True),
         StructField('row', ArrayType(StructType([StructField('_VALUE', StringType(), True),
                                      StructField('_attr', StringType(), True),
                                      StructField('_id', LongType(), True)]), True), True)])
</code>```

Read the XML file into a dataframe using the schema

```<code>    spark_df = spark.read.format("xml").options(rowTag="event").options(nullValue="").schema(mySchema).load("s3://bucket/path/to/xml")
</code>```

Use explode to create a new dataframe with one row per row tag

```<code>    row_df = spark_df.withColumn('eachrow', explode(col('row')))
</code>```

This will give you a dataframe that looks like this:

```<code>+--------------+--------------------+-------------+
|    _timestamp|                 row|      eachrow|
+--------------+--------------------+-------------+
|20200529032100|[[data,test,3], [...|[data,test,3]|
|20200529032100|[[data,test,3], [...|[data,gfds,6]|
|20200529032100|[[data,test,3], [...|[data,sadf,8]|
+--------------+--------------------+-------------+
</code>```

Select the timestamp attribute and row attribute/values.

```<code>final_df = row_df.select(col('_timestamp').alias('timestamp'), col('eachrow._VALUE').alias('row_value')...)
</code>```

You can then write out the dataframe in whatever format you need.

Title: Nested XML data AWS Glue

Body:
We have some data in this format:

<doc>
  <event timestamp="20200529032100">
    <row attr="test" id="3">data</row>
    <row attr="gfds" id="6">data</row>
    <row attr="sadf" id="8">data</row>
  </event>
</doc>

We want to extract the data in each row, but the timestamp at the same time. We are trying to do this with an AWS ETL job and CSV as output.

We tried to add a classifier for row, but then we don't get the timestamp. When we try to add a classifier for event, we get the timestamp, but after the etl job, the fields extracted from row only shows up for events with only one row-entry inside it. For the ones with multiple row-entries, there is only one row in the resulting CSV, and the fields we try to extract from row are empty, instead of getting the same number of csv rows, as there are row entries, which is what we want.

Is this possible to solve with AWS Glue, or is this something we have to create on our own?

Body:
We had a similar situation and weren't able to build a table using just a custom classifier. We wrote a job that read the XML into a dataframe using the schema that we specified, then used the explode method to pivot nested elements into their own rows.

Note that you'll need to add the spark_xml jar as a dependent jar for your job (or dev endpoint if you're developing in a notebook) as described in https://towardsdatascience.com/use-aws-glue-and-or-databricks-spark-xml-to-process-xml-data-21eaef390fda.

Rough outline of what you should try in your job:

Define a schema for the structure of the element that represents the rows you will read into the data frame initially. In your example, if you want one row per event, define a schema for your event element that includes the row element as an array type. Something like:

    mySchema = StructType(
        [StructField('_timestamp',LongType(),True),
         StructField('row', ArrayType(StructType([StructField('_VALUE', StringType(), True),
                                      StructField('_attr', StringType(), True),
                                      StructField('_id', LongType(), True)]), True), True)])

Read the XML file into a dataframe using the schema

    spark_df = spark.read.format("xml").options(rowTag="event").options(nullValue="").schema(mySchema).load("s3://bucket/path/to/xml")

Use explode to create a new dataframe with one row per row tag

    row_df = spark_df.withColumn('eachrow', explode(col('row')))

This will give you a dataframe that looks like this:

+--------------+--------------------+-------------+
|    _timestamp|                 row|      eachrow|
+--------------+--------------------+-------------+
|20200529032100|[[data,test,3], [...|[data,test,3]|
|20200529032100|[[data,test,3], [...|[data,gfds,6]|
|20200529032100|[[data,test,3], [...|[data,sadf,8]|
+--------------+--------------------+-------------+

Select the timestamp attribute and row attribute/values.

final_df = row_df.select(col('_timestamp').alias('timestamp'), col('eachrow._VALUE').alias('row_value')...)

You can then write out the dataframe in whatever format you need.


问:
AWS Lambda with Python write to CloudWatch throw DataAlreadyAcceptedException
Hi I am building a AWS lambda function with API Gateway to write the log from ngx-logger in my Angular project to CloudWatch. Here is the python lambda function

```<code>def log(event, context):
    log_streams = logs.describe_log_streams(logGroupName=LOG_GROUP)
    nextSequenceToken=log_streams['logStreams'][0]['uploadSequenceToken']

    timestamp = int(round(time.time() * 1000))

    result = logs.put_log_events(
        logGroupName=LOG_GROUP,
        logStreamName=LOG_STREAM,
        logEvents=[
            {
                'timestamp': timestamp,
                'message': Hello world, here is our first log message!'
            }
        ],
        sequenceToken=nextSequenceToken)

    return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda!')
}
</code>```

However, when I trigger my frontend with a few errors, I can see some errors are logged while some errors are not with the following exception

```<code>DataAlreadyAcceptedException: An error occurred (DataAlreadyAcceptedException) when calling the PutLogEvents operation: The given batch of log events has already been accepted. The next batch can be sent with sequenceToken: xxxxxxxxxxxxxxxxxxx
</code>```

I am thing if it is because Lambda is async and two requests get the same next sequence number. Is there any way I can avoid this issue? Thank you

答:
My understanding is if the log stream is newly created, then I do not need to set this value. But if I reuse an existing stream, this field is necessary. Please correct me if I am wrong.

You are absolutely correct, and I apologize that I did not more closely read the spec.

Here's a quick example I threw together to demo how I would solve this problem. It's certainly not foolproof depending on the volume you expect to be working with. (Pardon the solution being in JavaScript rather than Python; this is what I'm more familiar with.)

```<code>const AWS = require('aws-sdk');
const cloudwatchlogs = new AWS.CloudWatchLogs();

exports.handler = async(event) => {
    const LOG_GROUP_NAME = 'test-logs';
    const LOG_STREAM_NAME = 'test-stream';

    let nextSequenceToken = null;

    // Naive initial usage. Since we're including an empty nextSequenceToken
    // we'll call describeLogStreams first to retrieve the token
    nextSequenceToken = await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 1',
        nextSequenceToken,
    );

    // This is the happy path. It will still fail on the first log attempt if
    // another process has written to the stream. Note that we intentionally
    // don't update nextSequenceToken
    await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 2',
        nextSequenceToken,
    );

    // This will definitely fail on the first attempt since we didn't update
    // nextSequenceToken above -- but the first retry will succeed
    await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 3',
        nextSequenceToken,
    );

    return {};
};

const log = async(
    logGroupName,
    logStreamName,
    message,
    sequenceToken = null,
    retries = 3,
) => {
    if (sequenceToken == null) {
        sequenceToken = await retrieveNextSequenceToken(
            logGroupName,
            logStreamName,
        );
    }

    var params = {
        logEvents: [{
            message,
            timestamp: Date.now(),
        }],
        logGroupName,
        logStreamName,
        sequenceToken,
    };

    return await new Promise((resolve, reject) => {
        cloudwatchlogs.putLogEvents(params, function(err, data) {
            if (err) {
                if (
                    retries > 0 &&
                    err.code === 'InvalidSequenceTokenException'
                ) {
                    console.log('invalid sequence token, retrying');
                    const nextSequenceToken =
                        /sequenceToken is: (.*)/.exec(err.message)[1];
                    console.log('nextSequenceToken: ' + nextSequenceToken);
                    log(
                        logGroupName,
                        logStreamName,
                        message,
                        nextSequenceToken,
                        retries - 1,
                    ).then(resolve).catch(reject);
                }
                else {
                    reject(err);
                }
            }
            else {
                resolve(data.nextSequenceToken);
            }
        });
    });
};

const retrieveNextSequenceToken = async(logGroupName, logStreamName) => {
    const params = {
        logGroupName,
        descending: true,
        limit: 1,
        logStreamNamePrefix: logStreamName,
        orderBy: 'LogStreamName',
    };

    return await new Promise((resolve, reject) => {
        cloudwatchlogs.describeLogStreams(params, function(err, data) {
            if (err) {
                reject(err);
            }
            else {
                resolve(data.logStreams[0].uploadSequenceToken);
            }
        });
    });
};
</code>```

Execution logs:

```<code>START RequestId: 64c93ac7-d7a3-415d-a65f-88f9a01f5e31 Version: $LATEST
2020-05-30T00:26:47.987Z    64c93ac7-d7a3-415d-a65f-88f9a01f5e31    INFO    invalid sequence token, retrying
2020-05-30T00:26:48.025Z    64c93ac7-d7a3-415d-a65f-88f9a01f5e31    INFO    nextSequenceToken: 49605487572640549775784175775008805339581397298215084354
END RequestId: 64c93ac7-d7a3-415d-a65f-88f9a01f5e31
</code>```

This is kind of a hack -- and even AWS doesn't try to do this when working with potentially concurrent data streams (look at how Lambda executions create new streams for each underlying runner). If there is not a strong reason for you needing to send logs to the same stream I would suggest following a similar pattern.

Body:
Hi I am building a AWS lambda function with API Gateway to write the log from ngx-logger in my Angular project to CloudWatch. Here is the python lambda function

def log(event, context):
    log_streams = logs.describe_log_streams(logGroupName=LOG_GROUP)
    nextSequenceToken=log_streams['logStreams'][0]['uploadSequenceToken']

    timestamp = int(round(time.time() * 1000))

    result = logs.put_log_events(
        logGroupName=LOG_GROUP,
        logStreamName=LOG_STREAM,
        logEvents=[
            {
                'timestamp': timestamp,
                'message': Hello world, here is our first log message!'
            }
        ],
        sequenceToken=nextSequenceToken)

    return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda!')
}

However, when I trigger my frontend with a few errors, I can see some errors are logged while some errors are not with the following exception

DataAlreadyAcceptedException: An error occurred (DataAlreadyAcceptedException) when calling the PutLogEvents operation: The given batch of log events has already been accepted. The next batch can be sent with sequenceToken: xxxxxxxxxxxxxxxxxxx

I am thing if it is because Lambda is async and two requests get the same next sequence number. Is there any way I can avoid this issue? Thank you

Body:
My understanding is if the log stream is newly created, then I do not need to set this value. But if I reuse an existing stream, this field is necessary. Please correct me if I am wrong.

You are absolutely correct, and I apologize that I did not more closely read the spec.

Here's a quick example I threw together to demo how I would solve this problem. It's certainly not foolproof depending on the volume you expect to be working with. (Pardon the solution being in JavaScript rather than Python; this is what I'm more familiar with.)

const AWS = require('aws-sdk');
const cloudwatchlogs = new AWS.CloudWatchLogs();

exports.handler = async(event) => {
    const LOG_GROUP_NAME = 'test-logs';
    const LOG_STREAM_NAME = 'test-stream';

    let nextSequenceToken = null;

    // Naive initial usage. Since we're including an empty nextSequenceToken
    // we'll call describeLogStreams first to retrieve the token
    nextSequenceToken = await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 1',
        nextSequenceToken,
    );

    // This is the happy path. It will still fail on the first log attempt if
    // another process has written to the stream. Note that we intentionally
    // don't update nextSequenceToken
    await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 2',
        nextSequenceToken,
    );

    // This will definitely fail on the first attempt since we didn't update
    // nextSequenceToken above -- but the first retry will succeed
    await log(
        LOG_GROUP_NAME,
        LOG_STREAM_NAME,
        'log 3',
        nextSequenceToken,
    );

    return {};
};

const log = async(
    logGroupName,
    logStreamName,
    message,
    sequenceToken = null,
    retries = 3,
) => {
    if (sequenceToken == null) {
        sequenceToken = await retrieveNextSequenceToken(
            logGroupName,
            logStreamName,
        );
    }

    var params = {
        logEvents: [{
            message,
            timestamp: Date.now(),
        }],
        logGroupName,
        logStreamName,
        sequenceToken,
    };

    return await new Promise((resolve, reject) => {
        cloudwatchlogs.putLogEvents(params, function(err, data) {
            if (err) {
                if (
                    retries > 0 &&
                    err.code === 'InvalidSequenceTokenException'
                ) {
                    console.log('invalid sequence token, retrying');
                    const nextSequenceToken =
                        /sequenceToken is: (.*)/.exec(err.message)[1];
                    console.log('nextSequenceToken: ' + nextSequenceToken);
                    log(
                        logGroupName,
                        logStreamName,
                        message,
                        nextSequenceToken,
                        retries - 1,
                    ).then(resolve).catch(reject);
                }
                else {
                    reject(err);
                }
            }
            else {
                resolve(data.nextSequenceToken);
            }
        });
    });
};

const retrieveNextSequenceToken = async(logGroupName, logStreamName) => {
    const params = {
        logGroupName,
        descending: true,
        limit: 1,
        logStreamNamePrefix: logStreamName,
        orderBy: 'LogStreamName',
    };

    return await new Promise((resolve, reject) => {
        cloudwatchlogs.describeLogStreams(params, function(err, data) {
            if (err) {
                reject(err);
            }
            else {
                resolve(data.logStreams[0].uploadSequenceToken);
            }
        });
    });
};

Execution logs:

START RequestId: 64c93ac7-d7a3-415d-a65f-88f9a01f5e31 Version: $LATEST
2020-05-30T00:26:47.987Z    64c93ac7-d7a3-415d-a65f-88f9a01f5e31    INFO    invalid sequence token, retrying
2020-05-30T00:26:48.025Z    64c93ac7-d7a3-415d-a65f-88f9a01f5e31    INFO    nextSequenceToken: 49605487572640549775784175775008805339581397298215084354
END RequestId: 64c93ac7-d7a3-415d-a65f-88f9a01f5e31

This is kind of a hack -- and even AWS doesn't try to do this when working with potentially concurrent data streams (look at how Lambda executions create new streams for each underlying runner). If there is not a strong reason for you needing to send logs to the same stream I would suggest following a similar pattern.


问:
Lambda expression type inference is different in inheritance chain. Why?
Given the following classes:

```<code>public class Class1<TObject> {
    protected void MethodA<TType>(Expression<Func<TObject, TType>> property, ref TType store, TType value) {
    }
}

public class Class2<TObject> : Class1<Class2<TObject>>{
    private int _propertyInt;
    public int PropertyInt {
        get { return _propertyInt; }
        set { MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); }
    }
}

public class Class3 : Class2<Class3> {
    private float _propertyFloat;
    public float PropertyFloat {
        get { return _propertyFloat; }
        set { MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); }
    }
}
</code>```

For Class2 the C# compiler infers the generic type of the base class for the lambda expression in the 'PropertyInt' property setter, but for Class3 the compiler infers the base class, not just the generic type of the base class.  Why is this?  What is the criteria for the inferred type in the code sample.  Thanks.

答:
First off, the TObject generic parameter is defined in Class1.  That TObject is used in Class1 as the type argument in MethodA.

In Class2, the TObject passed to the base (Class1) is a Class2, and so the lambda can infer the local property _propertyInt.

In Class3, the TObject passed to the base is a Class2, not a Class3.  Therefore, the lambda's argument is inferred, but it is inferred as a Class2, not a Class3.

The fact that Class2 also has a type parameter named TObject is entirely coincidental- I think you are expecting that anything passed to that TObject will be transitively passed on to Class1, which it is not.

If you defined Class3 as follows, it would work:

```<code>public class Class3 : Class1<Class3> { ... }
</code>```

Given the comment, then might I offer this extension method based solution, (assuming that the type parameters were only for the purpose of making this work):

```<code>public class Class1
{
}

public static class StaticClass1
{
    public static void MethodA<TZen, TType>(this TZen zen, Expression<Func<TZen, TType>> property, ref TType store, TType value) where TZen : Class1
    {
        // Do whatever here...
    }
}

public class Class2 : Class1
{
    private int _propertyInt;
    public int PropertyInt
    {
        get { return _propertyInt; }
        set { this.MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); }
    }
}

public class Class3 : Class2
{
    private float _propertyFloat;
    public float PropertyFloat
    {
        get { return _propertyFloat; }
        set { this.MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); }
    }
}
</code>```

Body:
Given the following classes:

public class Class1<TObject> {
    protected void MethodA<TType>(Expression<Func<TObject, TType>> property, ref TType store, TType value) {
    }
}

public class Class2<TObject> : Class1<Class2<TObject>>{
    private int _propertyInt;
    public int PropertyInt {
        get { return _propertyInt; }
        set { MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); }
    }
}

public class Class3 : Class2<Class3> {
    private float _propertyFloat;
    public float PropertyFloat {
        get { return _propertyFloat; }
        set { MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); }
    }
}

For Class2 the C# compiler infers the generic type of the base class for the lambda expression in the 'PropertyInt' property setter, but for Class3 the compiler infers the base class, not just the generic type of the base class.  Why is this?  What is the criteria for the inferred type in the code sample.  Thanks.

Body:
First off, the TObject generic parameter is defined in Class1.  That TObject is used in Class1 as the type argument in MethodA.

In Class2, the TObject passed to the base (Class1) is a Class2, and so the lambda can infer the local property _propertyInt.

In Class3, the TObject passed to the base is a Class2, not a Class3.  Therefore, the lambda's argument is inferred, but it is inferred as a Class2, not a Class3.

The fact that Class2 also has a type parameter named TObject is entirely coincidental- I think you are expecting that anything passed to that TObject will be transitively passed on to Class1, which it is not.

If you defined Class3 as follows, it would work:

public class Class3 : Class1<Class3> { ... }

Given the comment, then might I offer this extension method based solution, (assuming that the type parameters were only for the purpose of making this work):

public class Class1
{
}

public static class StaticClass1
{
    public static void MethodA<TZen, TType>(this TZen zen, Expression<Func<TZen, TType>> property, ref TType store, TType value) where TZen : Class1
    {
        // Do whatever here...
    }
}

public class Class2 : Class1
{
    private int _propertyInt;
    public int PropertyInt
    {
        get { return _propertyInt; }
        set { this.MethodA(c2 => c2.PropertyInt, ref _propertyInt, value); }
    }
}

public class Class3 : Class2
{
    private float _propertyFloat;
    public float PropertyFloat
    {
        get { return _propertyFloat; }
        set { this.MethodA(c3 => c3.PropertyFloat, ref _propertyFloat, value); }
    }
}


问:
Debugging json_t object with GDB
I have a application in C programming which uses jansson library(json library written in C). I'm trying to view value of json_t object in gdb but it just prints

```<code>(gdb) p jmsg
$20 = (json_t *) 0x69c350
(gdb) p *jmsg
$21 = {type = JSON_OBJECT, refcount = 1}
</code>```

How is it possible to view the value of json_t in gdb.?

答:
When in GDB, you can make function calls directly. Jansson library has a json_dumps(json_t *, int flags) API that returns a char* string of the json_t object.

So while in GDB, just simply do:

```<code>(gdb) call json_dumps(obj, 0)
</code>```

GDB will then print the string output of your json object.

Title: Debugging json_t object with GDB

Body:
I have a application in C programming which uses jansson library(json library written in C). I'm trying to view value of json_t object in gdb but it just prints

(gdb) p jmsg
$20 = (json_t *) 0x69c350
(gdb) p *jmsg
$21 = {type = JSON_OBJECT, refcount = 1}

How is it possible to view the value of json_t in gdb.?

Body:
When in GDB, you can make function calls directly. Jansson library has a json_dumps(json_t *, int flags) API that returns a char* string of the json_t object.

So while in GDB, just simply do:

(gdb) call json_dumps(obj, 0)

GDB will then print the string output of your json object.


问:
PHP for each, use specific key's value
I am using foreach($_GET as $key => $value) { But dont know how to do something if $key is something specific then use its value.

I have read official documentation and few articles here cant find example of this.

I need something like:

```<code>    foreach($_GET as $key => $value) {
    if ($key="something"){
echo $value;
    //do something with that specifics key value
    }
</code>```

Code above is "doing something" always because one of the keys "is something" and it takes last value of that array and echo it. I need value just of that one key.

答:
Your if() should contain == which checks the value for you and it should be $_GET['something'] not $_GET

```<code>foreach($_GET['something'] as $key => $value) {
if ($key == "something"){
echo $value;
 //do something with that specifics key value
}
</code>```

Title: PHP for each, use specific key's value

Body:
I am using foreach($_GET as $key => $value) { But dont know how to do something if $key is something specific then use its value.

I have read official documentation and few articles here cant find example of this.

I need something like:

    foreach($_GET as $key => $value) {
    if ($key="something"){
echo $value;
    //do something with that specifics key value
    }

Code above is "doing something" always because one of the keys "is something" and it takes last value of that array and echo it. I need value just of that one key.

Body:
Your if() should contain == which checks the value for you and it should be $_GET['something'] not $_GET

foreach($_GET['something'] as $key => $value) {
if ($key == "something"){
echo $value;
 //do something with that specifics key value
}


问:
Flutter App stuck at "Running Gradle task 'assembleDebug'... "
When I run the app it get stuck

```<code>Launching lib\main.dart on Lenovo A319 in debug mode...
Running Gradle task 'assembleDebug'...
(This is taking an unexpectedly long time.)
</code>```

It never initialize Gradle nor the dependencies

答:
I solved the issue by reinstalling SDK Platform on Android studio for Android API 29

```<code>Tools->SDK Manager-SDK Platform
</code>```

Next go to

```<code>Android > app > build.gradle
</code>```

Make sure you also change

```<code>compileSdkVersion 29

targetSdkVersion 29
</code>```

Be patient, it take longer for the first launch...But, not take forever like before.

good luck

Body:
When I run the app it get stuck

Launching lib\main.dart on Lenovo A319 in debug mode...
Running Gradle task 'assembleDebug'...
(This is taking an unexpectedly long time.)

It never initialize Gradle nor the dependencies

Body:
I solved the issue by reinstalling SDK Platform on Android studio for Android API 29

Tools->SDK Manager-SDK Platform

Next go to

Android > app > build.gradle

Make sure you also change

compileSdkVersion 29

targetSdkVersion 29

Be patient, it take longer for the first launch...But, not take forever like before.

good luck


问:
C++ concept check vs inheritance
What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?

It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sense to favor one over the other?

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

So, on one hand, I want containers to behave polymorphicly. On the other, I still have to use concepts if I want to correctly implement some algorithms. What is a junior developer to do?

答:
Yes, polymorphic behavior is possible with both mechanisms. In fact, both are called polymorphism too.

Virtual functions give you dynamic polymorphism (because it's decided at runtime), while templates give you static polymorphism (everything is decided at compile-time).

And that should answer the question of which to prefer as well. Whenever possible, prefer to move work to compile-time. So when you can get away with it, use templates to solve your polymorphism needs. And when that's not possible (because you need to use runtime type information, because the exact types aren't known at compile-time), fall back to dynamic polymorphism.

(Of course there may be other reasons to prefer one or the other. In particular, templates require you to move a lot of code to header files which may or may not be a problem, and compilation speed tends to suffer, which also may or may not be a problem.)

OwnerDisplayName: Voltaire

ContentLicense: CC BY-SA 2.5

Title: C++ concept check vs inheritance

OwnerDisplayName: jalf


问:
Configure Ngnix with Django and Gunicorn
I have the Nginx code below. It sort of works.

If I enter 'https://' to go to the site, the SSL kicks in. However, if I just enter www.thaifoodbypla.com, it does not re-direct to HTTPS, it just loads HTTP.

Nginx config:

```<code>upstream gunicorn{
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).

# for UNIX domain socket setups:

server unix:/home/ubuntu/thaiFoodByPla/project.sock  fail_timeout=0;

# for TCP setups, point these to your backend servers
# server 127.0.0.1:9000 fail_timeout=0;
}
server {
listen 80;
listen 443 ssl http2;
server_name www.thaifoodbypla.com;
ssl_certificate /etc/ssl/private/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/private/briefing_key.pem;

# path for static files
root /home/ubuntu/thaiFoodByPla/project/project;

location / {
  # checks for static file, if not found proxy to app
  try_files $uri @proxy_to_app;
}

location @proxy_to_app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # When Nginx is handling SSL it is helpful to pass the protocol information
    # to Gunicorn. Many web frameworks use this information to generate URLs.
    # Without this information, the application may mistakenly generate http
    # URLs in https responses, leading to mixed content warnings or broken
    # applications. In this case, configure Nginx to pass an appropriate header:
    proxy_set_header X-Forwarded-Proto $scheme;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    proxy_pass http://gunicorn;
}
</code>```

I'm not sure what to do. What can I change to make it forward to https:// automatically?

答:
By adding listen 80 nginx will listen on http and serve that directly to gunicorn.

You can solve that by removing listen 80 and create a redirect from port 80 to 443 as the following:

server {
    listen 443 ssl http2;
    server_name www.thaifoodbypla.com;
    ssl_certificate /etc/ssl/private/ssl-bundle.crt;
    ssl_certificate_key /etc/ssl/private/briefing_key.pem;
    # rest of this block
}

server {
    # if a request is made on port 80 to your domain, it will be redirected
    if ($host = www.thaifoodbypla.com) {
        return 301 https://$host$request_uri;
    }
    listen 80;
    server_name www.thaifoodbypla.com;
    return 404;
}
```

This way all requests on port 80 to your domain will be redirected to https, and 404 response is returned if the domain doesn't match.

Body:
I have the Nginx code below. It sort of works.

If I enter 'https://' to go to the site, the SSL kicks in. However, if I just enter www.thaifoodbypla.com, it does not re-direct to HTTPS, it just loads HTTP.

Nginx config:

upstream gunicorn{
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).

# for UNIX domain socket setups:

server unix:/home/ubuntu/thaiFoodByPla/project.sock  fail_timeout=0;

# for TCP setups, point these to your backend servers
# server 127.0.0.1:9000 fail_timeout=0;
}
server {
listen 80;
listen 443 ssl http2;
server_name www.thaifoodbypla.com;
ssl_certificate /etc/ssl/private/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/private/briefing_key.pem;

# path for static files
root /home/ubuntu/thaiFoodByPla/project/project;

location / {
  # checks for static file, if not found proxy to app
  try_files $uri @proxy_to_app;
}

location @proxy_to_app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # When Nginx is handling SSL it is helpful to pass the protocol information
    # to Gunicorn. Many web frameworks use this information to generate URLs.
    # Without this information, the application may mistakenly generate http
    # URLs in https responses, leading to mixed content warnings or broken
    # applications. In this case, configure Nginx to pass an appropriate header:
    proxy_set_header X-Forwarded-Proto $scheme;

    # pass the Host: header from the client right along so redirects
    # can be set properly within the Rack application
    proxy_set_header Host $http_host;

    # we don't want nginx trying to do something clever with
    # redirects, we set the Host: header above already.
    proxy_redirect off;

    # Try to serve static files from nginx, no point in making an
    # *application* server like Unicorn/Rainbows! serve static files.
    proxy_pass http://gunicorn;
}

I'm not sure what to do. What can I change to make it forward to https:// automatically?

Body:
By adding listen 80 nginx will listen on http and serve that directly to gunicorn.

You can solve that by removing listen 80 and create a redirect from port 80 to 443 as the following:

server {
    listen 443 ssl http2;
    server_name www.thaifoodbypla.com;
    ssl_certificate /etc/ssl/private/ssl-bundle.crt;
    ssl_certificate_key /etc/ssl/private/briefing_key.pem;
    # rest of this block
}

server {
    # if a request is made on port 80 to your domain, it will be redirected
    if ($host = www.thaifoodbypla.com) {
        return 301 https://$host$request_uri;
    }
    listen 80;
    server_name www.thaifoodbypla.com;
    return 404;
}

This way all requests on port 80 to your domain will be redirected to https, and 404 response is returned if the domain doesn't match.


问:
Suppress potential NullPointerException in Android Studio
This:

```<code>@Nullable
Item[] mItems;

public Item getItem(int position) {
    return mItems[position];
}
</code>```

produces the warning:

Array access 'mItems[position]' may produce NullPointerException
```

I want to suppress this warning (I know that getItem() will not be called if mItems is null).

I've tried using the following annotations:

@SuppressWarnings({"NullableProblems"})

@SuppressWarnings({"null"})

as well as with the //noinspection notation, but they're all not working.

Using @SuppressWarnings({"all"}) works, but it's obviously not what I'm looking for.

Android Studio doesn't offer any suppression option when I hit alt + enter, just the options to add a (useless) null check.

答:
To illustrate visually on Mac,

Go to Preferences -> Editor -> Inspections

Then in the search box type constant conditions

Then uncheck the one shown in the image below:

Body:
This:

@Nullable
Item[] mItems;

public Item getItem(int position) {
    return mItems[position];
}

produces the warning:

Array access 'mItems[position]' may produce NullPointerException

I want to suppress this warning (I know that getItem() will not be called if mItems is null).

I've tried using the following annotations:

@SuppressWarnings({"NullableProblems"})

@SuppressWarnings({"null"})

as well as with the //noinspection notation, but they're all not working.

Using @SuppressWarnings({"all"}) works, but it's obviously not what I'm looking for.

Android Studio doesn't offer any suppression option when I hit alt + enter, just the options to add a (useless) null check.


问:
onClick going off without being clicked
I'm very new to writing with JavaScript and am creating a basic tab navigation interface as a prototype/practice. Right now I'm trying to make an alert appear using the onclick event handler on an unordered list of links just as a test and can't figure it out. Every time I load the page, all 5 onclick events occur without having clicked anything. Take a look at the code and let me know if you have any suggestions:

```<code>window.onload = initAll;
var xhr = false;

function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        navTabs[i].onclick = tellTab(i);
    }
}

function tellTab (number) {
    number = number + 1;
    alert("You clicked tab number " + number);
}
</code>```

The HTML structure is as follows:

```<code>    <div id="tab_navigation">
        <ul>
            <li><a href="#1">Tab 1</a></li>
            <li><a href="#2">Tab 2</a></li>
            <li><a href="#3">Tab 3</a></li>
            <li><a href="#4">Tab 4</a></li>
            <li><a href="#5">Tab 5</a></li>
        </ul>
    </div>
</code>```

答:
In a for loop, you have this line:

```<code>navTabs[i].onclick = tellTab(i);
</code>```

That calls tellTab immediately. What you can do is have tellTab return a closure, like this:

```<code>function tellTab (number) {
    return function() {
        // I commented out the following line
        // because I don't think it's necessary.
        //number = number + 1;
        alert("You clicked tab number " + number);
    };
}
</code>```

A different option is creating a closure inside the for loop:

```<code>for (var i = 0; i < navTabs.length; i++) {
    (function(i) {
        navTabs[i].onclick = function() {
            tellTab(i);
        };
    })(i);
}
</code>```

Title: onClick going off without being clicked

Body:
I'm very new to writing with JavaScript and am creating a basic tab navigation interface as a prototype/practice. Right now I'm trying to make an alert appear using the onclick event handler on an unordered list of links just as a test and can't figure it out. Every time I load the page, all 5 onclick events occur without having clicked anything. Take a look at the code and let me know if you have any suggestions:

window.onload = initAll;
var xhr = false;

function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        navTabs[i].onclick = tellTab(i);
    }
}

function tellTab (number) {
    number = number + 1;
    alert("You clicked tab number " + number);
}

The HTML structure is as follows:

Tab 1

Tab 2

Tab 3

Tab 4

Tab 5

Body:
In a for loop, you have this line:

navTabs[i].onclick = tellTab(i);

That calls tellTab immediately. What you can do is have tellTab return a closure, like this:

function tellTab (number) {
    return function() {
        // I commented out the following line
        // because I don't think it's necessary.
        //number = number + 1;
        alert("You clicked tab number " + number);
    };
}

A different option is creating a closure inside the for loop:

for (var i = 0; i < navTabs.length; i++) {
    (function(i) {
        navTabs[i].onclick = function() {
            tellTab(i);
        };
    })(i);
}