问:
What does the term "broadcasting" mean in Pandas documentation?
I'm reading through the Pandas documentation, and the term "broadcasting" is used extensively, but never really defined or explained.

What does it mean?

答:
Broadcasting on Pandas DataFrames with MultiIndex

Broadcasting is especially interesting with DataFrames which have a pandas.MultiIndex as I show you in the following example.

Pandas makes it possible to broadcast over the dimensions added via a multidimensional and even hierarchical index, and this is very powerfull, if you know how to use it. You don't need to code your loops and conditions. You can rely on what works already.

I filled two pandas.DataFrames, af and df with a pandas.MultiIndex on the 0-axis (the index) and 10 columns labeled with integeres refering for example to scenario data from a Monte-Carlo simulation.

The pandas.MultiIndexes of the af and df share some common levels in the names (I call them dimensions). Not all labels (newer pandas versions call them codes) need to be in the matching dimensions. In the example, the dimensions 'a' and 'c' are shared. In both frames the 'a'-dimensions has the entries (labels) ['A' and 'B'], whereas in the 'c' dimension the frames af and bf have the entries [0, 1, 2, 3] and [0, 1, 2] respectively.

Nonetheless, Broadcasting works fine. Which means in the following example, when multiplying the two frames, a group-wise multiplication for each group with matching entries in the matching dimensions is performed.

The following example shows broadcasting on multiplications, but it works for all binary operations between pandas.DataFrames on the left- and right-hand side.

Some observations

Note, that both frames can have additional dimensions. It is not necessary that one set of names is a subset of the other. In the example we have ['a', 'b', 'c'] and ['a', 'c', 'd'] for the af and bf frames respectively

The result spans up the whole space, as expected: ['a', 'b', 'c', 'd']

Since dimension 'c' does not have the entry (code) '3' in frame bf, whereas af has, the result fills the resulting block with NaNs.

Note, that pandas 1.0.3 has been used here. Broadcasting with more then one overlapping dimensions did not work with pandas version 0.23.4.

Broadcasting over the 0-axis and the 1-axis at the same time does also work. See the last two examples. For example, if you would like to multiply the af with only bf[0].to_frame(), the first scenario. But it will only be applied to the equally labeled columns (as broadcasting is intended).

Further Hints

If you want to multiply the af frame with a column vector (I need to apply some weights sometimes with additional dimensions), then you can easily implement it yourself. You can expand your dataframe to n = af.shape[1] columns and use then that one for multiplication. Have a look at numpy.tile on how to do it 'without' coding.

```<code>>>> af
Values    0    1    2    3    4    5    6    7    8    9
a b c
A a 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  b 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  c 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
B a 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  b 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  c 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
>>> bf
Values    0    1    2    3    4    5    6    7    8    9
a c d
A 0 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  1 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  2 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
B 0 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  1 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  2 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
>>> af * bf
Values       0    1    2    3    4    5    6    7    8    9
a c b d
A 0 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  1 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  2 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  3 a NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    b NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    c NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
B 0 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  1 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  2 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  3 a NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    b NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    c NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
>>> af * bf[0] # Raises Error: ValueError: cannot join with no overlapping index names

   # Removed that part

>>> af * bf[0].to_frame()  # works consistently
             0   1   2   3   4   5   6   7   8   9
a c b d
A 0 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  1 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  2 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  3 a NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
B 0 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  1 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  2 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  3 a NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

>>> cf = bf[0].to_frame()
>>> cf.columns = [3]
>>> af * cf  # And as expected we can broadcast over the same column labels at the same time
            0   1   2    3   4   5   6   7   8   9
a c b d
A 0 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  1 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  2 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  3 a NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    b NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    c NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
B 0 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  1 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  2 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  3 a NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    b NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    c NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
</code>```

Body:
Broadcasting on Pandas DataFrames with MultiIndex

Broadcasting is especially interesting with DataFrames which have a pandas.MultiIndex as I show you in the following example.

Pandas makes it possible to broadcast over the dimensions added via a multidimensional and even hierarchical index, and this is very powerfull, if you know how to use it. You don't need to code your loops and conditions. You can rely on what works already.

I filled two pandas.DataFrames, af and df with a pandas.MultiIndex on the 0-axis (the index) and 10 columns labeled with integeres refering for example to scenario data from a Monte-Carlo simulation.

The pandas.MultiIndexes of the af and df share some common levels in the names (I call them dimensions). Not all labels (newer pandas versions call them codes) need to be in the matching dimensions. In the example, the dimensions 'a' and 'c' are shared. In both frames the 'a'-dimensions has the entries (labels) ['A' and 'B'], whereas in the 'c' dimension the frames af and bf have the entries [0, 1, 2, 3] and [0, 1, 2] respectively.

Nonetheless, Broadcasting works fine. Which means in the following example, when multiplying the two frames, a group-wise multiplication for each group with matching entries in the matching dimensions is performed.

The following example shows broadcasting on multiplications, but it works for all binary operations between pandas.DataFrames on the left- and right-hand side.

Some observations

Note, that both frames can have additional dimensions. It is not necessary that one set of names is a subset of the other. In the example we have ['a', 'b', 'c'] and ['a', 'c', 'd'] for the af and bf frames respectively

The result spans up the whole space, as expected: ['a', 'b', 'c', 'd']

Since dimension 'c' does not have the entry (code) '3' in frame bf, whereas af has, the result fills the resulting block with NaNs.

Note, that pandas 1.0.3 has been used here. Broadcasting with more then one overlapping dimensions did not work with pandas version 0.23.4.

Broadcasting over the 0-axis and the 1-axis at the same time does also work. See the last two examples. For example, if you would like to multiply the af with only bf[0].to_frame(), the first scenario. But it will only be applied to the equally labeled columns (as broadcasting is intended).

Further Hints

If you want to multiply the af frame with a column vector (I need to apply some weights sometimes with additional dimensions), then you can easily implement it yourself. You can expand your dataframe to n = af.shape[1] columns and use then that one for multiplication. Have a look at numpy.tile on how to do it 'without' coding.

>>> af
Values    0    1    2    3    4    5    6    7    8    9
a b c
A a 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  b 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  c 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
B a 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  b 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
  c 0   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    1   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    2   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
    3   2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0  2.0
>>> bf
Values    0    1    2    3    4    5    6    7    8    9
a c d
A 0 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  1 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  2 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
B 0 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  1 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
  2 *   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
    #   3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0  3.0
>>> af * bf
Values       0    1    2    3    4    5    6    7    8    9
a c b d
A 0 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  1 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  2 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  3 a NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    b NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    c NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
B 0 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  1 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  2 a *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    b *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
    c *    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
      #    6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0  6.0
  3 a NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    b NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
    c NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
>>> af * bf[0] # Raises Error: ValueError: cannot join with no overlapping index names

   # Removed that part

>>> af * bf[0].to_frame()  # works consistently
             0   1   2   3   4   5   6   7   8   9
a c b d
A 0 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  1 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  2 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  3 a NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
B 0 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  1 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  2 a *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c *    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
      #    6.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
  3 a NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    b NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
    c NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

