问:
Matplotlib ScalarMappable returning only black color
I am using matplotlib to create many plots. The plots involve making many FancyBboxPatches and setting the color for each patch using a ScalarMappable. Each plot corresponds to a "time step" from a physical process. I have made the following minimal working example to illustrate what I am trying to do and the problem I am having.

Suppose there is a file data.txt. If a line has one entry, that value is the time step. If a line has three entries, then the first entry is the x value, the second entry is the y value, and the third entry is the value that will use the ScalarMappable. Here is an example of data.txt:

```<code>1
0   0   0.1
0   1   1
0   2   2
0   3   3
0   4   4
1   0   10
1   1   11
1   2   12
1   3   13
1   4   14
2   0   20
2   1   21
2   2   22
2   3   23
2   4   24
3   0   30
3   1   31
3   2   32
3   3   33
3   4   34
2
1   0   10
1   1   11
1   2   12
1   3   13
1   4   14
2   0   110
2   1   111
2   2   112
2   3   113
2   4   114
3   0   120
3   1   121
3   2   122
3   3   123
3   4   124
4   0   130
4   1   131
4   2   132
4   3   133
4   4   134
3
2   0   110
2   1   111
2   2   112
2   3   113
2   4   114
3   0   1110
3   1   1111
3   2   1112
3   3   1113
3   4   1114
4   0   1120
4   1   1121
4   2   1122
4   3   1123
4   4   1124
5   0   1130
5   1   1131
5   2   1132
5   3   1133
5   4   1134
4
3   0   1110
3   1   1111
3   2   1112
3   3   1113
3   4   1114
4   0   11110
4   1   11111
4   2   11112
4   3   11113
4   4   11114
5   0   11120
5   1   11121
5   2   11122
5   3   11123
5   4   11124
6   0   11130
6   1   11131
6   2   11132
6   3   11133
6   4   11134
</code>```

Here is the script I use to generate the plots:

```<code>#!/usr/bin/env python3

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib.patches import FancyBboxPatch

def parse_file(file_name):

    output = {}

    with open(file_name, 'r') as data_file:
        for line in data_file:
            entries = line.strip().split()
            if len(entries) == 1:
                time_step = int(entries[0])
                output[time_step] = {}
            elif len(entries) == 3:
                x = float(entries[0])
                y = float(entries[1])
                value = float(entries[2])
                output[time_step][(x, y)] = value
            else:
                raise RuntimeError('Anomalous line {} in file {}'.format(line, data_file.name))

    return output

def main():

    fig, axes = plt.subplots()
    axes.set_xlim(-1,10)
    axes.set_ylim(-1,10)

    cmap = cm.plasma
    norm = LogNorm(vmin = 1e-2, vmax = 1.2e4)
    smap = cm.ScalarMappable(norm = norm, cmap = cmap)
    smap.set_array([])
    color_bar = fig.colorbar(mappable = smap, ax = axes, orientation = 'vertical', label = 'label')

    data = parse_file(file_name = 'data.txt')

    for time_step, information in data.items():
        cells = []
        for (x,y), value in information.items():

            cell = FancyBboxPatch(xy = (x - 0.5, y - 0.5),
                                  width = 1, height = 1,
                                  boxstyle = 'square,pad=0.',
                                  edgecolor = 'black',
                                  facecolor = smap.to_rgba(value))

            #print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))

            axes.add_patch(cell)
            cells.append(cell)

        fig.savefig('time-step_{}.png'.format(time_step))

        for cell in cells:
            cell.remove()

if __name__ == '__main__':
    main()
</code>```

And here is one of the plots that is created from running that script:

This plot (and the other three that are created, but not shown here) look fine. So I am confident that I am using ScalarMappable correctly. Now I take the actual data I want to plot, again in a file called data.txt. The format is the same as before, except if a line has four entries, then the first entry is the time step (and I do not care about the other entries). Here is an example of data.txt:

```<code>     2    0.424066E-02    0.200000E+01    0.885500E+08
  0     1    0.850703E+00
  1     3    0.388551E-09
  2     4    0.141948E-06
  2     6    0.126299E-09
  3     9    0.166871E-08
  4    12    0.340738E-08
  5    13    0.246948E-09
  5    14    0.129005E-09
  6    16    0.140043E-08
  6    17    0.885307E-09
 26    76    0.591676E-08
 26    78    0.745985E-08
 27    77    0.263136E-08
 27    78    0.131857E-08
 27    79    0.151193E-05
 27    80    0.265941E-07
 27    81    0.170975E-05
 27    82    0.206355E-08
 27    83    0.334444E-07
 28    80    0.569439E-05
 28    81    0.864904E-07
 28    82    0.114196E-02
 28    83    0.130067E-06
 28    84    0.608045E-04
 28    85    0.351649E-07
 28    86    0.543117E-07
 28    88    0.202115E-08
 29    83    0.225374E-07
 29    84    0.125586E-07
 29    85    0.253383E-04
 29    86    0.943810E-06
 29    87    0.104539E-04
 29    88    0.210241E-06
 29    89    0.196533E-03
 29    90    0.707278E-06
 29    91    0.565096E-05
 29    92    0.840856E-08
 29    93    0.277478E-07
 30    86    0.707234E-09
 30    88    0.549048E-07
 30    89    0.281776E-08
 30    90    0.259219E-04
 30    91    0.298973E-06
 30    92    0.311047E-04
 30    93    0.144465E-05
 30    94    0.632642E-04
 30    95    0.787893E-08
 30    96    0.252900E-08
 31    91    0.425350E-08
 31    92    0.371105E-08
 31    93    0.621869E-05
 31    94    0.680069E-06
 31    95    0.315149E-04
 31    96    0.670790E-07
 31    97    0.568911E-06
 31    98    0.187946E-08
 31    99    0.135024E-07
 32    94    0.384693E-09
 32    96    0.174407E-06
 32    97    0.480216E-08
 32    98    0.244989E-05
 32    99    0.876257E-07
 32   100    0.189371E-04
 32   101    0.264917E-06
 32   102    0.297745E-05
 32   103    0.213684E-09
 33    99    0.110356E-08
 33   100    0.131345E-08
 33   101    0.448076E-06
 33   102    0.106369E-06
 33   103    0.128984E-04
 33   104    0.230382E-07
 33   105    0.266535E-07
 34   102    0.428166E-08
 34   103    0.668242E-08
 34   104    0.842244E-05
 34   105    0.843016E-07
 34   106    0.137510E-05
 34   107    0.879097E-08
 34   108    0.758233E-07
 35   105    0.280844E-06
 35   106    0.639110E-07
 35   107    0.497335E-05
 35   108    0.260105E-06
 35   109    0.188060E-05
 35   110    0.375853E-09
 35   111    0.935430E-09
 35   112    0.138533E-07
 35   113    0.101658E-06
 35   114    0.504823E-09
 35   115    0.989704E-09
 35   116    0.152468E-06
 35   117    0.220735E-07
 36   114    0.430884E-08
 36   116    0.115980E-07
 36   117    0.128436E-05
 36   118    0.814433E-05
 37   117    0.316595E-09
 37   118    0.141531E-06
 37   119    0.965141E-05
 38   119    0.459954E-08
 38   120    0.114088E-04
 38   121    0.198695E-09
 39   120    0.109457E-08
 39   121    0.105160E-04
 39   122    0.254984E-08
 40   122    0.717566E-05
 40   123    0.179081E-08
 40   124    0.352463E-09
 41   123    0.454357E-05
 41   124    0.629608E-07
 41   125    0.777480E-07
 42   124    0.453866E-05
 42   125    0.108592E-06
 42   126    0.320262E-06
 42   127    0.252596E-09
 42   128    0.114714E-09
 43   125    0.372578E-06
 43   126    0.344297E-07
 43   127    0.188018E-05
 43   128    0.631276E-08
 43   129    0.368003E-08
 44   126    0.170090E-07
 44   127    0.121695E-07
 44   128    0.147407E-05
 44   129    0.349674E-07
 44   130    0.767494E-06
 45   128    0.193141E-09
 45   129    0.361851E-06
 45   130    0.573704E-07
 45   131    0.457287E-06
 45   132    0.148004E-08
 45   133    0.164772E-07
 45   134    0.386942E-09
 45   135    0.539603E-08
 45   136    0.227778E-09
 45   137    0.640126E-08
 45   138    0.189604E-09
 45   139    0.754561E-09
 46   132    0.215880E-07
 46   134    0.102847E-08
 46   136    0.628736E-08
 46   137    0.427124E-09
 46   138    0.711664E-07
 46   139    0.749082E-08
 46   140    0.425043E-06
 46   141    0.776307E-08
 46   142    0.102985E-06
 46   143    0.693232E-09
 46   144    0.215846E-08
 47   141    0.660244E-08
 47   142    0.901189E-09
 47   143    0.299062E-07
 47   144    0.195833E-08
 47   145    0.178405E-07
 47   146    0.558550E-09
 47   147    0.235167E-08
 48   144    0.393065E-09
 48   146    0.493252E-08
 48   147    0.299176E-09
 48   148    0.130504E-07
 48   149    0.244654E-09
 48   150    0.143702E-08
 49   149    0.565286E-09
 49   151    0.122230E-08
     3    0.424066E-02    0.200000E+01    0.885500E+08
  0     1    0.850710E+00
  1     3    0.388551E-09
  2     4    0.141948E-06
  2     6    0.126299E-09
  3     9    0.166871E-08
  4    12    0.340738E-08
  5    13    0.246948E-09
  5    14    0.129005E-09
  6    16    0.140043E-08
  6    17    0.885307E-09
 26    76    0.593799E-08
 26    78    0.747463E-08
 27    77    0.283934E-08
 27    78    0.115725E-08
 27    79    0.153613E-05
 27    80    0.236099E-08
 27    81    0.171178E-05
 27    83    0.334426E-07
 28    80    0.575684E-05
 28    81    0.242170E-07
 28    82    0.114208E-02
 28    83    0.133947E-07
 28    84    0.608362E-04
 28    85    0.335522E-08
 28    86    0.543624E-07
 28    88    0.202170E-08
 29    83    0.258149E-07
 29    84    0.107337E-07
 29    85    0.261133E-04
 29    86    0.167223E-06
 29    87    0.108977E-04
 29    88    0.432469E-08
 29    89    0.196993E-03
 29    90    0.997563E-08
 29    91    0.565922E-05
 29    92    0.127589E-09
 29    93    0.277365E-07
 30    86    0.731139E-09
 30    88    0.613936E-07
 30    89    0.984612E-09
 30    90    0.261316E-04
 30    91    0.845314E-07
 30    92    0.324848E-04
 30    93    0.656773E-07
 30    94    0.632706E-04
 30    95    0.335583E-09
 30    96    0.252938E-08
 31    91    0.529954E-08
 31    92    0.394099E-08
 31    93    0.681605E-05
 31    94    0.104800E-06
 31    95    0.315602E-04
 31    96    0.231610E-08
 31    97    0.566868E-06
 31    99    0.135330E-07
 32    94    0.450380E-09
 32    96    0.178679E-06
 32    97    0.955313E-09
 32    98    0.252946E-05
 32    99    0.770340E-08
 32   100    0.191937E-04
 32   101    0.825856E-08
 32   102    0.297762E-05
 33    99    0.128999E-08
 33   100    0.146516E-08
 33   101    0.616111E-06
 33   102    0.539415E-07
 33   103    0.128046E-04
 33   104    0.865090E-09
 33   105    0.266759E-07
 34   102    0.899336E-08
 34   103    0.331924E-08
 34   104    0.850733E-05
 34   105    0.462457E-08
 34   106    0.137714E-05
 34   107    0.199044E-09
 34   108    0.758844E-07
 35   105    0.308602E-06
 35   106    0.470668E-07
 35   107    0.520013E-05
 35   108    0.458893E-07
 35   109    0.185756E-05
 35   111    0.159320E-07
 35   112    0.729552E-09
 35   113    0.101697E-06
 35   114    0.135746E-09
 35   115    0.128676E-06
 35   116    0.231448E-07
 35   117    0.220783E-07
 36   114    0.480979E-08
 36   116    0.921582E-06
 36   117    0.373798E-06
 36   118    0.814449E-05
 37   117    0.888355E-08
 37   118    0.132905E-06
 37   119    0.965147E-05
 38   118    0.360663E-09
 38   119    0.423745E-08
 38   120    0.114090E-04
 39   120    0.109122E-08
 39   121    0.105186E-04
 40   122    0.717737E-05
 40   124    0.352428E-09
 41   123    0.460618E-05
 41   124    0.358205E-09
 41   125    0.777514E-07
 42   124    0.464136E-05
 42   125    0.589035E-08
 42   126    0.320503E-06
 42   128    0.114709E-09
 43   125    0.408148E-06
 43   126    0.567978E-08
 43   127    0.187958E-05
 43   129    0.368007E-08
 44   126    0.258868E-07
 44   127    0.348446E-08
 44   128    0.150718E-05
 44   129    0.167101E-08
 44   130    0.767515E-06
 45   128    0.176686E-09
 45   129    0.403334E-06
 45   130    0.162718E-07
 45   131    0.458273E-06
 45   132    0.196826E-09
 45   133    0.167474E-07
 45   135    0.563904E-08
 45   137    0.655709E-08
 45   139    0.751998E-09
 46   132    0.216010E-07
 46   134    0.107901E-08
 46   136    0.673825E-08
 46   138    0.784839E-07
 46   139    0.220743E-09
 46   140    0.432287E-06
 46   141    0.427029E-09
 46   142    0.103696E-06
 46   144    0.211976E-08
 47   141    0.696394E-08
 47   142    0.585710E-09
 47   143    0.315456E-07
 47   144    0.425448E-09
 47   145    0.181981E-07
 47   146    0.136911E-09
 47   147    0.226765E-08
 48   144    0.442465E-09
 48   146    0.553370E-08
 48   147    0.138932E-09
 48   148    0.128376E-07
 48   150    0.144107E-08
 49   149    0.624360E-09
 49   151    0.123765E-08
</code>```