>>> cf = bf[0].to_frame()
>>> cf.columns = [3]
>>> af * cf  # And as expected we can broadcast over the same column labels at the same time
            0   1   2    3   4   5   6   7   8   9
a c b d
A 0 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  1 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  2 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  3 a NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    b NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    c NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
B 0 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  1 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  2 a *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    b *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
    c *   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
      #   NaN NaN NaN  6.0 NaN NaN NaN NaN NaN NaN
  3 a NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    b NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN
    c NaN NaN NaN NaN  NaN NaN NaN NaN NaN NaN NaN


来源: stackexchange

问:
Checking if a constant is empty
Why is this not possible?

```<code>if(!empty( _MY_CONST)){
  ...
</code>```

But yet this is:

```<code>$my_const = _MY_CONST;
if(!empty($my_const)){
  ...
</code>```

```<code>define( 'QUOTA_MSG' , '' ); // There is currently no message to show

$message = QUOTA_MSG;
if(!empty($message)){
  echo $message;
}
</code>```

I just wanted to make it a little cleaner by just referencing the constant itself.

答:
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:

```<code>define('MY_CONST', '');
if (!MY_CONST) {
    echo 'MY_CONST is empty';
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Checking if a constant is empty

Body:
Why is this not possible?

if(!empty( _MY_CONST)){
  ...

But yet this is:

$my_const = _MY_CONST;
if(!empty($my_const)){
  ...

define( 'QUOTA_MSG' , '' ); // There is currently no message to show

$message = QUOTA_MSG;
if(!empty($message)){
  echo $message;
}

I just wanted to make it a little cleaner by just referencing the constant itself.

Body:
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:

define('MY_CONST', '');
if (!MY_CONST) {
    echo 'MY_CONST is empty';
}

ContentLicense: CC BY-SA 4.0


问:
Blocking all traffic except from ELB security groups, nginx responds with 502
I hope you can help me.
I have succesfully configured an ELB attached to two ec2 instances.
ELB listens on port 443 and forwards to port 80.

Everything works as expected.

What I want to achieve now is to block all traffic to the ec2 instances except the one coming from the ELB.

I have a created a new security group:

```<code>Accept all from sg-xxxxx
</code>```

Where sg-xxx is the security group of the ELB which is set to:

```<code>Accept HTTPS from 0.0.0.0/0 | 0:*
</code>```

I go the ec2 instance, remove the default SG and assign the newly created SG to accept traffic only from the ELB (networking, assign security group) server responds with:

```<code><html>

<head>
    <title>502 Bad Gateway</title>
</head>

<body>
    <center>
        <h1>502 Bad Gateway</h1>
    </center>
    <hr>
    <center>nginx/1.15.8</center>
</body>

</html>
</code>```

What am I doing wrong?

Thank you for any help!

答:
The recommended configuration would be:

A security group on the Load Balancer (LB-SG) with:

Inbound rules: ports 80 and 443 from 0.0.0.0/0

Outbound rules: Allow all traffic

A security group on each Amazon EC2 instance (App-SG) with:

Inbound rules: port 80 from LB-SG

Outbound rules: Allow all traffic

That is, the App-SG should accept inbound traffic from LB-SG by referencing the other security group.

It is recommended to always allow all outbound traffic, since applications running on your own instance should be "trusted" unless you specifically want to lock-down security.

Body:
I hope you can help me.
I have succesfully configured an ELB attached to two ec2 instances.
ELB listens on port 443 and forwards to port 80.

Everything works as expected.

What I want to achieve now is to block all traffic to the ec2 instances except the one coming from the ELB.

I have a created a new security group:

Accept all from sg-xxxxx

Where sg-xxx is the security group of the ELB which is set to:

Accept HTTPS from 0.0.0.0/0 | 0:*

I go the ec2 instance, remove the default SG and assign the newly created SG to accept traffic only from the ELB (networking, assign security group) server responds with:

    <title>502 Bad Gateway</title>

502 Bad Gateway

    nginx/1.15.8

What am I doing wrong?

Thank you for any help!


问:
Why does my script for a Chrome extension that is meant to get the current url not work?
I got a script from Stack Overflow for getting the current Chrome tab, but every time I try to run it, this error shows up in Google Chrome:

```<code>Uncaught TypeError: Cannot read property 'query' of undefined
Context

https://www.youtube.com/
Stack Trace

**chrome.tabs.query({active: true, currentWindow: true}, tabs => {**
    let url = tabs[0].url;
    // use `url` here inside the callback because it's asynchronous!
});
</code>```

The code in bold is the highlighted code in the error. I have tried to replace currentWindow with lastFocusedWindow, but that did nothing. The permissions are all correct, and I even added extra permissions that I do not need, as shown here:

```<code>"permissions": [
    "tabs",
    "<all_urls>",
    "activeTab" ]
</code>```

I only need tabs and <all_urls> for my script, but I have activeTab just in case. What is the problem here, and how can I fix it?

答:
There are two ways to do it.

calling getCurrent(). More details here on which page you should execute the script -> https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/getCurrent

chrome.tabs.getCurrent(function callback)

If you want the current URL on click of browser action then.

chrome.browserAction.onClicked.addListener( activeTab =>  {
    console.log(activeTab);
});

Body:
I got a script from Stack Overflow for getting the current Chrome tab, but every time I try to run it, this error shows up in Google Chrome:

Uncaught TypeError: Cannot read property 'query' of undefined
Context

https://www.youtube.com/
Stack Trace

**chrome.tabs.query({active: true, currentWindow: true}, tabs => {**
    let url = tabs[0].url;
    // use `url` here inside the callback because it's asynchronous!
});

The code in bold is the highlighted code in the error. I have tried to replace currentWindow with lastFocusedWindow, but that did nothing. The permissions are all correct, and I even added extra permissions that I do not need, as shown here:

"permissions": [
    "tabs",
    "<all_urls>",
    "activeTab" ]

I only need tabs and <all_urls> for my script, but I have activeTab just in case. What is the problem here, and how can I fix it?


问:
RegEx remove part of string and and replace another part
I have a challenge getting the desired result with RegEx (using C#) and I hope that the community can help.

I have a URL in the following format:
https://somedomain.com/subfolder/category/?abc=text:value&ida=0&idb=1

I want make two modifications, specifically:

1) Remove everything after 'value' e.g. '&ida=0&idb=1'

2) Replace 'category' with e.g. 'newcategory'

So the result is:
https://somedomain.com/subfolder/newcategory/?abc=text:value

I can remove the string from 1) e.g. ^[^&]+ above but I have been unable to figure out how to replace the 'category' substring.

Any help or guidance would be much appreciated.

Thank you in advance.

答:
Use the following:

Find: /(category/.+?value)&.+

Replace: /new$1 or /new\1 depending on your regex flavor

Demo & explanation

Update according to comment.

If the new name is completely_different_name, use the following:

Find: /category(/.+?value)&.+

Replace: /completely_different_name$1

Demo & explanation


问:
PyLint shows "Unable to import" error with app's module file in Django project
I have an app named "diary" in my Django project:

```<code>school_diary/
    diary/
        <standart files inside app>
        views.py
        forms.py