The script that I use to create the plots is almost the same as before. The only differences are (1) how data.txt is parsed, (2) setting the limits of the x and y axes, and (3) the variable norm. Here is the script:

```<code>#!/usr/bin/env python3

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib.patches import FancyBboxPatch

def parse_file(file_name):

    output = {}

    with open(file_name, 'r') as data_file:
        for line in data_file:
            entries = line.strip().split()
            if len(entries) == 4:
                time_step = int(entries[0])
                output[time_step] = {}
            elif len(entries) == 3:
                x = float(entries[0])
                y = float(entries[1])
                value = float(entries[2])
                output[time_step][(x, y)] = value
            else:
                raise RuntimeError('Anomalous line {} in file {}'.format(line, data_file.name))

    return output

def main():

    fig, axes = plt.subplots()
    axes.set_xlim(0,150)
    axes.set_ylim(0,250)

    cmap = cm.plasma
    norm = LogNorm(vmin = pow(10, -10), vmax = pow(10, -2.2))
    smap = cm.ScalarMappable(norm = norm, cmap = cmap)
    smap.set_array([])
    color_bar = fig.colorbar(mappable = smap, ax = axes, orientation = 'vertical', label = 'label')

    data = parse_file(file_name = 'data.txt')

    for time_step, information in data.items():
        cells = []
        for (x,y), value in information.items():

            cell = FancyBboxPatch(xy = (x - 0.5, y - 0.5),
                                  width = 1, height = 1,
                                  boxstyle = 'square,pad=0.',
                                  edgecolor = 'black',
                                  facecolor = smap.to_rgba(value))

            #print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))

            axes.add_patch(cell)
            cells.append(cell)

        fig.savefig('time-step_{}.png'.format(time_step))

        for cell in cells:
            cell.remove()

if __name__ == '__main__':
    main()
</code>```

Now all of the patches are black. Here is one of the plots that is created:

I do not see anything obviously wrong using the print statement (which is commented out in the script):

```<code>print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))
</code>```

Why are all the FancyBboxPatches black instead of the color I have chosen with the ScalarMappable (and how can I make them be the color I have chosen with the ScalarMappable)?

答: It doesn't look as if the patches are black. I would guess that they are just too small, such that their edge (which is black) takes up the complete area of the patch. You may use a thinner edge, or no edge at all, or you may set the edgecolor to the value of your liking as well. In general, You may also use simple patches like Rectangle instead of the FancyBboxPatch.</p>

Body:
I am using matplotlib to create many plots. The plots involve making many FancyBboxPatches and setting the color for each patch using a ScalarMappable. Each plot corresponds to a "time step" from a physical process. I have made the following minimal working example to illustrate what I am trying to do and the problem I am having.

Suppose there is a file data.txt. If a line has one entry, that value is the time step. If a line has three entries, then the first entry is the x value, the second entry is the y value, and the third entry is the value that will use the ScalarMappable. Here is an example of data.txt:

1
0   0   0.1
0   1   1
0   2   2
0   3   3
0   4   4
1   0   10
1   1   11
1   2   12
1   3   13
1   4   14
2   0   20
2   1   21
2   2   22
2   3   23
2   4   24
3   0   30
3   1   31
3   2   32
3   3   33
3   4   34
2
1   0   10
1   1   11
1   2   12
1   3   13
1   4   14
2   0   110
2   1   111
2   2   112
2   3   113
2   4   114
3   0   120
3   1   121
3   2   122
3   3   123
3   4   124
4   0   130
4   1   131
4   2   132
4   3   133
4   4   134
3
2   0   110
2   1   111
2   2   112
2   3   113
2   4   114
3   0   1110
3   1   1111
3   2   1112
3   3   1113
3   4   1114
4   0   1120
4   1   1121
4   2   1122
4   3   1123
4   4   1124
5   0   1130
5   1   1131
5   2   1132
5   3   1133
5   4   1134
4
3   0   1110
3   1   1111
3   2   1112
3   3   1113
3   4   1114
4   0   11110
4   1   11111
4   2   11112
4   3   11113
4   4   11114
5   0   11120
5   1   11121
5   2   11122
5   3   11123
5   4   11124
6   0   11130
6   1   11131
6   2   11132
6   3   11133
6   4   11134

Here is the script I use to generate the plots:

#!/usr/bin/env python3

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib.patches import FancyBboxPatch

def parse_file(file_name):

    output = {}

    with open(file_name, 'r') as data_file:
        for line in data_file:
            entries = line.strip().split()
            if len(entries) == 1:
                time_step = int(entries[0])
                output[time_step] = {}
            elif len(entries) == 3:
                x = float(entries[0])
                y = float(entries[1])
                value = float(entries[2])
                output[time_step][(x, y)] = value
            else:
                raise RuntimeError('Anomalous line {} in file {}'.format(line, data_file.name))

    return output

def main():

    fig, axes = plt.subplots()
    axes.set_xlim(-1,10)
    axes.set_ylim(-1,10)

    cmap = cm.plasma
    norm = LogNorm(vmin = 1e-2, vmax = 1.2e4)
    smap = cm.ScalarMappable(norm = norm, cmap = cmap)
    smap.set_array([])
    color_bar = fig.colorbar(mappable = smap, ax = axes, orientation = 'vertical', label = 'label')

    data = parse_file(file_name = 'data.txt')

    for time_step, information in data.items():
        cells = []
        for (x,y), value in information.items():

            cell = FancyBboxPatch(xy = (x - 0.5, y - 0.5),
                                  width = 1, height = 1,
                                  boxstyle = 'square,pad=0.',
                                  edgecolor = 'black',
                                  facecolor = smap.to_rgba(value))

            #print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))

            axes.add_patch(cell)
            cells.append(cell)

        fig.savefig('time-step_{}.png'.format(time_step))

        for cell in cells:
            cell.remove()

if __name__ == '__main__':
    main()

And here is one of the plots that is created from running that script:

This plot (and the other three that are created, but not shown here) look fine. So I am confident that I am using ScalarMappable correctly. Now I take the actual data I want to plot, again in a file called data.txt. The format is the same as before, except if a line has four entries, then the first entry is the time step (and I do not care about the other entries). Here is an example of data.txt:

     2    0.424066E-02    0.200000E+01    0.885500E+08
  0     1    0.850703E+00
  1     3    0.388551E-09
  2     4    0.141948E-06
  2     6    0.126299E-09
  3     9    0.166871E-08
  4    12    0.340738E-08
  5    13    0.246948E-09
  5    14    0.129005E-09
  6    16    0.140043E-08
  6    17    0.885307E-09
 26    76    0.591676E-08
 26    78    0.745985E-08
 27    77    0.263136E-08
 27    78    0.131857E-08
 27    79    0.151193E-05
 27    80    0.265941E-07
 27    81    0.170975E-05
 27    82    0.206355E-08
 27    83    0.334444E-07
 28    80    0.569439E-05
 28    81    0.864904E-07
 28    82    0.114196E-02
 28    83    0.130067E-06
 28    84    0.608045E-04
 28    85    0.351649E-07
 28    86    0.543117E-07
 28    88    0.202115E-08
 29    83    0.225374E-07
 29    84    0.125586E-07
 29    85    0.253383E-04
 29    86    0.943810E-06
 29    87    0.104539E-04
 29    88    0.210241E-06
 29    89    0.196533E-03
 29    90    0.707278E-06
 29    91    0.565096E-05
 29    92    0.840856E-08
 29    93    0.277478E-07
 30    86    0.707234E-09
 30    88    0.549048E-07
 30    89    0.281776E-08
 30    90    0.259219E-04
 30    91    0.298973E-06
 30    92    0.311047E-04
 30    93    0.144465E-05
 30    94    0.632642E-04
 30    95    0.787893E-08
 30    96    0.252900E-08
 31    91    0.425350E-08
 31    92    0.371105E-08
 31    93    0.621869E-05
 31    94    0.680069E-06
 31    95    0.315149E-04
 31    96    0.670790E-07
 31    97    0.568911E-06
 31    98    0.187946E-08
 31    99    0.135024E-07
 32    94    0.384693E-09
 32    96    0.174407E-06
 32    97    0.480216E-08
 32    98    0.244989E-05
 32    99    0.876257E-07
 32   100    0.189371E-04
 32   101    0.264917E-06
 32   102    0.297745E-05
 32   103    0.213684E-09
 33    99    0.110356E-08
 33   100    0.131345E-08
 33   101    0.448076E-06
 33   102    0.106369E-06
 33   103    0.128984E-04
 33   104    0.230382E-07
 33   105    0.266535E-07
 34   102    0.428166E-08
 34   103    0.668242E-08
 34   104    0.842244E-05
 34   105    0.843016E-07
 34   106    0.137510E-05
 34   107    0.879097E-08
 34   108    0.758233E-07
 35   105    0.280844E-06
 35   106    0.639110E-07
 35   107    0.497335E-05
 35   108    0.260105E-06
 35   109    0.188060E-05
 35   110    0.375853E-09
 35   111    0.935430E-09
 35   112    0.138533E-07
 35   113    0.101658E-06
 35   114    0.504823E-09
 35   115    0.989704E-09
 35   116    0.152468E-06
 35   117    0.220735E-07
 36   114    0.430884E-08
 36   116    0.115980E-07
 36   117    0.128436E-05
 36   118    0.814433E-05
 37   117    0.316595E-09
 37   118    0.141531E-06
 37   119    0.965141E-05
 38   119    0.459954E-08
 38   120    0.114088E-04
 38   121    0.198695E-09
 39   120    0.109457E-08
 39   121    0.105160E-04
 39   122    0.254984E-08
 40   122    0.717566E-05
 40   123    0.179081E-08
 40   124    0.352463E-09
 41   123    0.454357E-05
 41   124    0.629608E-07
 41   125    0.777480E-07
 42   124    0.453866E-05
 42   125    0.108592E-06
 42   126    0.320262E-06
 42   127    0.252596E-09
 42   128    0.114714E-09
 43   125    0.372578E-06
 43   126    0.344297E-07
 43   127    0.188018E-05
 43   128    0.631276E-08
 43   129    0.368003E-08
 44   126    0.170090E-07
 44   127    0.121695E-07
 44   128    0.147407E-05
 44   129    0.349674E-07
 44   130    0.767494E-06
 45   128    0.193141E-09
 45   129    0.361851E-06
 45   130    0.573704E-07
 45   131    0.457287E-06
 45   132    0.148004E-08
 45   133    0.164772E-07
 45   134    0.386942E-09
 45   135    0.539603E-08
 45   136    0.227778E-09
 45   137    0.640126E-08
 45   138    0.189604E-09
 45   139    0.754561E-09
 46   132    0.215880E-07
 46   134    0.102847E-08
 46   136    0.628736E-08
 46   137    0.427124E-09
 46   138    0.711664E-07
 46   139    0.749082E-08
 46   140    0.425043E-06
 46   141    0.776307E-08
 46   142    0.102985E-06
 46   143    0.693232E-09
 46   144    0.215846E-08
 47   141    0.660244E-08
 47   142    0.901189E-09
 47   143    0.299062E-07
 47   144    0.195833E-08
 47   145    0.178405E-07
 47   146    0.558550E-09
 47   147    0.235167E-08
 48   144    0.393065E-09
 48   146    0.493252E-08
 48   147    0.299176E-09
 48   148    0.130504E-07
 48   149    0.244654E-09
 48   150    0.143702E-08
 49   149    0.565286E-09
 49   151    0.122230E-08
     3    0.424066E-02    0.200000E+01    0.885500E+08
  0     1    0.850710E+00
  1     3    0.388551E-09
  2     4    0.141948E-06
  2     6    0.126299E-09
  3     9    0.166871E-08
  4    12    0.340738E-08
  5    13    0.246948E-09
  5    14    0.129005E-09
  6    16    0.140043E-08
  6    17    0.885307E-09
 26    76    0.593799E-08
 26    78    0.747463E-08
 27    77    0.283934E-08
 27    78    0.115725E-08
 27    79    0.153613E-05
 27    80    0.236099E-08
 27    81    0.171178E-05
 27    83    0.334426E-07
 28    80    0.575684E-05
 28    81    0.242170E-07
 28    82    0.114208E-02
 28    83    0.133947E-07
 28    84    0.608362E-04
 28    85    0.335522E-08
 28    86    0.543624E-07
 28    88    0.202170E-08
 29    83    0.258149E-07
 29    84    0.107337E-07
 29    85    0.261133E-04
 29    86    0.167223E-06
 29    87    0.108977E-04
 29    88    0.432469E-08
 29    89    0.196993E-03
 29    90    0.997563E-08
 29    91    0.565922E-05
 29    92    0.127589E-09
 29    93    0.277365E-07
 30    86    0.731139E-09
 30    88    0.613936E-07
 30    89    0.984612E-09
 30    90    0.261316E-04
 30    91    0.845314E-07
 30    92    0.324848E-04
 30    93    0.656773E-07
 30    94    0.632706E-04
 30    95    0.335583E-09
 30    96    0.252938E-08
 31    91    0.529954E-08
 31    92    0.394099E-08
 31    93    0.681605E-05
 31    94    0.104800E-06
 31    95    0.315602E-04
 31    96    0.231610E-08
 31    97    0.566868E-06
 31    99    0.135330E-07
 32    94    0.450380E-09
 32    96    0.178679E-06
 32    97    0.955313E-09
 32    98    0.252946E-05
 32    99    0.770340E-08
 32   100    0.191937E-04
 32   101    0.825856E-08
 32   102    0.297762E-05
 33    99    0.128999E-08
 33   100    0.146516E-08
 33   101    0.616111E-06
 33   102    0.539415E-07
 33   103    0.128046E-04
 33   104    0.865090E-09
 33   105    0.266759E-07
 34   102    0.899336E-08
 34   103    0.331924E-08
 34   104    0.850733E-05
 34   105    0.462457E-08
 34   106    0.137714E-05
 34   107    0.199044E-09
 34   108    0.758844E-07
 35   105    0.308602E-06
 35   106    0.470668E-07
 35   107    0.520013E-05
 35   108    0.458893E-07
 35   109    0.185756E-05
 35   111    0.159320E-07
 35   112    0.729552E-09
 35   113    0.101697E-06
 35   114    0.135746E-09
 35   115    0.128676E-06
 35   116    0.231448E-07
 35   117    0.220783E-07
 36   114    0.480979E-08
 36   116    0.921582E-06
 36   117    0.373798E-06
 36   118    0.814449E-05
 37   117    0.888355E-08
 37   118    0.132905E-06
 37   119    0.965147E-05
 38   118    0.360663E-09
 38   119    0.423745E-08
 38   120    0.114090E-04
 39   120    0.109122E-08
 39   121    0.105186E-04
 40   122    0.717737E-05
 40   124    0.352428E-09
 41   123    0.460618E-05
 41   124    0.358205E-09
 41   125    0.777514E-07
 42   124    0.464136E-05
 42   125    0.589035E-08
 42   126    0.320503E-06
 42   128    0.114709E-09
 43   125    0.408148E-06
 43   126    0.567978E-08
 43   127    0.187958E-05
 43   129    0.368007E-08
 44   126    0.258868E-07
 44   127    0.348446E-08
 44   128    0.150718E-05
 44   129    0.167101E-08
 44   130    0.767515E-06
 45   128    0.176686E-09
 45   129    0.403334E-06
 45   130    0.162718E-07
 45   131    0.458273E-06
 45   132    0.196826E-09
 45   133    0.167474E-07
 45   135    0.563904E-08
 45   137    0.655709E-08
 45   139    0.751998E-09
 46   132    0.216010E-07
 46   134    0.107901E-08
 46   136    0.673825E-08
 46   138    0.784839E-07
 46   139    0.220743E-09
 46   140    0.432287E-06
 46   141    0.427029E-09
 46   142    0.103696E-06
 46   144    0.211976E-08
 47   141    0.696394E-08
 47   142    0.585710E-09
 47   143    0.315456E-07
 47   144    0.425448E-09
 47   145    0.181981E-07
 47   146    0.136911E-09
 47   147    0.226765E-08
 48   144    0.442465E-09
 48   146    0.553370E-08
 48   147    0.138932E-09
 48   148    0.128376E-07
 48   150    0.144107E-08
 49   149    0.624360E-09
 49   151    0.123765E-08

The script that I use to create the plots is almost the same as before. The only differences are (1) how data.txt is parsed, (2) setting the limits of the x and y axes, and (3) the variable norm. Here is the script:

#!/usr/bin/env python3

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib.patches import FancyBboxPatch

def parse_file(file_name):

    output = {}

    with open(file_name, 'r') as data_file:
        for line in data_file:
            entries = line.strip().split()
            if len(entries) == 4:
                time_step = int(entries[0])
                output[time_step] = {}
            elif len(entries) == 3:
                x = float(entries[0])
                y = float(entries[1])
                value = float(entries[2])
                output[time_step][(x, y)] = value
            else:
                raise RuntimeError('Anomalous line {} in file {}'.format(line, data_file.name))

    return output

def main():

    fig, axes = plt.subplots()
    axes.set_xlim(0,150)
    axes.set_ylim(0,250)

    cmap = cm.plasma
    norm = LogNorm(vmin = pow(10, -10), vmax = pow(10, -2.2))
    smap = cm.ScalarMappable(norm = norm, cmap = cmap)
    smap.set_array([])
    color_bar = fig.colorbar(mappable = smap, ax = axes, orientation = 'vertical', label = 'label')

    data = parse_file(file_name = 'data.txt')

    for time_step, information in data.items():
        cells = []
        for (x,y), value in information.items():

            cell = FancyBboxPatch(xy = (x - 0.5, y - 0.5),
                                  width = 1, height = 1,
                                  boxstyle = 'square,pad=0.',
                                  edgecolor = 'black',
                                  facecolor = smap.to_rgba(value))

            #print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))

            axes.add_patch(cell)
            cells.append(cell)

        fig.savefig('time-step_{}.png'.format(time_step))

        for cell in cells:
            cell.remove()

if __name__ == '__main__':
    main()

Now all of the patches are black. Here is one of the plots that is created:

I do not see anything obviously wrong using the print statement (which is commented out in the script):

print(time_step, '\t', x, '\t', y, '\t', value, '\t', smap.to_rgba(value))

Why are all the FancyBboxPatches black instead of the color I have chosen with the ScalarMappable (and how can I make them be the color I have chosen with the ScalarMappable)?


来源: stackexchange

问:
Detached entity passed to persist when using Composite Key with Objects
I'm having problems in saving an entity that has child objects attached. The following code is throwing "org.hibernate.PersistentObjectException: detached entity passed to persist: nl.test.api.domain.attribute.Attribute" when trying to save the Ad entity, knowing that it has Cascade.ALL in its child object field. Important to say that I'm using IdClass for composite primary key and using objects Ad and Attribute as parts of the composite primary key of AdAttribute.

I understand what the exception means but either way I'm not able to fix it, specially because the creation method is Transactional. Any thoughts?

The root/Ad object:

```<code>@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "ad")
public class Ad implements SearchableAdDefinition {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
    private User user;

    @OneToMany(mappedBy = "ad", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<AdAttribute> adAttributes;

(...)
}
</code>```

The "Child object" (which contains a composite key in which the @ManyToOne objects are part of the key)