</code>```

Inside my views.py I make this import:

```<code>from . import forms
</code>```

PyLint marks it as error. Here's what I have inside my settings.json:

```<code>{
    ...,
    "python.linting.enabled": true,
    "on.linting.pylintEnabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.maxNumberOfProblems": 200,
    "python.linting.pylintPath": "/home/alantheknight/Python/Environments/secenv/bin/pylint",
    "python.pythonPath": "/home/alantheknight/Python/Environments/secenv/bin/python3.7",
    ...
</code>```

Also, I read about generating .pylintrc, so I ran this command:

```<code>$ pylint --generate-rcfile > ~/.pylintrc
</code>```

Where have I made a mistake?

答:
This is a common error that most people come across.
You have not installed pylint in the same environment that contains your python packages.
The environment selected in VS Code is displayed at the bottom left on the status bar of VS Code.

Take a look at stackoverflow/pylint-unable-to-import-error-how-to-set-pythonpath.
and also pythonVSCodeDocs/docs/troubleshooting_linting

Body:
I have an app named "diary" in my Django project:

school_diary/
    diary/
        <standart files inside app>
        views.py
        forms.py

Inside my views.py I make this import:

from . import forms

PyLint marks it as error. Here's what I have inside my settings.json:

{
    ...,
    "python.linting.enabled": true,
    "on.linting.pylintEnabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.maxNumberOfProblems": 200,
    "python.linting.pylintPath": "/home/alantheknight/Python/Environments/secenv/bin/pylint",
    "python.pythonPath": "/home/alantheknight/Python/Environments/secenv/bin/python3.7",
    ...

Also, I read about generating .pylintrc, so I ran this command:

$ pylint --generate-rcfile > ~/.pylintrc

Where have I made a mistake?


问:
Add a back button in activity
Good morning, Guys I have a code that plays an audio when the activity starts it performs a welcome greeting, however when I go to other activities and return to the main menu the audio is played again I would like to notice that when I use the back action bar button I don't have this problem, but I need to use a button in the fragment or activity, I can't have an action bar in my app

Code to Play audio:

```<code>new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);
</code>```

Code button on fragment:

```<code>button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });
</code>```

答:
Stop your media playback when you leave the activity in onPause of the Activity

```<code>@Override
    public void onPause() {
        super.onPause();
        play.stop();
    }
</code>```

And you don't need to restart the previous activity on click of the button in the second activity, you just need to call onBackPressed() to go to the previous activity.

```<code>button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

       onBackPressed();
    }

});
</code>```

Title: Add a back button in activity

Body:
Good morning, Guys I have a code that plays an audio when the activity starts it performs a welcome greeting, however when I go to other activities and return to the main menu the audio is played again I would like to notice that when I use the back action bar button I don't have this problem, but I need to use a button in the fragment or activity, I can't have an action bar in my app

Code to Play audio:

new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.audioboatarde);
                play.start();
            }
        }, 1000);

Code button on fragment:

button = view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent intent1 = new Intent(getContext(), MainActivity.class);
             startActivity(intent1);
        }

    });

Body:
Stop your media playback when you leave the activity in onPause of the Activity

@Override
    public void onPause() {
        super.onPause();
        play.stop();
    }

And you don't need to restart the previous activity on click of the button in the second activity, you just need to call onBackPressed() to go to the previous activity.

button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

       onBackPressed();
    }

});


问:
Is there a way to make babel embed @babel/runtime?
I'm using @babel/plugin-transform-runtime to transpile async/await statements with babel.

Only problem I have is that @babel/plugin-transform-runtime needs @babel/runtime at runtime.

I just cannot find a simple way to get babel to inline the helper functions.

```<code>var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
</code>```

What I want:

```<code>var _interopRequireDefault = /* resolved definition */

var _regenerator = /* resolved definition */

var _asyncToGenerator2 = /* resolved definition */
</code>```

答:
I opened an issue on the babel github project.

It is possible to embed some functions with the option:

```<code>"helpers": false
</code>```

However runtime-generator cannot be embedded at the time.

Body:
I'm using @babel/plugin-transform-runtime to transpile async/await statements with babel.

Only problem I have is that @babel/plugin-transform-runtime needs @babel/runtime at runtime.

I just cannot find a simple way to get babel to inline the helper functions.

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

What I want:

var _interopRequireDefault = /* resolved definition */

var _regenerator = /* resolved definition */

var _asyncToGenerator2 = /* resolved definition */

Body:
I opened an issue on the babel github project.

It is possible to embed some functions with the option:

"helpers": false

However runtime-generator cannot be embedded at the time.


问:
How do I deal with "undefined reference to `regcomp'" error
I'm new to Eclipse environment and I'm trying to write a C program in Eclipse installed in Windows 10. Compiler I use is MinGW latest version installed through MSYS2. The program I've written has got regular expressions used in it. When I try to build the code, I get the following errors-

21: undefined reference to regcomp'
35: undefined reference toregexec'
enter image description here

Can anyone help me resolve this issue??

答:
If you have #include <regex.h> in your code and it compiles then it looks like you have the library installed.

But undefined reference to 'regexec' is a linker error, which means you're not linking with the library that you are calling functions of.

So you need to link with this library, probably by adding the linker flag -lregex.


问:
Docker multiple ports (frontend&backend) not working
I'm very new to Docker and CI's so please be don't grill me :)

I'm on Linode and I would like to to run the frontend(react) and backend(python) on the same server. Both will be on separate ports, unless you tell me that this is a wrong approach.

Now, I'm running Jenkins on port 8081 and have two individual jobs:

Backend Jenkins:

```<code>IMAGE = "my_docker_flask:latest"
image = docker.build("${IMAGE}");
def container = image.run('-p 5000:5000')
def contport = container.port(5000)
</code>```

Backend Dockerfile (flask):

```<code>FROM python:2.7
WORKDIR app
COPY . .
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]
</code>```

Frontend Jenkins:

```<code>IMAGE = "reactapp"
image = docker.build("${IMAGE}")
def container = image.run('-p 6000:6000')
def contport = container.port(6000)
</code>```

Frontend Dockerfile:

```<code>FROM nginx
COPY build /var/www
</code>```

The backend works fine when I open my Linode's IP with port 5000 but the 6000 does not work. I even tried with 3333 but that does not work either and.

Here's my docker ps -a:

```<code>reactapp  "nginx -g 'daemon of…"   41 seconds ago      Up 40 seconds       80/tcp, 0.0.0.0:6000->6000/tcp
reactapp  "nginx -g 'daemon of…"   2 days ago          Up 2 days           80/tcp, 0.0.0.0:3333->3333/tcp
my_docker_flask:latest   "python app.py"   2 days ago          Up 2 days           0.0.0.0:5000->5000/tcp
</code>```

Can please someone help me?

How can I run multiple apps on different ports using the same IP?

EDIT

I have fixed it but changing to the below:

```<code>COPY build /usr/share/nginx/html
</code>```

and

```<code>def container = image.run('-p 5000:80')
</code>```

答:
```<code>80/tcp, 0.0.0.0:6000->6000/tcp
</code>```

Looking at this carefully, we can know that your reactapp service is being served at port 80 within the container. But you are trying to map the port 6000 in the container to port 6000 outside. Certainly, you will not be able to access a service where it is not being served at all.

Also, the reason behind This site can’t be reached - ERR_UNSAFE_PORT is because you are using the port 6000 which is restricted by the Chrome browser.

Solution:

map the port 80 only and not any other port as it is being served at.

stop all other services that are using port 80

have only one instance of reactapp service, as we don't want the other instance to block the port.

Body:
I'm very new to Docker and CI's so please be don't grill me :)

I'm on Linode and I would like to to run the frontend(react) and backend(python) on the same server. Both will be on separate ports, unless you tell me that this is a wrong approach.

Now, I'm running Jenkins on port 8081 and have two individual jobs:

Backend Jenkins:

IMAGE = "my_docker_flask:latest"
image = docker.build("${IMAGE}");
def container = image.run('-p 5000:5000')
def contport = container.port(5000)

Backend Dockerfile (flask):

FROM python:2.7
WORKDIR app
COPY . .
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]

Frontend Jenkins:

IMAGE = "reactapp"
image = docker.build("${IMAGE}")
def container = image.run('-p 6000:6000')
def contport = container.port(6000)

Frontend Dockerfile:

FROM nginx
COPY build /var/www

The backend works fine when I open my Linode's IP with port 5000 but the 6000 does not work. I even tried with 3333 but that does not work either and.

Here's my docker ps -a:

reactapp  "nginx -g 'daemon of…"   41 seconds ago      Up 40 seconds       80/tcp, 0.0.0.0:6000->6000/tcp
reactapp  "nginx -g 'daemon of…"   2 days ago          Up 2 days           80/tcp, 0.0.0.0:3333->3333/tcp
my_docker_flask:latest   "python app.py"   2 days ago          Up 2 days           0.0.0.0:5000->5000/tcp

Can please someone help me?

How can I run multiple apps on different ports using the same IP?

EDIT

I have fixed it but changing to the below:

COPY build /usr/share/nginx/html

and

def container = image.run('-p 5000:80')

Body:
80/tcp, 0.0.0.0:6000->6000/tcp

Looking at this carefully, we can know that your reactapp service is being served at port 80 within the container. But you are trying to map the port 6000 in the container to port 6000 outside. Certainly, you will not be able to access a service where it is not being served at all.

Also, the reason behind This site can’t be reached - ERR_UNSAFE_PORT is because you are using the port 6000 which is restricted by the Chrome browser.

Solution:

map the port 80 only and not any other port as it is being served at.

stop all other services that are using port 80

have only one instance of reactapp service, as we don't want the other instance to block the port.


问:
How to make a CustomControl with a particular shape that inherits from the Button control?
I have created a MenuBarButton.cs CustomControl in which I inherit from the Button class to add an image and some text to the button like in the picture shown below.

Here's my control class:

public class MenuBarButton : Button
{
    public static readonly DependencyProperty ItemNameProperty =
        DependencyProperty.Register(
            "ItemName",             // Property name
            typeof(string),         // Property type
            typeof(MenuBarButton)   // Property owner
            );
    public string ItemName
    {
        get { return (string)GetValue(ItemNameProperty); }
        set { SetValue(ItemNameProperty, value); }
    }

    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            "Source",               // Property name
            typeof(ImageSource),    // Property type
            typeof(MenuBarButton)   // Property owner
            );
    public ImageSource Source
    {
        get { return (ImageSource)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }
    static MenuBarButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MenuBarButton),
            new FrameworkPropertyMetadata(typeof(MenuBarButton))
            );
    }
}
```

<p>And the Style is where I'm stuck a bit. So far I have this:</p>

<pre class="lang-xml prettyprint-override"><code><Style TargetType="{x:Type local:MenuBarButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MenuBarButton}">
                <Button>
                    <Grid HorizontalAlignment="Center">
                        <Image Source="{TemplateBinding Source}" />
                        <TextBlock Text="{TemplateBinding ItemName}" />
                    </Grid>
                </Button>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

But ideally I'd like to define a custom shape for the button while keeping the rest of the functionalities such as hovering over and pressing the button. I really wanted to do this with a custom control cause I got tired of having to create a buttons with an Image and a TextBlock inside over and over.

Do I have to define a separate style for the Button's shape explicitly or is there a way I can do this inside of the MenuBarButtonStyle dictionary?

答:
You could copy the default template for the Button and then edit as per your requirements. The easiest way to do this would be add a <Button /> element to a XAML source file in Visual Studio, switch to design mode, right-click on the Button and choose Edit Template and then Edit a copy ....

You could then for example replace the Border element in the default template with an Ellipse.

Below is an example:

```<code><Style x:Key="FocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
    <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
    <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
    <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Padding" Value="1"/>
    <Setter Property="Width" Value="200" />
    <Setter Property="Height" Value="200" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                    <Ellipse x:Name="border" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="{TemplateBinding BorderThickness}" Fill="{TemplateBinding Background}" SnapsToDevicePixels="true"
                                 Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
                    <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsDefaulted" Value="true">
                        <Setter Property="Stroke" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="true">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                        <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Usage:

```<code><Button Style="{StaticResource ButtonStyle1}" Content="Button..." />
</code>```

Appearance:

Body:
I have created a MenuBarButton.cs CustomControl in which I inherit from the Button class to add an image and some text to the button like in the picture shown below.

Here's my control class:

public class MenuBarButton : Button
{
    public static readonly DependencyProperty ItemNameProperty =
        DependencyProperty.Register(
            "ItemName",             // Property name
            typeof(string),         // Property type
            typeof(MenuBarButton)   // Property owner
            );
    public string ItemName
    {
        get { return (string)GetValue(ItemNameProperty); }
        set { SetValue(ItemNameProperty, value); }
    }

    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            "Source",               // Property name
            typeof(ImageSource),    // Property type
            typeof(MenuBarButton)   // Property owner
            );
    public ImageSource Source
    {
        get { return (ImageSource)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }
    static MenuBarButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MenuBarButton),
            new FrameworkPropertyMetadata(typeof(MenuBarButton))
            );
    }
}

And the Style is where I'm stuck a bit. So far I have this:

But ideally I'd like to define a custom shape for the button while keeping the rest of the functionalities such as hovering over and pressing the button. I really wanted to do this with a custom control cause I got tired of having to create a buttons with an Image and a TextBlock inside over and over.

Do I have to define a separate style for the Button's shape explicitly or is there a way I can do this inside of the MenuBarButtonStyle dictionary?

Body:
You could copy the default template for the Button and then edit as per your requirements. The easiest way to do this would be add a <Button /> element to a XAML source file in Visual Studio, switch to design mode, right-click on the Button and choose Edit Template and then Edit a copy ....

You could then for example replace the Border element in the default template with an Ellipse.

Below is an example:

<Style x:Key="FocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
    <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
    <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
    <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Padding" Value="1"/>
    <Setter Property="Width" Value="200" />
    <Setter Property="Height" Value="200" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                    <Ellipse x:Name="border" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="{TemplateBinding BorderThickness}" Fill="{TemplateBinding Background}" SnapsToDevicePixels="true"
                                 Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
                    <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsDefaulted" Value="true">
                        <Setter Property="Stroke" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="true">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Fill" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                        <Setter Property="Stroke" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                        <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Usage:

<Button Style="{StaticResource ButtonStyle1}" Content="Button..." />

Appearance:


问:
How to format Interval type to HH:MM format?
I am using oracle DB with below column

START_TIME INTERVAL DAY(0) TO SECOND(0)

I am using jdbc template in java code to access this value using the row mapper and getString() method like below: (I am running a basic select query to fetch values from DB)

```<code>String startTime = rs.getString("START_TIME");
</code>```

and the value I get is in this format

```<code>System.out.println(startTime); // 0 9:30:0.0
</code>```

I am not able to format this value in the HH:MM format string. I do not need the seconds as I am ignoring that value. So what I want is something like this 09:30

Found this which looks similar but I am using swagger open API yaml based generation for DTOs and don't know how can I achieve this. Also, I am not using hibernate. It's plain JDBC Template.

EDIT: Observed that when I have +00 11:00:00.000000 in the DB, the rs.getString("START_TIME") fetches 0 11:0:0.0 and when +00 09:30:00.000000 it fetches 0 9:30:0.0 but my requirement is 11:00 and 09:30. Hope this helps a little more.

答:
Find the substring from after the first space character to the second : colon character and left-pad it with a zero so that it is 5 characters long.

public static String getHoursMinutesFromInterval( final String time )
{
  String hhmm = time.replaceAll( "^0 (\\d{1,2}:\\d{2}):\\d+\\.\\d+$", "0$1" );
  if ( hhmm.length() > 5 )
  {
    hhmm = hhmm.substring(1, 6);
  }
  return hhmm;
}
```

Body:
I am using oracle DB with below column

START_TIME INTERVAL DAY(0) TO SECOND(0)

I am using jdbc template in java code to access this value using the row mapper and getString() method like below: (I am running a basic select query to fetch values from DB)

String startTime = rs.getString("START_TIME");

and the value I get is in this format

System.out.println(startTime); // 0 9:30:0.0

I am not able to format this value in the HH:MM format string. I do not need the seconds as I am ignoring that value. So what I want is something like this 09:30

Found this which looks similar but I am using swagger open API yaml based generation for DTOs and don't know how can I achieve this. Also, I am not using hibernate. It's plain JDBC Template.

EDIT: Observed that when I have +00 11:00:00.000000 in the DB, the rs.getString("START_TIME") fetches 0 11:0:0.0 and when +00 09:30:00.000000 it fetches 0 9:30:0.0 but my requirement is 11:00 and 09:30. Hope this helps a little more.


问:
Annotation processors must be explicitly declared now
```<code>Error:Execution failed for task ':laMusique2May2016:javaPreCompileRelease'.
> Annotation processors must be explicitly declared now.  The following dependencies on the compile classpath are found to contain annotation processor.  Please add them to the annotationProcessor configuration.
    - auto-value-1.1.jar (com.google.auto.value:auto-value:1.1)
  Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior.  Note that this option is deprecated and will be removed in the future.
  See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.
</code>```

I am seeing this issue, but the problem is auto-value-1.1.jar is not in my gradle files

答:
For me, this issue happened because jitpack wasn't placed as the last entry in root grade.

```<code>allprojects {
    repositories {
        // ... other repositories
        maven { url "https://jitpack.io" }
    }
}

</code>```

The solution was taken from @hotchemi comment in https://github.com/permissions-dispatcher/PermissionsDispatcher/issues/535#issuecomment-432190926

Body:
Error:Execution failed for task ':laMusique2May2016:javaPreCompileRelease'.
> Annotation processors must be explicitly declared now.  The following dependencies on the compile classpath are found to contain annotation processor.  Please add them to the annotationProcessor configuration.
    - auto-value-1.1.jar (com.google.auto.value:auto-value:1.1)
  Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior.  Note that this option is deprecated and will be removed in the future.
  See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.

I am seeing this issue, but the problem is auto-value-1.1.jar is not in my gradle files

Body:
For me, this issue happened because jitpack wasn't placed as the last entry in root grade.

allprojects {
    repositories {
        // ... other repositories
        maven { url "https://jitpack.io" }
    }
}

The solution was taken from @hotchemi comment in https://github.com/permissions-dispatcher/PermissionsDispatcher/issues/535#issuecomment-432190926


问:
Rust lifetime subtyping doesn't work with Cell
Given a value of type Vec<&'static str>, I can freely convert that to Vec<&'r str>, as 'r is a subregion of 'static. That seems to work for most types, e.g. Vec, pairs etc. However, it doesn't work for types like Cell or RefCell. Concretely, down_vec compiles, but down_cell doesn't:

use std::cell::Cell;

fn down_vec<'p, 'r>(x: &'p Vec<&'static str>) -> &'p Vec<&'r str> {
    x
}

fn down_cell<'p, 'r>(x: &'p Cell<&'static str>) -> &'p Cell<&'r str> {
    x
}
```

<p>Giving the error:</p>

```error[E0308]: mismatched types
 --> src/lib.rs:9:5
  |
9 |     x
  |     ^ lifetime mismatch
  |
  = note: expected reference `&'p std::cell::Cell<&'r str>`
             found reference `&'p std::cell::Cell<&'static str>`
note: the lifetime `'r` as defined on the function body at 8:18...
 --> src/lib.rs:8:18
  |
8 | fn down_cell<'p, 'r>(x: &'p Cell<&'static str>) -> &'p Cell<&'r str> {
  |                  ^^
  = note: ...does not necessarily outlive the static lifetime
```

Why does this not work for Cell? How does the compiler track that it doesn't work? Is there an alternative that can make it work?

答:
Cell and RefCell are different because they allow mutation of the internal value through a shared reference.

To see why this is important, we can write a function that uses down_cell to leak a reference to freed memory:

```<code>fn oops() -> &'static str {
    let cell = Cell::new("this string doesn't matter");
    let local = String::from("this string is local to oops");
    let broken = down_cell(&cell);  // use our broken function to rescope the Cell
    broken.set(&local);             // use the rescoped Cell to mutate `cell`
    cell.into_inner()               // return a reference to `local`
}                                   // uh-oh! `local` is dropped here
</code>```

oops contains no unsafe blocks, but it compiles, so in order to prevent accessing freed memory the compiler must reject down_cell.

The type level explanation for why this is so is because Cell<T> and RefCell<T> contain an UnsafeCell<T>, which makes them invariant in T, while Box<T> and Vec<T> are covariant in T.

The reason Vec, Box and other container-like structures can be covariant is because those containers require &mut access to mutate their contents, and &mut T is itself invariant in T. You couldn't write a function like oops using down_vec -- the compiler wouldn't allow it.

References

The Subtyping and Variance chapter of the Rustonomicon

How does the Rust compiler know `Cell` has internal mutability?

Why does linking lifetimes matter only with mutable references?

Body:
Given a value of type Vec<&'static str>, I can freely convert that to Vec<&'r str>, as 'r is a subregion of 'static. That seems to work for most types, e.g. Vec, pairs etc. However, it doesn't work for types like Cell or RefCell. Concretely, down_vec compiles, but down_cell doesn't:

use std::cell::Cell;

fn down_vec<'p, 'r>(x: &'p Vec<&'static str>) -> &'p Vec<&'r str> {
    x
}

fn down_cell<'p, 'r>(x: &'p Cell<&'static str>) -> &'p Cell<&'r str> {
    x
}

Giving the error:

error[E0308]: mismatched types
 --> src/lib.rs:9:5
  |
9 |     x
  |     ^ lifetime mismatch
  |
  = note: expected reference `&'p std::cell::Cell<&'r str>`
             found reference `&'p std::cell::Cell<&'static str>`
note: the lifetime `'r` as defined on the function body at 8:18...
 --> src/lib.rs:8:18
  |