```<code>@Entity
@Table(name = "attrib_ad")
@IdClass(CompositeAdAttributePk.class)
public class AdAttribute {

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ad_id")
    private Ad ad;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "attrib_id")
    private Attribute attribute;

    @Column(name = "value", length = 75)
    private String value;

    public Ad getAd() {
        return ad;
    }

    public void setAd(Ad ad) {
        this.ad = ad;
    }

    public Attribute getAttribute() {
        return attribute;
    }

    public void setAttribute(Attribute attribute) {
        this.attribute = attribute;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

 class CompositeAdAttributePk implements Serializable {
    private Ad ad;
    private Attribute attribute;

    public CompositeAdAttributePk() {

    }

    public CompositeAdAttributePk(Ad ad, Attribute attribute) {
        this.ad = ad;
        this.attribute = attribute;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CompositeAdAttributePk compositeAdAttributePk = (CompositeAdAttributePk) o;
        return ad.getId().equals(compositeAdAttributePk.ad.getId()) && attribute.getId().equals(compositeAdAttributePk.attribute.getId());

    }

    @Override
    public int hashCode() {
        return Objects.hash(ad.getId(), attribute.getId());
    }
</code>```

And finally, the method I create the parent object (Ad) and attach the child objects (Ad Attributes):

```<code>@Transactional
public Ad create(String title, User user, Category category, AdStatus status, String description, String url, Double price, AdPriceType priceType, Integer photoCount, Double minimumBid, Integer options, Importer importer, Set<AdAttribute> adAttributes) {

    Ad ad = new Ad();

    ad.setTitle(title);
    ad.setUser(user);
    ad.setCategory(category);
    ad.setStatus(status);
    ad.setDescription(description);
    ad.setUrl(url);
    ad.setPrice(price);
    ad.setPriceType(priceType);
    ad.setPhotoCount(photoCount);
    ad.setMinimumBid(minimumBid);
    ad.setOptions(options);
    ad.setImporter(importer);
    ad.setAdAttributes(adAttributes);

    for (AdAttribute adAttribute : ad.getAdAttributes()) {
        adAttribute.setAd(ad);
    }

    ad = adRepository.save(ad);

    solrAdDocumentRepository.save(AdDocument.adDocumentBuilder(ad));

    return ad;
}
</code>```

答:
The PersistentObjectException ...detached entity passed to persist... is thrown because Attribute is not a transient instance, and AFAIK, your second level cache has nothing to do here!

Check if you're persisting Attribute entity with an assigned id, either directly or via other Entity using CascadeType.PERSIST/ALL association,

To solve it, you can use EntityManager.merge, but It's better to review your persistence and cascade strategy to better control your data flow, and do never expose a method that modify a primary key (except in a contructor if you're not using the auto-generated strategy).

You may check other possible solutions in this SO thread as well for your exception!

Note:

In CompositeAdAttributePk.equals use instanceOf instead of getClass() as hibernate may use a proxy + you should check for null id as well.

...futhermore avoid using surrogate id in equals/hasCode methods if you're using auto-generated identity, as it's not constant throughout all entity states, use business key instead, I suggest you to read about implementing Equals and HashCode in Hibernate, as It states:

...Instead of using the database identifier for the equality comparison,
you should use a set of properties for equals() that identify your
individual objects. For example, if you have an "Item" class and it
has a "name" String and "created" Date, I can use both to implement a
good equals() method. No need to use the persistent identifier, the so
called "business key" is much better. It's a natural key, but this
time there is nothing wrong in using it!

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
I'm having problems in saving an entity that has child objects attached. The following code is throwing "org.hibernate.PersistentObjectException: detached entity passed to persist: nl.test.api.domain.attribute.Attribute" when trying to save the Ad entity, knowing that it has Cascade.ALL in its child object field. Important to say that I'm using IdClass for composite primary key and using objects Ad and Attribute as parts of the composite primary key of AdAttribute.

I understand what the exception means but either way I'm not able to fix it, specially because the creation method is Transactional. Any thoughts?

The root/Ad object:

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "ad")
public class Ad implements SearchableAdDefinition {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
    private User user;

    @OneToMany(mappedBy = "ad", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<AdAttribute> adAttributes;

(...)
}

The "Child object" (which contains a composite key in which the @ManyToOne objects are part of the key)

@Entity
@Table(name = "attrib_ad")
@IdClass(CompositeAdAttributePk.class)
public class AdAttribute {

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ad_id")
    private Ad ad;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "attrib_id")
    private Attribute attribute;

    @Column(name = "value", length = 75)
    private String value;

    public Ad getAd() {
        return ad;
    }

    public void setAd(Ad ad) {
        this.ad = ad;
    }

    public Attribute getAttribute() {
        return attribute;
    }