8 | fn down_cell<'p, 'r>(x: &'p Cell<&'static str>) -> &'p Cell<&'r str> {
  |                  ^^
  = note: ...does not necessarily outlive the static lifetime

Why does this not work for Cell? How does the compiler track that it doesn't work? Is there an alternative that can make it work?

Body:
Cell and RefCell are different because they allow mutation of the internal value through a shared reference.

To see why this is important, we can write a function that uses down_cell to leak a reference to freed memory:

fn oops() -> &'static str {
    let cell = Cell::new("this string doesn't matter");
    let local = String::from("this string is local to oops");
    let broken = down_cell(&cell);  // use our broken function to rescope the Cell
    broken.set(&local);             // use the rescoped Cell to mutate `cell`
    cell.into_inner()               // return a reference to `local`
}                                   // uh-oh! `local` is dropped here

oops contains no unsafe blocks, but it compiles, so in order to prevent accessing freed memory the compiler must reject down_cell.

The type level explanation for why this is so is because Cell<T> and RefCell<T> contain an UnsafeCell<T>, which makes them invariant in T, while Box<T> and Vec<T> are covariant in T.

The reason Vec, Box and other container-like structures can be covariant is because those containers require &mut access to mutate their contents, and &mut T is itself invariant in T. You couldn't write a function like oops using down_vec -- the compiler wouldn't allow it.

References

The Subtyping and Variance chapter of the Rustonomicon

How does the Rust compiler know `Cell` has internal mutability?

Why does linking lifetimes matter only with mutable references?


问:
Make two geom_bar() plots base on different columns in one plot
I have a data frame that looks like this:

```<code> Year     Women       Men
1 2013    145169      889190
2 2014    119064      849778
3 2015    210107     1079592
4 2016    221217     1427639
5 2017    205000     1692592
6 2018    273721     1703456
7 2019    434407     2010493
</code>```

I want to make a geom_bar, where x is a year and every year has two bars for a number from Women and Men. I have found a solution where this table should looks different, but I'm wondering if there is an option to work with this one. Thank You for any help :)

答:
You can use the following code

```<code>library(tidyverse)

df %>%
      pivot_longer(cols = -c(Year,Sl), values_to = "Value", names_to = "Name") %>%
      ggplot(aes(x = Year, y = Value, fill = Name))+geom_col(position = "dodge")
</code>```

Data

```<code>df = structure(list(Sl = 1:7, Year = 2013:2019, Women = c(145169L,
119064L, 210107L, 221217L, 205000L, 273721L, 434407L), Men = c(889190L,
849778L, 1079592L, 1427639L, 1692592L, 1703456L, 2010493L)), class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
I have a data frame that looks like this:

 Year     Women       Men
1 2013    145169      889190
2 2014    119064      849778
3 2015    210107     1079592
4 2016    221217     1427639
5 2017    205000     1692592
6 2018    273721     1703456
7 2019    434407     2010493

I want to make a geom_bar, where x is a year and every year has two bars for a number from Women and Men. I have found a solution where this table should looks different, but I'm wondering if there is an option to work with this one. Thank You for any help :)

Body:
You can use the following code

library(tidyverse)

df %>%
      pivot_longer(cols = -c(Year,Sl), values_to = "Value", names_to = "Name") %>%
      ggplot(aes(x = Year, y = Value, fill = Name))+geom_col(position = "dodge")

Data

df = structure(list(Sl = 1:7, Year = 2013:2019, Women = c(145169L,
119064L, 210107L, 221217L, 205000L, 273721L, 434407L), Men = c(889190L,
849778L, 1079592L, 1427639L, 1692592L, 1703456L, 2010493L)), class = "data.frame", row.names = c(NA,
-7L))


问:
How to spawn child process and communicate with it Deno?
Suppose I have 2 script, father.ts and child.ts, how do I spawn child.ts from father.ts and periodically send message from father.ts to child.ts ?</p>

答:
You have to use the Worker API

father.ts

```<code>const worker = new Worker("./child.ts", { type: "module", deno: true });
worker.postMessage({ filename: "./log.txt" });
</code>```

child.ts

```<code>self.onmessage = async (e) => {
  const { filename } = e.data;
  const text = await Deno.readTextFile(filename);
  console.log(text);
  self.close();
};
</code>```

You can send messages using .postMessage

Body:
You have to use the Worker API

father.ts

const worker = new Worker("./child.ts", { type: "module", deno: true });
worker.postMessage({ filename: "./log.txt" });

child.ts

self.onmessage = async (e) => {
  const { filename } = e.data;
  const text = await Deno.readTextFile(filename);
  console.log(text);
  self.close();
};

You can send messages using .postMessage


问:
Apache Beam count of unique elements
I have an Apache Beam job, which injest data from PubSub and then load into BigQuery,
I transform PubSub message to pojo with fields

id,
  name, count

Count mean the count of not unique elements into single ingest.

If i load from PubSub 3 elements, two of which are same, then i need to load into BigQuery 2 elements, one of them will have count 2.

I wonder how easily make it in Apache Beam.
I tried to make it wia DoFn or MapElements, but there i can process only single element.
I also tried to convert element to KV, and then count, but i have non determenistics coder.

In usual java app i can simple use equals or via Map, but here in Apache beam all is different.

答:
The simple and right approach would be to use Count.<T>perElement(), like this :

```<code>Pipeline p = ...;
PCollection<T> elements = p.apply(...); // read elements
PCollection<KV<T, Long>> elementsCounts =
    elements.apply(Count.<T>perElement());
PCollection<TableRow> results = elementsCounts.apply(ParDo.of(
    new FormatOutputFn()));