    public void setAttribute(Attribute attribute) {
        this.attribute = attribute;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

 class CompositeAdAttributePk implements Serializable {
    private Ad ad;
    private Attribute attribute;

    public CompositeAdAttributePk() {

    }

    public CompositeAdAttributePk(Ad ad, Attribute attribute) {
        this.ad = ad;
        this.attribute = attribute;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CompositeAdAttributePk compositeAdAttributePk = (CompositeAdAttributePk) o;
        return ad.getId().equals(compositeAdAttributePk.ad.getId()) && attribute.getId().equals(compositeAdAttributePk.attribute.getId());

    }

    @Override
    public int hashCode() {
        return Objects.hash(ad.getId(), attribute.getId());
    }

And finally, the method I create the parent object (Ad) and attach the child objects (Ad Attributes):

@Transactional
public Ad create(String title, User user, Category category, AdStatus status, String description, String url, Double price, AdPriceType priceType, Integer photoCount, Double minimumBid, Integer options, Importer importer, Set<AdAttribute> adAttributes) {

    Ad ad = new Ad();

    ad.setTitle(title);
    ad.setUser(user);
    ad.setCategory(category);
    ad.setStatus(status);
    ad.setDescription(description);
    ad.setUrl(url);
    ad.setPrice(price);
    ad.setPriceType(priceType);
    ad.setPhotoCount(photoCount);
    ad.setMinimumBid(minimumBid);
    ad.setOptions(options);
    ad.setImporter(importer);
    ad.setAdAttributes(adAttributes);

    for (AdAttribute adAttribute : ad.getAdAttributes()) {
        adAttribute.setAd(ad);
    }

    ad = adRepository.save(ad);

    solrAdDocumentRepository.save(AdDocument.adDocumentBuilder(ad));

    return ad;
}

ContentLicense: CC BY-SA 4.0


问:
Why isnt my javascript function being run?
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

```<code> <div class = mainInfo>
    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>
    <div id="feedback">
    </div>
 </div>
<script>
function validate()
{
    document.getElementById("feedback").innerHTML = "functionbeingcalled";
    var p1 = document.getElementById("p1").value,
                p2 = document.getElementById("p2").value);
    if( ! p1===p2 )
    {

        document.getElementById("feedback").innerHTML = "passwords dont match";
    }
    if(p1==="")
    {
         document.getElementById("feedback").innerHTML = "Must have a password";
    }
}
window.setInterval(validate(),1000);
</script>

<?php include "footer.php"; ?>
</code>```

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

```<code> document.getElementById("feedback").innerHTML = "functionbeingcalled";
</code>```

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.

答:
Pass the function instead of calling it.

```<code>//             no parentheses!
window.setInterval(validate, 1000);
</code>```

And this is wrong.

```<code>if( ! p1===p2 )
</code>```

it should be this

```<code>if( p1!==p2 )
</code>```

because of the higher precedence of the prefix !

Body:
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>

<?php include "footer.php"; ?>

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

 document.getElementById("feedback").innerHTML = "functionbeingcalled";

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.

Body:
Pass the function instead of calling it.

//             no parentheses!
window.setInterval(validate, 1000);

And this is wrong.

if( ! p1===p2 )

it should be this

if( p1!==p2 )

because of the higher precedence of the prefix !


问:
Convert select statement to Group by
i create a view (see below)
the problem is that i get dublicat rows and with UNION they are deselected,
i dont want to use UNION ALL

so my question is, how can i rewrite the two "select .. " to a Group by expression,Group by: YEAR, Month
and get the same result as UNION ALL

```<code> CREAT VIEW v_test_rerytering (.......) AS
 select
   F.ALDER
   age,
   cast(P.AR as VARCHAR2(4)) year,
   ccast((P.MANAD)as VARCHAR2(2)) month,
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
   cast('Extern' as VARCHAR2(50)) R_KOD,
   F.NR_REK
   REK
 from test.Table_anstallda F join test.PERIOD P on P.PERIOD =
 F.PERIOD

 union

 select
   F.ALDER
   age,
   cast(P.AR as VARCHAR2(4)) year,
   ccast((P.MANAD)as VARCHAR2(2)) month,
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
  cast('Extern' as VARCHAR2(50)) R_KOD,
  F.NR_dism
  REK
from test.Table_anstallda F join test.PERIOD P on P.PERIOD_SN =
 F.PERIOD   ;
</code>```

答:
You should join PERIOD on PERIOD or PERIOD_SN and use COALESCE or a CASE statement to set the field for the REK column.

This is the coalesce version, which may not work depending on your data:

```<code>SELECT F.ALDER age
    ,cast(P.AR AS VARCHAR2(4)) year
    ,ccast((P.MANAD) AS VARCHAR2(2)) month
    ,cast(K.KON_KOD AS VARCHAR2(50)) SEX
    ,cast('Extern' AS VARCHAR2(50)) R_KOD
    ,REK = coalesce(F.NR_REK, F.NR_dism)
FROM test.Table_anstallda F
JOIN test.PERIOD P
    ON P.PERIOD = F.PERIOD
    OR p.Period = f.PERIOD_SN
</code>```

Title: Convert select statement to Group by

Body:
i create a view (see below)
the problem is that i get dublicat rows and with UNION they are deselected,
i dont want to use UNION ALL

so my question is, how can i rewrite the two "select .. " to a Group by expression,Group by: YEAR, Month
and get the same result as UNION ALL

 CREAT VIEW v_test_rerytering (.......) AS
 select
   F.ALDER
   age,
   cast(P.AR as VARCHAR2(4)) year,
   ccast((P.MANAD)as VARCHAR2(2)) month,
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
   cast('Extern' as VARCHAR2(50)) R_KOD,
   F.NR_REK
   REK
 from test.Table_anstallda F join test.PERIOD P on P.PERIOD =
 F.PERIOD

 union

 select
   F.ALDER
   age,
   cast(P.AR as VARCHAR2(4)) year,
   ccast((P.MANAD)as VARCHAR2(2)) month,
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
  cast('Extern' as VARCHAR2(50)) R_KOD,
  F.NR_dism
  REK
from test.Table_anstallda F join test.PERIOD P on P.PERIOD_SN =
 F.PERIOD   ;

Body:
You should join PERIOD on PERIOD or PERIOD_SN and use COALESCE or a CASE statement to set the field for the REK column.

This is the coalesce version, which may not work depending on your data:

SELECT F.ALDER age
    ,cast(P.AR AS VARCHAR2(4)) year
    ,ccast((P.MANAD) AS VARCHAR2(2)) month
    ,cast(K.KON_KOD AS VARCHAR2(50)) SEX
    ,cast('Extern' AS VARCHAR2(50)) R_KOD
    ,REK = coalesce(F.NR_REK, F.NR_dism)
FROM test.Table_anstallda F
JOIN test.PERIOD P
    ON P.PERIOD = F.PERIOD
    OR p.Period = f.PERIOD_SN


问:
vba code for copying a string if it contains a certain value
Hi I'm looking on how to edit my code so that instead of turning the font colour of the start of the string red and bold, it pastes these strings into another worksheet, however ever time I try to edit it I always end up with a run time error. Any help would be appreciated, here is my current code:</p>

```<code>Sub colorText()

    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim searchText As String
    Dim endPos As Integer
    Dim testPos As Integer

     ' specify text to search.
     searchText = "(9)"

    ' loop trough all cells in selection/range
     For Each cl In Range("A:A")
      totalLen = Len(searchText)
      startPos = InStr(cl, searchText)
      testPos = 0

      Do While startPos > testPos
         With cl.Characters(startPos, totalLen).Font
          .FontStyle = "Bold"
          .ColorIndex = 3
         End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
     startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub
</code>```

答:
If I have correctly anderstood your problem, you have just to construct the string that you want to copy, and assign it to the cell you wante :</p>

```<code>Dim temp as String
If Not startPos = 0 Then
    temp = Mid(cl, startPos)
    Sheets("sheet2").Cells(cl.Row, cl.Column) = temp
End If
</code>```

Body:
Hi I'm looking on how to edit my code so that instead of turning the font colour of the start of the string red and bold, it pastes these strings into another worksheet, however ever time I try to edit it I always end up with a run time error. Any help would be appreciated, here is my current code:

Sub colorText()

    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim searchText As String
    Dim endPos As Integer
    Dim testPos As Integer

     ' specify text to search.
     searchText = "(9)"

    ' loop trough all cells in selection/range
     For Each cl In Range("A:A")
      totalLen = Len(searchText)
      startPos = InStr(cl, searchText)
      testPos = 0

      Do While startPos > testPos
         With cl.Characters(startPos, totalLen).Font
          .FontStyle = "Bold"
          .ColorIndex = 3
         End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
     startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub

Body:
If I have correctly anderstood your problem, you have just to construct the string that you want to copy, and assign it to the cell you wante :

Dim temp as String
If Not startPos = 0 Then
    temp = Mid(cl, startPos)
    Sheets("sheet2").Cells(cl.Row, cl.Column) = temp
End If


问:
When programming for iphone how do you use data for multiple views?
I am a objective-c newbie and I was wondering how do you use data obtained from one view in another? For example I ask a user for a text input, and this text input then changes a label when a button is hit. I want this information for another label in a different view. how would I get it?
Thanks</p>

答:
If you are doing something simple like passing a value from one view controller to another, you can just store a reference to the first view controller in your second view controller, and this would then give you access to the first view controller's ivars.  Here is a blog post I did on this very subject:

http://www.dosomethinghere.com/2009/10/04/passing-values-and-messages-between-views-on-iphone/

ContentLicense: CC BY-SA 2.5


问:
How to use if statement PyTorch using torch.FloatTensor
I am trying to use the if statement in my PyTorch code using torch.FloatTensor as data type, to speed it up into the GPU.

This is my code:

```<code>import torch
import time
def fitness(x):
     return torch.pow(x, 2)

def velocity(v, gxbest, pxbest, pybest, x, pop):
     return torch.rand(pop).type(dtype)*v + \
            torch.rand(pop).type(dtype)*(pxbest - x) + \
            torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x)

dtype = torch.cuda.FloatTensor
def main():

    pop, xmax, xmin, niter = 300000, 50, -50, 100
    v                      = torch.rand(pop).type(dtype)
    x                      = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y                      = fitness(x)
    [miny, indexminy]      = y.min(0)
    gxbest                 = x[indexminy]
    pxbest                 = x
    pybest                 = y

    for K in range(niter):

        vnext = velocity(v, gxbest, pxbest, pybest, x, pop)

        xnext = x + vnext
        ynext = fitness(x)
        [minynext, indexminynext]  = ynext.min(0)

        if (minynext < miny):
            miny   = minynext
            gxbest = xnext[indexminynext]

        indexpbest         = (ynext < pybest)
        pxbest[indexpbest] = xnext[indexpbest]
        pybest[indexpbest] = ynext[indexpbest]
        x                  = xnext
        v                  = vnext
main()
</code>```

Unfortanally it is not working. It is giving me a error message and I can not figure it out what is the problem.

RuntimeError: bool value of non-empty torch.cuda.ByteTensor objects is ambiguous

How can I use the if in PyTorch? I tried to convert the cuda.Tensor into a numpy array but it did not work also.

```<code>  minynext = minynext.cpu().numpy()
  miny = miny.cpu().numpy()
</code>```

PS: Am I doing the code the efficient/faster way possible ? Or should I change something to achieve faster results?

答:
When you compare pyTorch tensors, the output is usually a ByteTensor. This data type is not suitable for if statements.

Change the condition inside the if:

```<code>if (minynext[0] < miny[0])
</code>```

Body:
I am trying to use the if statement in my PyTorch code using torch.FloatTensor as data type, to speed it up into the GPU.

This is my code:

import torch
import time
def fitness(x):
     return torch.pow(x, 2)

def velocity(v, gxbest, pxbest, pybest, x, pop):
     return torch.rand(pop).type(dtype)*v + \
            torch.rand(pop).type(dtype)*(pxbest - x) + \
            torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x)

dtype = torch.cuda.FloatTensor
def main():

    pop, xmax, xmin, niter = 300000, 50, -50, 100
    v                      = torch.rand(pop).type(dtype)
    x                      = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y                      = fitness(x)
    [miny, indexminy]      = y.min(0)
    gxbest                 = x[indexminy]
    pxbest                 = x
    pybest                 = y

    for K in range(niter):

        vnext = velocity(v, gxbest, pxbest, pybest, x, pop)

        xnext = x + vnext
        ynext = fitness(x)
        [minynext, indexminynext]  = ynext.min(0)

        if (minynext < miny):
            miny   = minynext
            gxbest = xnext[indexminynext]

        indexpbest         = (ynext < pybest)
        pxbest[indexpbest] = xnext[indexpbest]
        pybest[indexpbest] = ynext[indexpbest]
        x                  = xnext
        v                  = vnext
main()

Unfortanally it is not working. It is giving me a error message and I can not figure it out what is the problem.

RuntimeError: bool value of non-empty torch.cuda.ByteTensor objects is ambiguous

How can I use the if in PyTorch? I tried to convert the cuda.Tensor into a numpy array but it did not work also.

  minynext = minynext.cpu().numpy()
  miny = miny.cpu().numpy()

PS: Am I doing the code the efficient/faster way possible ? Or should I change something to achieve faster results?

Body:
When you compare pyTorch tensors, the output is usually a ByteTensor. This data type is not suitable for if statements.

Change the condition inside the if:

if (minynext[0] < miny[0])


问:
EntityFrameworkCore Mapping Relationships
I have the following two entities:

```<code>public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}
</code>```

This corresponds to two DB tables:

```<code>Company:
  Id uniqueidentifier
  Name varchar

Address:
  Id uniqueidentifier
  Town varchar
  Country varchar
  RelationId uniqueidentifier
</code>```

RelationId is the foreign key which stores the link back to CompanyId.

I can not change either the classes or the tables.

I am trying to figure out how to represent this construct in code first EFCore.

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<Address>().ToTable("Addresses");

        modelBuilder.Entity<Company>().HasKey(c => c.Id);
        modelBuilder.Entity<Address>().HasKey(c => c.Id);

        ???????????????????????
    }
</code>```

What am I missing in the code above to prevent the creation of a CompanyId foreign key and use the 'RelationId' instead.

答:
Here is the solution for your requirement :

```<code>public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }

    [ForeignKey("Company ")]
    public Guid RelationId { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public Company Company {get; set;}
}
</code>```

Using Fluent API:

```<code>public class YourDbContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Address> Addresses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>()
            .HasOne(p => p.Company)
            .WithMany(b => b.Addresses);
    }
}
</code>```

Body:
I have the following two entities:

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}

This corresponds to two DB tables:

Company:
  Id uniqueidentifier
  Name varchar

Address:
  Id uniqueidentifier
  Town varchar
  Country varchar
  RelationId uniqueidentifier

RelationId is the foreign key which stores the link back to CompanyId.

I can not change either the classes or the tables.

I am trying to figure out how to represent this construct in code first EFCore.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<Address>().ToTable("Addresses");

        modelBuilder.Entity<Company>().HasKey(c => c.Id);
        modelBuilder.Entity<Address>().HasKey(c => c.Id);

        ???????????????????????
    }

What am I missing in the code above to prevent the creation of a CompanyId foreign key and use the 'RelationId' instead.

Body:
Here is the solution for your requirement :

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }

    [ForeignKey("Company ")]
    public Guid RelationId { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }

    //remove virtual keyword as there is no lazy loading in  entityframework core
    public Company Company {get; set;}
}

Using Fluent API:

public class YourDbContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Address> Addresses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>()
            .HasOne(p => p.Company)
            .WithMany(b => b.Addresses);
    }
}


问:
How to find the log files which are 2 days older, ZIP them and move them to Amazon S3
I have tried this:</p>

```<code>#!/bin/bash
for f in find /var/lib/tomcat7/logs -name 'testing.*.log' -and -ctime +2 -exec bzip2 -zv {} \;
do
aws s3 mv $f s3://ri-uat-bucket/testing/
done
</code>```

答:
Use the below code:</p>

```<code>for f in `find /var/lib/tomcat7/logs -name 'testing.*.log' -ctime +2`
do
bzip2 -zv $f
aws s3 mv $f.bz2 s3://ri-uat-bucket/testing/
done
</code>```

Body:
I have tried this:

#!/bin/bash
for f in find /var/lib/tomcat7/logs -name 'testing.*.log' -and -ctime +2 -exec bzip2 -zv {} \;
do
aws s3 mv $f s3://ri-uat-bucket/testing/
done

Body:
Use the below code:

for f in `find /var/lib/tomcat7/logs -name 'testing.*.log' -ctime +2`
do
bzip2 -zv $f
aws s3 mv $f.bz2 s3://ri-uat-bucket/testing/
done


问:
How can I copy a string variable to another character by character without defining size of target variable?
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

```<code>string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But as the size of the string in C++ is calculated dynamically as

```<code>string k = "Hello";
string l = "Hello World";
string m = k;
m = l;
</code>```

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

```<code>string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?

答:
Size of the string is dynamic, but it not changed automaticaly as you expect. operator[] only return i-th element, if current size of a string is less than i, it fill fail. It's up to you to make sure size of a string is big enough.

If you couldn't resize string in advance you can query size, increase it by one, ask string to resize, and set last char.

This is how push_back method works

Body:
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But as the size of the string in C++ is calculated dynamically as

string k = "Hello";
string l = "Hello World";
string m = k;
m = l;

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?


问:
How to build a dynamic URL in Spring MVC?
I am trying to send one URL which I will generate on basis of some dynamic value. But I don't want to hard code it nor want to use response or request object.

Example:

http://localhost:8585/app/image/{id}/{publicUrl}/{filename}

So I want to get the first part (i.e. http://localhost:8585/app/image)
from Spring Framework only. I will provide rest of the things like id, publicUrl, filename, so that it can generate a complete absolute URL.

How to do it in Spring MVC?

答:
Just an addition to Neil McGuigan's answer but without hardcoding schema, domain, port &, etc...

One could do this:

```<code>import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
...
ServletUriComponentsBuilder.fromCurrentRequest
        .queryParam("page", 1)
        .toUriString();