</code>```

Though, right, you need to have a deterministic elements coder for that. So if it's not case (as I understand from what you said above) you need to add a step before Count to transform an element into different representation where it will be possible to have a deterministic coder (like AvroCoder, for example).

If it's not possible for some reasons, then another workaround could be to calculate an uniq hash for every element (but the hash value must be deterministic as well), create a KV for every element with new hash as a Key and element as a Value and use GroupByKey downstream to have a grouped tuple of the same values.

Also, please note, that since PubSub is an unbounded source, you need to "window" your input by any type of Windows strategy (except Global one) since all your group/combine operations should be done inside a window. Take a look on WindowedWordCount as an example of solution for similar problem.

Title: Apache Beam count of unique elements

Body:
The simple and right approach would be to use Count.<T>perElement(), like this :

Pipeline p = ...;
PCollection<T> elements = p.apply(...); // read elements
PCollection<KV<T, Long>> elementsCounts =
    elements.apply(Count.<T>perElement());
PCollection<TableRow> results = elementsCounts.apply(ParDo.of(
    new FormatOutputFn()));

Though, right, you need to have a deterministic elements coder for that. So if it's not case (as I understand from what you said above) you need to add a step before Count to transform an element into different representation where it will be possible to have a deterministic coder (like AvroCoder, for example).

If it's not possible for some reasons, then another workaround could be to calculate an uniq hash for every element (but the hash value must be deterministic as well), create a KV for every element with new hash as a Key and element as a Value and use GroupByKey downstream to have a grouped tuple of the same values.

Also, please note, that since PubSub is an unbounded source, you need to "window" your input by any type of Windows strategy (except Global one) since all your group/combine operations should be done inside a window. Take a look on WindowedWordCount as an example of solution for similar problem.


问:
Rotate rigid body in one direction with AddTorque
I have a main camera that rotates around an object (which I already move with AddForce). Using AddTorque, I would like the object to rotate its Y axis of rotation in the direction in which the camera's Y axis of rotation points so as to simulate the rotation of a person turning around. To do this I thought of using a force that gave me 0 when the Y axes of the two objects are the same, but I tried and the rigidbody covers only one part of the rotation of the camera while the other part is as if it not is detected.

```<code>   var currentR = rb.rotation.y;
 var targetR = Camera.main.transform.rotation.y;
 rb.AddTorque(transform.up * 1000f * (targetR - currentR));
</code>```

rotation my object
desired rotation

答:
```<code>    Vector3 camForward = Camera.main.transform.forward;
Vector3 rbForward = rb.transform.forward;

Vector3 torque = Vector3.Cross(camForward, rbForward);
rb.AddTorque(torque);
</code>```

Body:
I have a main camera that rotates around an object (which I already move with AddForce). Using AddTorque, I would like the object to rotate its Y axis of rotation in the direction in which the camera's Y axis of rotation points so as to simulate the rotation of a person turning around. To do this I thought of using a force that gave me 0 when the Y axes of the two objects are the same, but I tried and the rigidbody covers only one part of the rotation of the camera while the other part is as if it not is detected.

   var currentR = rb.rotation.y;
 var targetR = Camera.main.transform.rotation.y;
 rb.AddTorque(transform.up * 1000f * (targetR - currentR));

rotation my object
desired rotation


问:
How to create custom types using typing module?
I am trying to create a custom type on Python 3.7 typing module. The new type (say Struct) should be same as type tuple. In Python3.6, I was able to do same by Typing.GenericMeta and typing.TupleMeta.

With typing module updated in Python3.7, GenericMeta and TupleMeta do not exist, and the special class that I would like to subclass, is not possible. e.g. _VariadicGenericAlias.

What I really want is something similar to:

```<code>Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True)
</code>```

and

```<code>assert _origin(Struct[int, str]) == Struct
</code>```

Note:

```<code>def _origin(typ: Any) -> Any:
    """Get the original (the bare) typing class.
    Get the unsubscripted version of a type. Supports generic types, Union,
    Callable, and Tuple. Returns None for unsupported types. Examples::
        get_origin(int) == None
        get_origin(ClassVar[int]) == None
        get_origin(Generic) == Generic
        get_origin(Generic[T]) == Generic
        get_origin(Union[T, int]) == Union
        get_origin(List[Tuple[T, T]][int]) == list
    """
    if isinstance(typ, _GenericAlias):
        return typ.__origin__ if typ.__origin__ is not ClassVar else None
    if typ is Generic:
        return Generic
    return None
</code>```

答:
Figured out solution that worked for me. Made use of "name" param that was somewhere hidden in _GenericAlias:</p>

```<code>Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True, name="Struct")
</code>```

Body:
I am trying to create a custom type on Python 3.7 typing module. The new type (say Struct) should be same as type tuple. In Python3.6, I was able to do same by Typing.GenericMeta and typing.TupleMeta.

With typing module updated in Python3.7, GenericMeta and TupleMeta do not exist, and the special class that I would like to subclass, is not possible. e.g. _VariadicGenericAlias.

What I really want is something similar to:

Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True)

and

assert _origin(Struct[int, str]) == Struct

Note:

def _origin(typ: Any) -> Any:
    """Get the original (the bare) typing class.
    Get the unsubscripted version of a type. Supports generic types, Union,
    Callable, and Tuple. Returns None for unsupported types. Examples::
        get_origin(int) == None
        get_origin(ClassVar[int]) == None
        get_origin(Generic) == Generic
        get_origin(Generic[T]) == Generic
        get_origin(Union[T, int]) == Union
        get_origin(List[Tuple[T, T]][int]) == list
    """
    if isinstance(typ, _GenericAlias):
        return typ.__origin__ if typ.__origin__ is not ClassVar else None
    if typ is Generic:
        return Generic
    return None

Body:
Figured out solution that worked for me. Made use of "name" param that was somewhere hidden in _GenericAlias:

Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True, name="Struct")


问:
Xcode Compile Flag to Suppress Nullability Warnings not Working?
For a limited time I want to suppress these kind of warnings the compiler is showing me in Xcode 7.3.1:

<File>: Pointer is missing a nullability type specifier (_Nonnull, _Nullable, or _Null_unspecified)

I have added this compiler flag to all classes under My Target/Build Phases/Compile Sources:
-Wnullability-completeness

But it's not working - the warnings are still shown. How can I get rid of the warnings?

答:
Settings for Xcode 11.5 when using project with mixed sources, ObjC and Swift:</p>

```<code>WARNING_CFLAGS = $(inherited) -Wno-nullability-completeness
OTHER_SWIFT_FLAGS = $(inherited) -Xcc -Wno-nullability-completeness
</code>```

Body:
Settings for Xcode 11.5 when using project with mixed sources, ObjC and Swift:

WARNING_CFLAGS = $(inherited) -Wno-nullability-completeness
OTHER_SWIFT_FLAGS = $(inherited) -Xcc -Wno-nullability-completeness


问:
aes-256-gcm encrypt with PHP, decrypt with javascript
I have some problems to decrypt my data in javascript side.
I successfully with aes-256-cbc but with aes-256-gcm, I have some trouble.

So I have an API in PHP and a front end in Reactjs.

See below the PHP side:

```<code>$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$sEncrypted = openssl_encrypt(
     json_encode($aData, true),
     $algo,
     $sKey,
     $options=0,
     $iv,
     $tag
);

$aEncrypt = [
    "ciphertext" => base64_encode($sEncrypted),
    "iv"         => base64_encode($iv),
    "tag"        => base64_encode($tag)
];

return $aEncrypt;
</code>```

on my javascript side:

```<code>import crypto from 'crypto';

// Retrieve json
let obj_json = JSON.parse(data);

// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');