</code>```

imagine original request was to

```<code>https://myapp.mydomain.com/api/resources
</code>```

this code will produce the following URL

```<code>https://myapp.mydomain.com/api/resources?page=1
</code>```

Hope this helps.

Body:
Just an addition to Neil McGuigan's answer but without hardcoding schema, domain, port &, etc...

One could do this:

import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
...
ServletUriComponentsBuilder.fromCurrentRequest
        .queryParam("page", 1)
        .toUriString();

imagine original request was to

https://myapp.mydomain.com/api/resources

this code will produce the following URL

https://myapp.mydomain.com/api/resources?page=1

Hope this helps.


问:
How can I return control to the client app and ask for input again from my API?
Writing a pure API seems to be bring up some challenges. For example, I am used to writing winforms/asp.net apps where if the input I have is invalid, I can programatically bring up a dialog box/webpage.

However, an API has no knowledge of the GUI app it may be executed from. If I have a method called TakeString (String s), and the string (s) cannot be more than 5 letters, how would I return control to the client if it was so? An exception seems like overkill? A simple return won't work if I am returning something in the method.

Thanks

答:
An Exception is the best way to handle this.

By definition, if the user is supplying invalid data, this is an exception.  The client app needs to be responsible for handling the exception and prompting the user to re-enter as necessary.

Your API (as you already pointed out) should be ignorant of the client app, including what type of app it is, so all your API has to do is say "Hey, that's invalid!" and let the developer of the client app figure out how to handle it.

For a simple example if you try the following line of C# code:

```<code>int myInt = Convert.ToInt32("SSDS");
</code>```

the .NET Framework doesn't try to re-prompt the user.  It just throws an exception.

Body:
An Exception is the best way to handle this.

By definition, if the user is supplying invalid data, this is an exception.  The client app needs to be responsible for handling the exception and prompting the user to re-enter as necessary.

Your API (as you already pointed out) should be ignorant of the client app, including what type of app it is, so all your API has to do is say "Hey, that's invalid!" and let the developer of the client app figure out how to handle it.

For a simple example if you try the following line of C# code:

int myInt = Convert.ToInt32("SSDS");

the .NET Framework doesn't try to re-prompt the user.  It just throws an exception.


问:
How to enable allow_url_fopen for phpMyAdmin?
After updating phpMyAdmin to v4.7.5 on my Apache/2.4.10 (Debian) I'm getting:

The curl extension was not found and allow_url_fopen is disabled. Due
  to this some features such as error reporting or version check are
  disabled.

phpinfo() says Local Value: Off, Master Value: On

In my /etc/php5/cli/php.ini I've: /etc/php5/cli/php.ini

I tried allow_url_fopen Local Value=Off Master Value=Off but it didn't help.

php --ini shows the following files:

```<code>Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/05-opcache.ini,
/etc/php5/cli/conf.d/10-pdo.ini,
/etc/php5/cli/conf.d/20-gd.ini,
/etc/php5/cli/conf.d/20-json.ini,
/etc/php5/cli/conf.d/20-mcrypt.ini,
/etc/php5/cli/conf.d/20-mysql.ini,
/etc/php5/cli/conf.d/20-mysqli.ini,
/etc/php5/cli/conf.d/20-pdo_mysql.ini,
/etc/php5/cli/conf.d/20-readline.ini
</code>```

(Of course I rebooted after making the changes.)

What can I do?

答:
I solved the problem by installing cURL with this command:

apt-get update && apt-get install php5-curl

then

reboot

and ready!

Body:
After updating phpMyAdmin to v4.7.5 on my Apache/2.4.10 (Debian) I'm getting:

The curl extension was not found and allow_url_fopen is disabled. Due
  to this some features such as error reporting or version check are
  disabled.

phpinfo() says Local Value: Off, Master Value: On

In my /etc/php5/cli/php.ini I've: /etc/php5/cli/php.ini

I tried allow_url_fopen Local Value=Off Master Value=Off but it didn't help.

php --ini shows the following files:

Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/05-opcache.ini,
/etc/php5/cli/conf.d/10-pdo.ini,
/etc/php5/cli/conf.d/20-gd.ini,
/etc/php5/cli/conf.d/20-json.ini,
/etc/php5/cli/conf.d/20-mcrypt.ini,
/etc/php5/cli/conf.d/20-mysql.ini,
/etc/php5/cli/conf.d/20-mysqli.ini,
/etc/php5/cli/conf.d/20-pdo_mysql.ini,
/etc/php5/cli/conf.d/20-readline.ini

(Of course I rebooted after making the changes.)

What can I do?


问:
How to pass dynamic page automation commands to puppeteer from external file?
I'm trying to pass dynamic page automation commands to puppeteer from an external file.  I'm new to puppeteer and node so I apologize in advance.

```<code>// app.js
// ========

app.get('/test', (req, res) =>
(async () => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://testurl.com');

var events = require('./events.json');

for(var i=0;i<events.length;i++){
  var tmp = events[i];
  await page.evaluate((tmp) => {  return Promise.resolve(tmp.event); }, tmp);
}

await browser.close();
})());
</code>```

My events json file looks like:

```<code>// events.json
// ========

  [
    {
        "event":"page.waitFor(4000)"
    },
    {
        "event":"page.click('#aLogin')"
    },
    {
        "event":"page.waitFor(1000)"
    }
]
</code>```

I've tried several variations of the above as well as importing a module that passes the page object to one of the module function, but nothing has worked.  Can anyone tell me if this is possible and, if so, how to better achieve this?

答:
The solution is actually very simple and straightforward. You just have to understand how this works.

First of all, you cannot pass page elements like that to evaluate. Instead you can do the following,

On a seperate file,

```<code>module.exports = async function getCommands(page) {
    return Promise.all([
        await page.waitFor(4000),
        await page.click("#aLogin"),
        await page.waitFor(1000)
    ]);
};
</code>```

Now on your main file,

```<code>await require('./events.js').getCommands(page);
</code>```

There, it's done! It'll execute all commands for you one by one just as you wanted.

Here is a complete code with some adjustments,

```<code>const puppeteer = require("puppeteer");

async function getCommands(page) {
    return Promise.all([
        await page.title(),
        await page.waitFor(1000)
    ]);
};

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("https://example.com");

    let data = await getCommands(page);
    console.log(data);

    await page.close();
    await browser.close();
})();
</code>```

Body:
I'm trying to pass dynamic page automation commands to puppeteer from an external file.  I'm new to puppeteer and node so I apologize in advance.

// app.js
// ========

app.get('/test', (req, res) =>
(async () => {

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://testurl.com');

var events = require('./events.json');

for(var i=0;i<events.length;i++){
  var tmp = events[i];
  await page.evaluate((tmp) => {  return Promise.resolve(tmp.event); }, tmp);
}

await browser.close();
})());

My events json file looks like:

// events.json
// ========

  [
    {
        "event":"page.waitFor(4000)"
    },
    {
        "event":"page.click('#aLogin')"
    },
    {
        "event":"page.waitFor(1000)"
    }
]

I've tried several variations of the above as well as importing a module that passes the page object to one of the module function, but nothing has worked.  Can anyone tell me if this is possible and, if so, how to better achieve this?

Body:
The solution is actually very simple and straightforward. You just have to understand how this works.

First of all, you cannot pass page elements like that to evaluate. Instead you can do the following,

On a seperate file,

module.exports = async function getCommands(page) {
    return Promise.all([
        await page.waitFor(4000),
        await page.click("#aLogin"),
        await page.waitFor(1000)
    ]);
};

Now on your main file,

await require('./events.js').getCommands(page);

There, it's done! It'll execute all commands for you one by one just as you wanted.

Here is a complete code with some adjustments,

const puppeteer = require("puppeteer");

async function getCommands(page) {
    return Promise.all([
        await page.title(),
        await page.waitFor(1000)
    ]);
};

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("https://example.com");

    let data = await getCommands(page);
    console.log(data);

    await page.close();
    await browser.close();
})();


问:
Show measure based on other column
I am trying to write oracle sql for below scenario. Can anyone provide pointers?

My data is like

Now whenever a customer has 401k account I have to default the balance to zero else show the total balance.

Thanks,
Pratap

答:
You can do this with a case expression.

```<code>select customer,
case when count(case when account='401K' then 1 end) > 0 then 0 else sum(balance) end
from tbl
group by customer
</code>```

Title: Show measure based on other column

Body:
You can do this with a case expression.

select customer,
case when count(case when account='401K' then 1 end) > 0 then 0 else sum(balance) end
from tbl
group by customer


问:
Melt columns from dataframe with unique id
I have a dataframe which has unique ids and other columns like this:

```<code>df = data.frame(id = c('id1', 'id2', 'id3'),
                col_1 = c(0,1,0),
                col_2 = c(1,0,0),
                col_3 = c(1,1,NA),
                col_4 = c(1,NA,NA))
</code>```

How is it possible to melt the dataframe aiming to have 2 columns one with the id which will be repeated based on the number of columns and the second column will contain the value from the other columns.

Example of expected output:

```<code>df = data.frame(id = c('id1', 'id1', 'id1', 'id1', 'id2', 'id2', 'id2', 'id2', 'id3', 'id3', 'id3', 'id3'),
                col_1 = c(0,1,1,1,1,0,1,NA,0,0,NA,NA))
</code>```

Body:
I have a dataframe which has unique ids and other columns like this:

df = data.frame(id = c('id1', 'id2', 'id3'),
                col_1 = c(0,1,0),
                col_2 = c(1,0,0),
                col_3 = c(1,1,NA),
                col_4 = c(1,NA,NA))

How is it possible to melt the dataframe aiming to have 2 columns one with the id which will be repeated based on the number of columns and the second column will contain the value from the other columns.

Example of expected output:

df = data.frame(id = c('id1', 'id1', 'id1', 'id1', 'id2', 'id2', 'id2', 'id2', 'id3', 'id3', 'id3', 'id3'),
                col_1 = c(0,1,1,1,1,0,1,NA,0,0,NA,NA))

Body:
Try:

library(reshape2)
df = data.frame(id=c('id1', 'id2', 'id3'),col_1 = c(0,1,0),col_2 = c(1,0,0),col_3 = c(1,1,NA),col_4 = c(1,NA,NA))
x <- melt(df, id.vars = "id")
x[order(x$id),c(1,3)]


问:
How to exclude the first element of an enumerated Type used as an array index in delphi?
I want to exclude the first value of this enumerated type

```<code>type
  TEnum = (val0, val1, val2, val3, val4);