</code>```

I get :

```<code>Error: Unsupported state or unable to authenticate data
</code>```

I tried different library (reactjs) but I get always this error.
Is there a problem with encoding iv or tag ?

Thank you :D

答:
The answer can be found here: Encrypt string in PHP and decrypt in Node.js

It might need a bit of tuning for your own set-up but it should work !

Cheers.

Body:
I have some problems to decrypt my data in javascript side.
I successfully with aes-256-cbc but with aes-256-gcm, I have some trouble.

So I have an API in PHP and a front end in Reactjs.

See below the PHP side:

$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$sEncrypted = openssl_encrypt(
     json_encode($aData, true),
     $algo,
     $sKey,
     $options=0,
     $iv,
     $tag
);

$aEncrypt = [
    "ciphertext" => base64_encode($sEncrypted),
    "iv"         => base64_encode($iv),
    "tag"        => base64_encode($tag)
];

return $aEncrypt;

on my javascript side:

import crypto from 'crypto';

// Retrieve json
let obj_json = JSON.parse(data);

// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');

I get :

Error: Unsupported state or unable to authenticate data

I tried different library (reactjs) but I get always this error.
Is there a problem with encoding iv or tag ?

Thank you :D


问:
Modal Popup Extender animation in ASP.net
I am currently developing an ASP.net c# application. I have a grid view which has bound link buttons inside. When the link button is pressed I want to display the modal popup using a fade in animation and a fade out animation when a button inside the modal popup is clicked.

I have added the animation extender into the code and set the TargetControlID to the ID of the link button, however, when I try to run the website it displays the error System.InvalidOperationException  the TargetControID of ModalPopupExtender is not valid. A control with ID 'sofLink' could not be found. sofLink is the ID of the LinkButton.

Below is the code for the grid view

```<code><asp:GridView ID="tblSoftware" runat="server" Width="100%"
                        EnableModelValidation="True" AutoGenerateColumns="False"
                        onselectedindexchanged="tblSoftware_SelectedIndexChanged"
                        CellPadding="2">
                        <Columns>
                            <asp:TemplateField HeaderText="Software Name">
                                <ItemTemplate>
                                <asp:LinkButton ID="sofLink" Text='<%# Bind("sof_softwareName") %>'
                                 CommandName="sofID" OnCommand="GetSoftwareModal" CommandArgument='<%# Eval("sof_id") %>' runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="sof_platform" HeaderText="Platform" ReadOnly="True" SortExpression="sof_platform" />
                        </Columns>
                        <HeaderStyle CssClass="gridHeader" />
                        <PagerSettings Position="Bottom" />
                        <PagerStyle HorizontalAlign="Right" VerticalAlign="Middle" CssClass="gridPage" />
                        <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
                    </asp:GridView>
</code>```

And below is the code for the ModalPopupExtender

```<code><ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="sofLink"
                    PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />

               <asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
                    <asp:Label ID="softwareTitle" Font-Bold="true" Font-Size="Medium" runat="server" Width="100%" style="text-align: center;" /><br /><br />
                    <asp:Literal ID="litSoftware" runat="server"></asp:Literal>
                    <asp:Button id="OKButton" runat="server" Text="Close" style="position: relative; right: 0px; width: 100px;" />
               </asp:Panel>

               <asp:ScriptManager ID="asm" runat="server" />
</code>```

And below is the code for the animation

```<code>       <ajaxToolkit:AnimationExtender ID="popupAnimation" runat="server"
            TargetControlID="sofLink">

            <Animations>
                <OnClick>
                    <Parallel AnimationTarget="ModalPanel"
                    Duration="0.3" Fps="25">
                    <FadeIn />
                    </Parallel>
                </OnClick>
            </Animations>
       </ajaxToolkit:AnimationExtender>
</code>```

Thanks for any help you can provide.

答:
You could use a hidden button and use it's ID as TargetControlID of the ModalPopupExtender.

```<code><asp:Button id="btnShowPopup" runat="server" style="display:none" />
</code>```

Then you can call the button's click clientside if you want to show the popup immediately without postback in the follwoing way:

```<code><asp:LinkButton ID="sofLink" runat="server" OnClientClick="javascript:document.getElementById('btnShowPopup').click();return false;">LinkButton</asp:LinkButton>
</code>```

Body:
I am currently developing an ASP.net c# application. I have a grid view which has bound link buttons inside. When the link button is pressed I want to display the modal popup using a fade in animation and a fade out animation when a button inside the modal popup is clicked.

I have added the animation extender into the code and set the TargetControlID to the ID of the link button, however, when I try to run the website it displays the error System.InvalidOperationException  the TargetControID of ModalPopupExtender is not valid. A control with ID 'sofLink' could not be found. sofLink is the ID of the LinkButton.

Below is the code for the grid view

<asp:GridView ID="tblSoftware" runat="server" Width="100%"
                        EnableModelValidation="True" AutoGenerateColumns="False"
                        onselectedindexchanged="tblSoftware_SelectedIndexChanged"
                        CellPadding="2">
                        <Columns>
                            <asp:TemplateField HeaderText="Software Name">
                                <ItemTemplate>
                                <asp:LinkButton ID="sofLink" Text='<%# Bind("sof_softwareName") %>'
                                 CommandName="sofID" OnCommand="GetSoftwareModal" CommandArgument='<%# Eval("sof_id") %>' runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="sof_platform" HeaderText="Platform" ReadOnly="True" SortExpression="sof_platform" />
                        </Columns>
                        <HeaderStyle CssClass="gridHeader" />
                        <PagerSettings Position="Bottom" />
                        <PagerStyle HorizontalAlign="Right" VerticalAlign="Middle" CssClass="gridPage" />
                        <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
                    </asp:GridView>

And below is the code for the ModalPopupExtender

<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="sofLink"
                    PopupControlID="ModalPanel" DropShadow="true" Drag="true" OkControlID="OKButton" />

               <asp:Panel ID="ModalPanel"  runat="server" Width="500px" style="width: auto; height: auto;" CssClass="modalPopup">
                    <asp:Label ID="softwareTitle" Font-Bold="true" Font-Size="Medium" runat="server" Width="100%" style="text-align: center;" />

                    <asp:Literal ID="litSoftware" runat="server"></asp:Literal>
                    <asp:Button id="OKButton" runat="server" Text="Close" style="position: relative; right: 0px; width: 100px;" />
               </asp:Panel>

               <asp:ScriptManager ID="asm" runat="server" />

And below is the code for the animation

       <ajaxToolkit:AnimationExtender ID="popupAnimation" runat="server"
            TargetControlID="sofLink">

            <Animations>
                <OnClick>
                    <Parallel AnimationTarget="ModalPanel"
                    Duration="0.3" Fps="25">
                    <FadeIn />
                    </Parallel>
                </OnClick>
            </Animations>
       </ajaxToolkit:AnimationExtender>

Thanks for any help you can provide.

Body:
You could use a hidden button and use it's ID as TargetControlID of the ModalPopupExtender.

<asp:Button id="btnShowPopup" runat="server" style="display:none" />

Then you can call the button's click clientside if you want to show the popup immediately without postback in the follwoing way:

<asp:LinkButton ID="sofLink" runat="server" OnClientClick="javascript:document.getElementById('btnShowPopup').click();return false;">LinkButton</asp:LinkButton>