</code>```

in order to make this array

```<code>TBValues: array [low(TEnum)..High(TEnum)] of boolean;
</code>```

contains only the last n-1 values (in this case n=5).

I tried this:

```<code>TBValues: array [low(TEnum)+1..High(TEnum)] of boolean;
</code>```

but I guess arithmetic operations are not allowed in this case because I'm getting this compiler error

E2010 Incompatible types: 'Int64' and 'TEnum'

How to do this?

答:
What about the obvious:

```<code>TBValues: array [val1..val4] of boolean;
</code>```

If you want to avoid the actual enum names, you can write it this way:

```<code>TBValues: array [Succ(low(TEnum))..High(TEnum)] of boolean;
</code>```

For more information:

Succ

Pred

Body:
I want to exclude the first value of this enumerated type

type
  TEnum = (val0, val1, val2, val3, val4);

in order to make this array

TBValues: array [low(TEnum)..High(TEnum)] of boolean;

contains only the last n-1 values (in this case n=5).

I tried this:

TBValues: array [low(TEnum)+1..High(TEnum)] of boolean;

but I guess arithmetic operations are not allowed in this case because I'm getting this compiler error

E2010 Incompatible types: 'Int64' and 'TEnum'

How to do this?

Body:
What about the obvious:

TBValues: array [val1..val4] of boolean;

If you want to avoid the actual enum names, you can write it this way:

TBValues: array [Succ(low(TEnum))..High(TEnum)] of boolean;

For more information:

Succ

Pred


问:
Cannot remove gerrit trigger server from jenkins
Added a gerrit trigger plugin in the jenkins. While setting up a gerrit server within the gerrit trigger configuration, I cannot remove the server already configured. It simply says

```<code>Cannot remove the last server!
</code>```

But I can edit the server details. Anyone has faced this issue?

```<code>Jenkins ver. 1.653
gerrit trigger version  2.21.1
</code>```

I dont have any job configured with Gerrit Trigger, and this jenkins is a fresh instance. Just have a test job

答:
There are must be some error in that gerrit server config section.

You can shutdown the tomcat if your jenkins was hold by tomcat, or shutdown the jenkins what ever.

Then goto /home/$yourname/.jenkins , edit gerrit-trigger.xml remove the server section. then restart jenkins and check it.

I just found it works.

Body:
Added a gerrit trigger plugin in the jenkins. While setting up a gerrit server within the gerrit trigger configuration, I cannot remove the server already configured. It simply says

Cannot remove the last server!

But I can edit the server details. Anyone has faced this issue?

Jenkins ver. 1.653
gerrit trigger version  2.21.1

I dont have any job configured with Gerrit Trigger, and this jenkins is a fresh instance. Just have a test job


问:
Applescript code completion shortcut
I'm new with applescript and this may seems dumb... but I have no clue at how to auto complete the code completion in the editor!?

I checked the option Use Script Assistant in the preferences.

For exemples When I create a new variable then I start to write it later in the code I can see in light grey color the word I want to auto complete.

But what is the shortcut to auto complete it? I tried spacebar, enter, shift + arrows... and so on

but have no clue

thanks for your help :P

答:
It probably changed whith sierra or High-Sierra :

It's now option + escape keys.

Title: Applescript code completion shortcut


问:
VBscript Can't Find Excel File
I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?</p>

```<code>Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")

Set objExcel = Nothing
Set objWorkbook = Nothing
</code>```

答:
From a windows command prompt type

```<code>c:\ dir C:\Users\Guest\Documents\Projects\1A.xlsx
</code>```

The file could have been saved with a different file extension, or if explorer is hiding extensions and a user has provided the extension on save it might be called 1A.xlsx.xslx

Windows explorer might be hiding data. If you can see it in explorer, right click the file > properties > details.

The Name attribute should tell you exactly what the file is named on disk and the Folder path should give you the path.

You can combine the two to give the full path to the file on disk

Title: VBscript Can't Find Excel File

Body:
I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")

Set objExcel = Nothing
Set objWorkbook = Nothing

Body:
From a windows command prompt type

c:\ dir C:\Users\Guest\Documents\Projects\1A.xlsx

The file could have been saved with a different file extension, or if explorer is hiding extensions and a user has provided the extension on save it might be called 1A.xlsx.xslx

Windows explorer might be hiding data. If you can see it in explorer, right click the file > properties > details.

The Name attribute should tell you exactly what the file is named on disk and the Folder path should give you the path.

You can combine the two to give the full path to the file on disk


问:
How to check for a node with a immediate ancestor using descendants method?
How do I get the values of a node whose immediate ancestor is another node (using descendants method), e.x. below is a small portion of a xml file

```<code><sec id="s2">
 <label>2.</label>
 <title>THE MORPHOLOGY OF CHONDRAE TENDIANEAE OF ATRIOVENTRICULAR VALVES HEARTS NEWBORNS AND INFANTS</title>
 <p>According to the macroscopic</p>
 <fig id="F1">
  <label>Figure 1.</label>
  <caption><p>Tendon string valvular heart baby infants. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
  <graphic xlink:href="00062_psisdg9066_90661R_page_2_1.jpg"/>
 </fig>
 <fig id="F2">
  <label>Figure 2.</label>
  <caption><p>Tendon string valvular heart newborn baby. 1 - mastoid muscle, 2 - tendon strings.</p></caption>
  <graphic xlink:href="00062_psisdg9066_90661R_page_2_2.jpg"/>
 </fig>
</sec>
<sec id="s3">
 <label>3.</label>
 <title>EXPERIMENTAL RESULTS AND DISCUSSION</title>
 <p>Material studies provided three-sided and mitral valve that were taken from 8 hearts of stillborn children and four dead infants.</p>
</sec>
</code>```

I want all the values of the node  which has a immediate ancestor node <sec>. i.e. in this case the value should be 2. and 3.
If I do

```<code>XDocument doc=XDocument.Load(@"D:\test\sample.XML");
var x = from a in doc.Descendants("label")
        where a.Ancestors("sec").Attributes("id").Any()
        select a.Value;
</code>```

I get 2., Figure 1., Figure 2., 3., what other conditions do I have to add to achieve what I want?

答:
Ancestors("sec") will find all ancestors, no matter how deeply nested, not the immediate ancestors, so that's not going to help.

You need to get only the first ancestor. Since Ancestors() will return them in reverse document order, we can simply get the first.

```<code>var x = from a in doc.Descendants("label")
    let ancestor = a.Ancestors().First()
    where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
    select a.Value;
</code>```

Body:
How do I get the values of a node whose immediate ancestor is another node (using descendants method), e.x. below is a small portion of a xml file

<sec id="s2">
 2.
 <title>THE MORPHOLOGY OF CHONDRAE TENDIANEAE OF ATRIOVENTRICULAR VALVES HEARTS NEWBORNS AND INFANTS</title>

According to the macroscopic

 <fig id="F1">
  Figure 1.

Tendon string valvular heart baby infants. 1 - mastoid muscle, 2 - tendon strings.

  <graphic xlink:href="00062_psisdg9066_90661R_page_2_1.jpg"/>
 </fig>
 <fig id="F2">
  Figure 2.

Tendon string valvular heart newborn baby. 1 - mastoid muscle, 2 - tendon strings.

  <graphic xlink:href="00062_psisdg9066_90661R_page_2_2.jpg"/>
 </fig>
</sec>
<sec id="s3">
 3.
 <title>EXPERIMENTAL RESULTS AND DISCUSSION</title>

Material studies provided three-sided and mitral valve that were taken from 8 hearts of stillborn children and four dead infants.

</sec>

I want all the values of the node  which has a immediate ancestor node <sec>. i.e. in this case the value should be 2. and 3.
If I do

XDocument doc=XDocument.Load(@"D:\test\sample.XML");
var x = from a in doc.Descendants("label")
        where a.Ancestors("sec").Attributes("id").Any()
        select a.Value;

I get 2., Figure 1., Figure 2., 3., what other conditions do I have to add to achieve what I want?

Body:
Ancestors("sec") will find all ancestors, no matter how deeply nested, not the immediate ancestors, so that's not going to help.

You need to get only the first ancestor. Since Ancestors() will return them in reverse document order, we can simply get the first.

var x = from a in doc.Descendants("label")
    let ancestor = a.Ancestors().First()
    where ancestor.Name == "sec" && ancestor.Attributes("id").Any()
    select a.Value;


问:
Encrypted database on device or cloud stored database?
I have a pre-populated SQLite database for my Android app and I need to do some reads to show elements for an autoCompleteTextView and then other few operation, only reads on the database.

In the past days I've read about SQLCipher and Cloud Firestore by Firebase. SQLCipher seems what I was looking for but I read that I can't use it with a pre-populated database. I think that Firestore (or any other cloud service) it's my only other solution but I'm a little worried about the price and the possibile delay between the input on the ACTV and the server results.

The database does not contain any user information or other sensitive data, I just want to protect my work. I've no need for the strongest protection.

Can I use Firestore with my SQLite database? Are there any other solution for my problem? Thanks!

答:
If you want to use Firebase, you need to know that there is way in which you can secure your database very simply using Firebase Database Security Rules.

Firebase Realtime Database Rules determine who has read and write access to your database, how your data is structured, and what indexes exist. These rules live on the Firebase servers and are enforced automatically at all times. Every read and write request will only be completed if your rules allow it. By default, your rules are set to allow only authenticated users full read and write access to your database. This is to protect your database from abuse until you have time to customize your rules or set up authentication.

If you want to use the new Firestore release (which is currently in beta release) please take a look at Secure Data in Cloud Firestore offical documentation for more informations.

Another thing to note is that also Firebase and Firestore can provide offline capabilities. So the pplications will work even if your app temporarily loses its network connection. So there is no need for other database in order to achieve that.

Another thing to note is that Firebase can provide Anonymously Authenticatin.

As a conclusion Firebase can provide you security, even your app does or does not contain any user information or other sensitive data.


Title: How to compute future row percentage change in Pandas DataTable

Body:
I have a Pandas DataTable and I'm trying to compute the max from the next x rows as a percentage compared to the current row. Eg, I have something like this:

|  datetime           |  open    |   high   |   low    |  close   |   volume    |
| 2016-12-06 14:00:00 | 0.009142 | 0.009152 | 0.008839 | 0.009038 |  888.080994 |
| 2016-12-06 15:00:00 | 0.009030 | 0.009200 | 0.008887 | 0.009076 | 1245.985840 |
| 2016-12-06 16:00:00 | 0.009070 | 0.009510 | 0.008992 | 0.009510 | 1630.514648 |
| 2016-12-06 17:00:00 | 0.009510 | 0.009889 | 0.009500 | 0.009677 | 2944.323730 |
| 2016-12-06 18:00:00 | 0.009677 | 0.009764 | 0.009400 | 0.009403 |  980.190186 |
| 2016-12-06 19:00:00 | 0.009410 | 0.009580 | 0.009361 | 0.009515 |  651.947754 |
| 2016-12-06 20:00:00 | 0.009515 | 0.010175 | 0.009510 | 0.009925 | 1637.252319 |
| 2016-12-06 21:00:00 | 0.009915 | 0.010430 | 0.009900 | 0.010383 | 2029.841675 |

I want to add a column which shows the highest price from the next n rows expressed as a percentage from the current row's open value.

I've got as far as this, which is from column "high" to "high" (ideally I'd like to use open to high).

periods = 3
df['high_pct'] = df['high'].rolling(periods).max().pct_change().shift(-periods)

But this is leaving me with some zero values and I can't figure out why:

|      datetime       |   open   |   high   |   low    |  close   |   volume    | high_pct |
| 2016-12-06 14:00:00 | 0.009142 | 0.009152 | 0.008839 | 0.009038 |  888.080994 | 0.039841 |
| 2016-12-06 15:00:00 | 0.009030 | 0.009200 | 0.008887 | 0.009076 | 1245.985840 | 0.000000 |
| 2016-12-06 16:00:00 | 0.009070 | 0.009510 | 0.008992 | 0.009510 | 1630.514648 | 0.000000 |
| 2016-12-06 17:00:00 | 0.009510 | 0.009889 | 0.009500 | 0.009677 | 2944.323730 | 0.028932 |
| 2016-12-06 18:00:00 | 0.009677 | 0.009764 | 0.009400 | 0.009403 |  980.190186 | 0.025062 |
| 2016-12-06 19:00:00 | 0.009410 | 0.009580 | 0.009361 | 0.009515 |  651.947754 | 0.000947 |
| 2016-12-06 20:00:00 | 0.009515 | 0.010175 | 0.009510 | 0.009925 | 1637.252319 | 0.000000 |
| 2016-12-06 21:00:00 | 0.009915 | 0.010430 | 0.009900 | 0.010383 | 2029.841675 | 0.000000 |

Am I on the right lines? Can anyone suggest a different approach if needed?

Thanks!

Body:
IIUC, I think you want something like this:

df['high_pct'] = df['high'].rolling(3, min_periods=1).max().shift(-2).ffill() / df['high'] - 1

Output:

                datetime      open      high       low     close       volume  \
0   2016-12-06 14:00:00   0.009142  0.009152  0.008839  0.009038   888.080994
1   2016-12-06 15:00:00   0.009030  0.009200  0.008887  0.009076  1245.985840
2   2016-12-06 16:00:00   0.009070  0.009510  0.008992  0.009510  1630.514648
3   2016-12-06 17:00:00   0.009510  0.009889  0.009500  0.009677  2944.323730
4   2016-12-06 18:00:00   0.009677  0.009764  0.009400  0.009403   980.190186
5   2016-12-06 19:00:00   0.009410  0.009580  0.009361  0.009515   651.947754
6   2016-12-06 20:00:00   0.009515  0.010175  0.009510  0.009925  1637.252319
7   2016-12-06 21:00:00   0.009915  0.010430  0.009900  0.010383  2029.841675

   high_pct
0  0.039117
1  0.074891
2  0.039853
3  0.000000
4  0.042093
5  0.088727
6  0.025061
7  0.000000


问:
Please explain this base 62 PHP conversion function/algorithm
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

```<code>private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}
</code>```

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

答:
There is a formula when working with logarithms:

logN(x) = log10(x) / log10(N).

In other words, the log of a number in base N is equal to the log (in base 10) of the number divided by the log (again in base 10) of the base.

So instead of creating a logarithm function for each base, like base 62, you can simply use the native log10() function and scale the numbers accordingly.

And in this particular algorithm, you want to determine how many digits there are, in base 62, for the number you are converting, so you can use that in the "for" loop.

You could, of course, do this is with a while loop without having to calculate log62(n). This is an exercise for the reader.

Body:
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.


问:
warning illegal string offset while fetching result from database
I am using the following code to find the data from database

```<code>echo $query = "select * from `oc_order` where `store_url`='' ORDER BY `order_id` DESC LIMIT 5";
$mysqlq = mysqli_query($connection,$query) or die(mysqli_error($connection));
$mysqlw = mysqli_fetch_array($mysqlq);
echo "```";
print_r($mysqlw);
foreach($mysqlw as $mysqlw)
{
    echo $mysqlw['telephone'];
}
?>
```

<p>I am getting the following array</p>

```Array
(
    [0] => 73
    [order_id] => 73
    [1] => 0
    [invoice_no] => 0
    [2] =>
    [invoice_prefix] =>
    [3] => 0
    [store_id] => 0
    [4] =>
    [store_name] =>
    [5] =>
    [store_url] =>
    [6] => 9
    [customer_id] => 9
    [7] => 1
    [customer_group_id] => 1
    [8] => T****
    [firstname] => ****
    [9] =>
    [lastname] =>
    [10] => ********
    [email] => *******
    [11] => *****
    [telephone] => *****
    [12] =>
    [fax] =>
    [13] => 364ce6e2003bb1404f34
    [custom_field] => 364ce6e2003bb1404f34
    [14] =>
    [payment_firstname] =>
    [15] =>
    [payment_lastname] =>
    [16] =>
    [payment_company] =>
    [17] =>
    [payment_address_1] =>
    [18] =>
    [payment_address_2] =>
    [19] =>
    [payment_city] =>
    [20] =>
    [payment_postcode] =>
    [21] =>
    [payment_country] =>
    [22] => 0
    [payment_country_id] => 0
    [23] =>
    [payment_zone] =>
    [24] => 0
    [payment_zone_id] => 0
    [25] =>
    [payment_address_format] =>
    [26] =>
    [payment_custom_field] =>
    [27] =>
    [payment_method] =>
    [28] =>
    [payment_code] =>
    [29] =>
    [shipping_firstname] =>
    [30] =>
    [shipping_lastname] =>
    [31] =>
    [shipping_company] =>
    [32] =>
    [shipping_address_1] =>
    [33] =>
    [shipping_address_2] =>
    [34] =>
    [shipping_city] =>
    [35] =>
    [shipping_postcode] =>
    [36] =>
    [shipping_country] =>
    [37] => 0
    [shipping_country_id] => 0
    [38] =>
    [shipping_zone] =>
    [39] => 0
    [shipping_zone_id] => 0
    [40] =>
    [shipping_address_format] =>
    [41] =>
    [shipping_custom_field] =>
    [42] =>
    [shipping_method] =>
    [43] =>
    [shipping_code] =>
    [44] => 1,19
    [comment] => 1,19
    [45] => 100.0000
    [total] => 100.0000
    [46] => 0
    [order_status_id] => 0
    [47] => 0
    [affiliate_id] => 0
    [48] => 0.0000
    [commission] => 0.0000
    [49] => 0
    [marketing_id] => 0
    [50] =>
    [tracking] =>
    [51] => 0
    [language_id] => 0
    [52] => 0
    [currency_id] => 0
    [53] => INR
    [currency_code] => INR
    [54] => 1.00000000
    [currency_value] => 1.00000000
    [55] =>
    [ip] =>
    [56] =>
    [forwarded_ip] =>
    [57] =>
    [user_agent] =>
    [58] =>
    [accept_language] =>
    [59] => 0000-00-00 00:00:00
    [date_added] => 0000-00-00 00:00:00
    [60] => 0000-00-00 00:00:00
    [date_modified] => 0000-00-00 00:00:00
)
```

but when i am trying to print the value of echo $mysqlw['telephone']; it is throwing warning Warning: Illegal string offset 'telephone' in

What mistake I am making in this code ?

答:
You are trying to do a foreach on the array that you've displayed in your post. That means you're cycling through each item in the array. By trying to access $mysqlw['telephone'] you're expecting the item in the array to be another array containing the key 'telephone'.

I believe you're intending to do this:

```<code>while ($mysqlw = mysqli_fetch_array($mysqlq) {
   echo $mysqlw['telephone'];
}
</code>```

But also, you really should read up on how to do MySQL in a more modern style. Using things like mysqli_query in the manner you've used it here can open you up to injection attacks when you start having user input involved in the query.

Body:
I am using the following code to find the data from database

echo $query = "select * from `oc_order` where `store_url`='' ORDER BY `order_id` DESC LIMIT 5";
$mysqlq = mysqli_query($connection,$query) or die(mysqli_error($connection));
$mysqlw = mysqli_fetch_array($mysqlq);
echo "
";
print_r($mysqlw);
foreach($mysqlw as $mysqlw)
{
    echo $mysqlw['telephone'];
}
?>

I am getting the following array

Array
(
    [0] => 73
    [order_id] => 73
    [1] => 0
    [invoice_no] => 0
    [2] =>
    [invoice_prefix] =>
    [3] => 0
    [store_id] => 0
    [4] =>
    [store_name] =>
    [5] =>
    [store_url] =>
    [6] => 9
    [customer_id] => 9
    [7] => 1
    [customer_group_id] => 1
    [8] => T****
    [firstname] => ****
    [9] =>
    [lastname] =>
    [10] => ********
    [email] => *******
    [11] => *****
    [telephone] => *****
    [12] =>
    [fax] =>
    [13] => 364ce6e2003bb1404f34
    [custom_field] => 364ce6e2003bb1404f34
    [14] =>
    [payment_firstname] =>
    [15] =>
    [payment_lastname] =>
    [16] =>
    [payment_company] =>
    [17] =>
    [payment_address_1] =>
    [18] =>
    [payment_address_2] =>
    [19] =>
    [payment_city] =>
    [20] =>
    [payment_postcode] =>
    [21] =>
    [payment_country] =>
    [22] => 0
    [payment_country_id] => 0
    [23] =>
    [payment_zone] =>
    [24] => 0
    [payment_zone_id] => 0
    [25] =>
    [payment_address_format] =>
    [26] =>
    [payment_custom_field] =>
    [27] =>
    [payment_method] =>
    [28] =>
    [payment_code] =>
    [29] =>
    [shipping_firstname] =>
    [30] =>
    [shipping_lastname] =>
    [31] =>
    [shipping_company] =>
    [32] =>
    [shipping_address_1] =>
    [33] =>
    [shipping_address_2] =>
    [34] =>
    [shipping_city] =>
    [35] =>
    [shipping_postcode] =>
    [36] =>
    [shipping_country] =>
    [37] => 0
    [shipping_country_id] => 0
    [38] =>
    [shipping_zone] =>
    [39] => 0
    [shipping_zone_id] => 0
    [40] =>
    [shipping_address_format] =>
    [41] =>
    [shipping_custom_field] =>
    [42] =>
    [shipping_method] =>
    [43] =>
    [shipping_code] =>
    [44] => 1,19
    [comment] => 1,19
    [45] => 100.0000
    [total] => 100.0000
    [46] => 0
    [order_status_id] => 0
    [47] => 0
    [affiliate_id] => 0
    [48] => 0.0000
    [commission] => 0.0000
    [49] => 0
    [marketing_id] => 0
    [50] =>
    [tracking] =>
    [51] => 0
    [language_id] => 0
    [52] => 0
    [currency_id] => 0
    [53] => INR
    [currency_code] => INR
    [54] => 1.00000000
    [currency_value] => 1.00000000
    [55] =>
    [ip] =>
    [56] =>
    [forwarded_ip] =>
    [57] =>
    [user_agent] =>
    [58] =>
    [accept_language] =>
    [59] => 0000-00-00 00:00:00
    [date_added] => 0000-00-00 00:00:00
    [60] => 0000-00-00 00:00:00
    [date_modified] => 0000-00-00 00:00:00
)

but when i am trying to print the value of echo $mysqlw['telephone']; it is throwing warning Warning: Illegal string offset 'telephone' in

What mistake I am making in this code ?

Body:
You are trying to do a foreach on the array that you've displayed in your post. That means you're cycling through each item in the array. By trying to access $mysqlw['telephone'] you're expecting the item in the array to be another array containing the key 'telephone'.

I believe you're intending to do this:

while ($mysqlw = mysqli_fetch_array($mysqlq) {
   echo $mysqlw['telephone'];
}

But also, you really should read up on how to do MySQL in a more modern style. Using things like mysqli_query in the manner you've used it here can open you up to injection attacks when you start having user input involved in the query.