问:
using curve_fit (python) with a gaussian function which gives you mean and variance
I have a problem with using curve_fit from scipy. Or at least it dosen't work the way that I expect it to work.

I have some kind of dataset from a histogram and the x-values are the sizes from the histogram as a numpy array. If needed, I will add my data later. The histogram has pretty much a Gaussian shape and I want to fit a Gauss function to it with only two free parameters, but it don't work.

With three parameters the code works fine:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

hist=np.load('Rinnen.npy')
faktor = np.sum(hist)

norm_hist=hist/faktor # values from the histogram are normed

ref_werte = np.arange(0,1,0.001)

def gauss(x, *p):
  a, b, c = p
  y = a*np.exp(-0.5*((x - b)/c)**2.)

  return y

p_initial = [0.1, 0.0, 0.1]

popt, pcov = curve_fit(gauss, ref_werte, norm_hist, p0=p_initial)

print(popt) #zeigen der koeffizienten

plt.figure()
plt.plot(ref_werte, norm_hist, linewidth=2.0, color='b')
plt.plot(ref_werte, gauss(ref_werte, *popt), 'b-', linewidth=2.0, color='r')
plt.xlabel('Reflektanzen')
plt.ylabel('normierte Häufigkeit')
plt.show()
</code>```

But my goal is do use a Gaussian which is the PDF of a normal distributen (see wikipedia). But when I change my code and use a new definition of a function like the following one it messes up everything and don't work at all.

```<code>def gauss(x, *p):
  b, c = p
  kons = np.sqrt(2.*np.pi)
  y = (1./(c*kons))*np.exp(-0.5*((x - b)/c)**2.)

  return y
</code>```

Even if I use for the p_initial values that are really close to the histogram like p_initial = [0.08 , 0.02] nothing works and I really don't understand why.

Would be really happy if someone could help me.

EDIT: A code example

One example array for hist is:

```<code>array([    0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     4,
          30,   224,  2257,  3603,  2029,  2412,  1391,  2269,  3789,
        8279,  9091,  6617,  7087,  5071,  2316,  2675,  2273,  3913,
        2299,  3573,  1761,  2445,  2426,  3261,  5881,  8408, 11659,
       15174, 21250, 19644, 32068, 25315, 19329, 23333, 17168, 15748,
       15744, 15045, 14274, 11566, 13887, 10144,  8532, 10696,  8531,
        9687,  9493,  9424, 10294,  8869,  9509,  8445,  7723,  8515,
        7137,  7464,  8006,  6440,  6457,  4999,  5364,  4519,  4361,
        3976,  3366,  3352,  2833,  2475,  2332,  1881,  1905,  1639,
        1568,  1318,  1141,  1130,  1010,   907,   906,   823,   789,
         745,   726,   674,   692,   630,   610,   568,   575,   589,
         535,   538,   522,   511,   513,   534,   467,   446,   445,
         337,   441,   454,   451,   438,   417,   388,   456,   405,
         408,   399,   356,   404,   371,   412,   404,   401,   389,
         354,   342,   358,   317,   306,   303,   295,   303,   294,
         288,   251,   256,   226,   178,   241,   213,   196,   215,
         210,   184,   165,   208,   200,   181,   171,   136,   156,
         147,   137,   102,   119,   116,    89,   117,   104,    85,
          77,    74,    52,    69,    34,    47,    44,    50,    32,
          27,    34,    38,    24,    21,    28,    24,    22,    25,
          19,    17,    15,    17,    18,    14,    11,    12,     5,
           9,     9,     9,     6,     5,     5,     8,     7,     4,
           4,     2,     1,     4,     0,     2,     2,     2,     3,
           2,     3,     1,     1,     2,     1,     2,     2,     0,
           1,     1,     2,     1,     1,     2,     0,     0,     0,
           0,     0,     1,     1,     0,     0,     0,     0,     0,
           0,     0,     1,     0,     0,     0,     0,     0,     0,
           1,     0,     0,     0,     1,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,     0])
</code>```

With this array my code works with the version with three parameters and I get [ 0.02697915  0.08060284  0.01334016] as a result. If I change my code to the two parameter version with the same array and everything in the same way... then it doesn't fit and work at all. I used an other version of p_initial = [0.08 , 0.02], which uses the mean and the standard derivation the result is not true at all: [-1.62281493  0.53329897].

Body:
I have a problem with using curve_fit from scipy. Or at least it dosen't work the way that I expect it to work.

I have some kind of dataset from a histogram and the x-values are the sizes from the histogram as a numpy array. If needed, I will add my data later. The histogram has pretty much a Gaussian shape and I want to fit a Gauss function to it with only two free parameters, but it don't work.

With three parameters the code works fine:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

hist=np.load('Rinnen.npy')
faktor = np.sum(hist)

norm_hist=hist/faktor # values from the histogram are normed

ref_werte = np.arange(0,1,0.001)

def gauss(x, *p):
  a, b, c = p
  y = a*np.exp(-0.5*((x - b)/c)**2.)

  return y

p_initial = [0.1, 0.0, 0.1]

popt, pcov = curve_fit(gauss, ref_werte, norm_hist, p0=p_initial)

print(popt) #zeigen der koeffizienten

plt.figure()
plt.plot(ref_werte, norm_hist, linewidth=2.0, color='b')
plt.plot(ref_werte, gauss(ref_werte, *popt), 'b-', linewidth=2.0, color='r')
plt.xlabel('Reflektanzen')
plt.ylabel('normierte Häufigkeit')
plt.show()

But my goal is do use a Gaussian which is the PDF of a normal distributen (see wikipedia). But when I change my code and use a new definition of a function like the following one it messes up everything and don't work at all.

def gauss(x, *p):
  b, c = p
  kons = np.sqrt(2.*np.pi)
  y = (1./(c*kons))*np.exp(-0.5*((x - b)/c)**2.)

  return y

Even if I use for the p_initial values that are really close to the histogram like p_initial = [0.08 , 0.02] nothing works and I really don't understand why.

Would be really happy if someone could help me.

EDIT: A code example

One example array for hist is:

array([    0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     4,
          30,   224,  2257,  3603,  2029,  2412,  1391,  2269,  3789,
        8279,  9091,  6617,  7087,  5071,  2316,  2675,  2273,  3913,
        2299,  3573,  1761,  2445,  2426,  3261,  5881,  8408, 11659,
       15174, 21250, 19644, 32068, 25315, 19329, 23333, 17168, 15748,
       15744, 15045, 14274, 11566, 13887, 10144,  8532, 10696,  8531,
        9687,  9493,  9424, 10294,  8869,  9509,  8445,  7723,  8515,
        7137,  7464,  8006,  6440,  6457,  4999,  5364,  4519,  4361,
        3976,  3366,  3352,  2833,  2475,  2332,  1881,  1905,  1639,
        1568,  1318,  1141,  1130,  1010,   907,   906,   823,   789,
         745,   726,   674,   692,   630,   610,   568,   575,   589,
         535,   538,   522,   511,   513,   534,   467,   446,   445,
         337,   441,   454,   451,   438,   417,   388,   456,   405,
         408,   399,   356,   404,   371,   412,   404,   401,   389,
         354,   342,   358,   317,   306,   303,   295,   303,   294,
         288,   251,   256,   226,   178,   241,   213,   196,   215,
         210,   184,   165,   208,   200,   181,   171,   136,   156,
         147,   137,   102,   119,   116,    89,   117,   104,    85,
          77,    74,    52,    69,    34,    47,    44,    50,    32,
          27,    34,    38,    24,    21,    28,    24,    22,    25,
          19,    17,    15,    17,    18,    14,    11,    12,     5,
           9,     9,     9,     6,     5,     5,     8,     7,     4,
           4,     2,     1,     4,     0,     2,     2,     2,     3,
           2,     3,     1,     1,     2,     1,     2,     2,     0,
           1,     1,     2,     1,     1,     2,     0,     0,     0,
           0,     0,     1,     1,     0,     0,     0,     0,     0,
           0,     0,     1,     0,     0,     0,     0,     0,     0,
           1,     0,     0,     0,     1,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,     0])

With this array my code works with the version with three parameters and I get [ 0.02697915  0.08060284  0.01334016] as a result. If I change my code to the two parameter version with the same array and everything in the same way... then it doesn't fit and work at all. I used an other version of p_initial = [0.08 , 0.02], which uses the mean and the standard derivation the result is not true at all: [-1.62281493  0.53329897].

Body:
The normal distribution is a continuous distribution, therefore you mustn't normalize the sum of your histogram, but the integral.

Here is a version of your code that works for me. The only thing I changed is dividing your histogram by the bin width. It returns [ 0.08083458  0.01470529]:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

hist = np.array([    0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     4,
          30,   224,  2257,  3603,  2029,  2412,  1391,  2269,  3789,
        8279,  9091,  6617,  7087,  5071,  2316,  2675,  2273,  3913,
        2299,  3573,  1761,  2445,  2426,  3261,  5881,  8408, 11659,
       15174, 21250, 19644, 32068, 25315, 19329, 23333, 17168, 15748,
       15744, 15045, 14274, 11566, 13887, 10144,  8532, 10696,  8531,
        9687,  9493,  9424, 10294,  8869,  9509,  8445,  7723,  8515,
        7137,  7464,  8006,  6440,  6457,  4999,  5364,  4519,  4361,
        3976,  3366,  3352,  2833,  2475,  2332,  1881,  1905,  1639,
        1568,  1318,  1141,  1130,  1010,   907,   906,   823,   789,
         745,   726,   674,   692,   630,   610,   568,   575,   589,
         535,   538,   522,   511,   513,   534,   467,   446,   445,
         337,   441,   454,   451,   438,   417,   388,   456,   405,
         408,   399,   356,   404,   371,   412,   404,   401,   389,
         354,   342,   358,   317,   306,   303,   295,   303,   294,
         288,   251,   256,   226,   178,   241,   213,   196,   215,
         210,   184,   165,   208,   200,   181,   171,   136,   156,
         147,   137,   102,   119,   116,    89,   117,   104,    85,
          77,    74,    52,    69,    34,    47,    44,    50,    32,
          27,    34,    38,    24,    21,    28,    24,    22,    25,
          19,    17,    15,    17,    18,    14,    11,    12,     5,
           9,     9,     9,     6,     5,     5,     8,     7,     4,
           4,     2,     1,     4,     0,     2,     2,     2,     3,
           2,     3,     1,     1,     2,     1,     2,     2,     0,
           1,     1,     2,     1,     1,     2,     0,     0,     0,
           0,     0,     1,     1,     0,     0,     0,     0,     0,
           0,     0,     1,     0,     0,     0,     0,     0,     0,
           1,     0,     0,     0,     1,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,     0])

faktor = np.sum(hist)

ref_werte = np.arange(0,1,0.001)

bin_width = 0.001

norm_hist=hist/(bin_width*faktor) # values from the histogram are normed

def gauss(x, *p):
  b, c = p
  kons = np.sqrt(2.*np.pi)
  y = (1./(c*kons))*np.exp(-0.5*((x - b)/c)**2.)

  return y

p_initial = [0, 1]

popt, pcov = curve_fit(gauss, ref_werte, norm_hist, p0=p_initial)

print(popt) #zeigen der koeffizienten

plt.figure()
plt.plot(ref_werte, norm_hist, linewidth=2.0, color='b')
plt.plot(ref_werte, gauss(ref_werte, *popt), 'b-', linewidth=2.0, color='r')
plt.xlabel('Reflektanzen')
plt.ylabel('normierte Häufigkeit')
plt.show()


来源: stackexchange

问:
SQL SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB)
So I have two tables and I want to use a concat on one of the columns in each table.

TableA

```<code>ColumnA
1
1
2
3
4
4
5
</code>```

TableB

```<code>ColumnX
a
a
b
c
d
d
e
</code>```

And I want to concat these two columns so they end up looking like the below result WITHOUT dublicates

```<code>Result
1|a
2|b
3|c
4|d
5|e
</code>```

So I have tried to do the following:

```<code>SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB) where tableA.Relation = TableB.Relation
</code>```

But I am still getting dublicates!? Why????

答:
This is similar only without the CTE</p>

```<code>select distinct A.a + '|' + B.b
from
(select a, Row_Number() over (order by a) as rowNum
from TableA) as A,
(select b, Row_Number() over (order by b) as rowNum
from TableB) as B
where A.rowNum = b.rowNum
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have two tables and I want to use a concat on one of the columns in each table.

TableA

ColumnA
1
1
2
3
4
4
5

TableB

ColumnX
a
a
b
c
d
d
e

And I want to concat these two columns so they end up looking like the below result WITHOUT dublicates

Result
1|a
2|b
3|c
4|d
5|e

So I have tried to do the following:

SELECT DISTINCT CONCAT(ColumnA,'|',ColumnB) where tableA.Relation = TableB.Relation

But I am still getting dublicates!? Why????

Body:
This is similar only without the CTE

select distinct A.a + '|' + B.b
from
(select a, Row_Number() over (order by a) as rowNum
from TableA) as A,
(select b, Row_Number() over (order by b) as rowNum
from TableB) as B
where A.rowNum = b.rowNum


问:
Comparing DistinguishedName of 2 Arrays and get back all the Data
I have to make a script to get all EoL Windows Machines. But i have to make a Whitelist for some exceptions.

First I get all old Computers:

```<code>$getad = Get-ADComputer -Filter {
    (operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*"`) `
    -or (operatingsystem -like "*Windows Vista*") `
    -or (operatingsystem -like "*Windows XP*") `
    -or (operatingsystem -like "*95*") `
    -or (operatingsystem -like "*94*") `
    -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") `
    -or (operatingsystem -like "*2000 Professional*") `
    -or (operatingsystem -like "*2000 Server*") `
    -or (operatingsystem -like "*2003*") `
    -or (operatingsystem -like "*Windows NT*") `
    -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")
} `
-Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

$selectobj = $getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName

</code>```

Then I load the Whitelist into a variable:

```<code>  $whitelisted = Get-Content "C:\Users\example\Desktop\whitelistedpcs.txt"
</code>```

Then i First empty out a variable (to be sure) and then i compare the computers I got with my Whitelist.

```<code>$AlertoldComputers = $null

$alertcompdist = Compare-Object -ReferenceObject $selectobj.DistinguishedName -DifferenceObject $whitelisted
</code>```

Now my result is a list of all Computers that are not on the Whitelist, but I've just got the Distinguished Name. I need all the Information:

Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName

I've tried to do it with a foreach but then i get no output at all:

```<code>foreach ($alertcomputer in $alertcompdist) {
    $AlertoldComputers += Get-ADComputer -Filter {(DistinguishedName -like "*$alertcomputer*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName') | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName
}
</code>```

The output should look something like this:

Name                   : Examplename

Operatingsystem        : Windows 10 Enterprise

DistinguishedName      : CN=Examplename,OU=Bla,OU=Da,OU=computers,OU=dadada,OU=gugu,DC=tra,DC=la,DC=la

Description            : Its just an example

Lastlogondate          : 01.01.1000

OperatingSystemVersion : 10.0 (10586)

Created                : 01.01.1000

Enabled                : True

SamAccountName         : Example

答:
Can you try with this?

The aim is to display computers AD informations and with if ($whitelisted -match $_.DistinguishedName), you check if a value is found in the list of hostnames that are whitelisted :

```<code>$getad = Get-ADComputer -Filter {(operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*") -or (operatingsystem -like "*Windows Vista*") -or (operatingsystem -like "*Windows XP*") -or  (operatingsystem -like "*95*") -or (operatingsystem -like "*94*") -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") -or (operatingsystem -like "*2000 Professional*") -or (operatingsystem -like "*2000 Server*") -or (operatingsystem -like "*2003*") -or (operatingsystem -like "*Windows NT*") -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

$whitelisted = Get-Content "C:\Users\example\Desktop\whitelistedpcs.txt"

$getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName | ForEach-Object {
    if ($whitelisted -match $_.DistinguishedName) {
        Write-Host "$($_.DistinguishedName) is whitelisted"
    }
    else{
        Write-Host "$($_.DistinguishedName) is not whitelisted" -ForegroundColor Yellow
        $_
    }
}
</code>```

Body:
I have to make a script to get all EoL Windows Machines. But i have to make a Whitelist for some exceptions.

First I get all old Computers:

$getad = Get-ADComputer -Filter {
    (operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*"`) `
    -or (operatingsystem -like "*Windows Vista*") `
    -or (operatingsystem -like "*Windows XP*") `
    -or (operatingsystem -like "*95*") `
    -or (operatingsystem -like "*94*") `
    -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") `
    -or (operatingsystem -like "*2000 Professional*") `
    -or (operatingsystem -like "*2000 Server*") `
    -or (operatingsystem -like "*2003*") `
    -or (operatingsystem -like "*Windows NT*") `
    -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")
} `
-Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

$selectobj = $getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName

Then I load the Whitelist into a variable:

  $whitelisted = Get-Content "C:\Users\example\Desktop\whitelistedpcs.txt"

Then i First empty out a variable (to be sure) and then i compare the computers I got with my Whitelist.

$AlertoldComputers = $null

$alertcompdist = Compare-Object -ReferenceObject $selectobj.DistinguishedName -DifferenceObject $whitelisted

Now my result is a list of all Computers that are not on the Whitelist, but I've just got the Distinguished Name. I need all the Information:

Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName

I've tried to do it with a foreach but then i get no output at all:

foreach ($alertcomputer in $alertcompdist) {
    $AlertoldComputers += Get-ADComputer -Filter {(DistinguishedName -like "*$alertcomputer*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName') | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName
}

The output should look something like this:

Name                   : Examplename

Operatingsystem        : Windows 10 Enterprise

DistinguishedName      : CN=Examplename,OU=Bla,OU=Da,OU=computers,OU=dadada,OU=gugu,DC=tra,DC=la,DC=la

Description            : Its just an example

Lastlogondate          : 01.01.1000

OperatingSystemVersion : 10.0 (10586)

Created                : 01.01.1000

Enabled                : True

SamAccountName         : Example

Body:
Can you try with this?

The aim is to display computers AD informations and with if ($whitelisted -match $_.DistinguishedName), you check if a value is found in the list of hostnames that are whitelisted :

$getad = Get-ADComputer -Filter {(operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*") -or (operatingsystem -like "*Windows Vista*") -or (operatingsystem -like "*Windows XP*") -or  (operatingsystem -like "*95*") -or (operatingsystem -like "*94*") -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") -or (operatingsystem -like "*2000 Professional*") -or (operatingsystem -like "*2000 Server*") -or (operatingsystem -like "*2003*") -or (operatingsystem -like "*Windows NT*") -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

$whitelisted = Get-Content "C:\Users\example\Desktop\whitelistedpcs.txt"

$getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName | ForEach-Object {
    if ($whitelisted -match $_.DistinguishedName) {
        Write-Host "$($_.DistinguishedName) is whitelisted"
    }
    else{
        Write-Host "$($_.DistinguishedName) is not whitelisted" -ForegroundColor Yellow
        $_
    }
}


问:
Event Handler Use
Is there a way to have a function executed when an automated script is completed, as opposed to having the function initiated in response to a user's action, such as mouse movement?</p>

答:
I just modified your code.</p>

```<code><font face="helvetica" color="1b1b1b" size="5px" repeat>

<html>
<head>
<style type="text/css">
#text-box {

padding: 4px;
width: 602px;
}
#text-content {
color: #1b1b1b;

}
</style>

</head>
<body>

<div id="text-box">
<div id="text-content"></div>

</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready( function() {
var textArray = [
'Flow',
'Precision',
'Voice',
'Imagery',
'Pace',
'Unity',
'Word Choice',
'Rhythm',
'Inspiration',
'Balance',
'Clarity',
'Simplicity',
'Revision',
'Discipline',
'Fundamentals',
'Dedication',
'Practice',
];
$('#text-content').loadText( textArray, 5500 ); // ( array, interval )
});

// custom jquery plugin loadText()
$.fn.loadText = function( textArray, interval ) {
return this.each( function() {
var obj = $(this);
obj.fadeOut( 'slow', function() {
obj.empty().html( random_array( textArray ) );
obj.fadeIn( 'slow' );
alignarray()
});

timeOut = setTimeout( function(){ obj.loadText( textArray, interval )}, interval );

});
}
//public function
function random_array( aArray ) {
var rand = Math.floor( Math.random() * aArray.length + aArray.length );
var randArray = aArray[ rand - aArray.length ];
return randArray;
}

function nameoffunction(){
    //code in this function will be done after the window loads
    alert("random_array");
}

function alignarray(){
    var alignarray=['left','center','right'];
    var elem=document.getElementById('text-content');
    elem.style.textAlign=alignarray[Math.round(Math.random()*2)];
    nameoffunction();
}
</script>
</html>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Event Handler Use

Body:
I just modified your code.

<font face="helvetica" color="1b1b1b" size="5px" repeat>

<html>
<head>
<style type="text/css">
#text-box {

padding: 4px;
width: 602px;
}
#text-content {
color: #1b1b1b;

}
</style>

</head>
<body>

<div id="text-box">
<div id="text-content"></div>

</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready( function() {
var textArray = [
'Flow',
'Precision',
'Voice',
'Imagery',
'Pace',
'Unity',
'Word Choice',
'Rhythm',
'Inspiration',
'Balance',
'Clarity',
'Simplicity',
'Revision',
'Discipline',
'Fundamentals',
'Dedication',
'Practice',
];
$('#text-content').loadText( textArray, 5500 ); // ( array, interval )
});

// custom jquery plugin loadText()
$.fn.loadText = function( textArray, interval ) {
return this.each( function() {
var obj = $(this);
obj.fadeOut( 'slow', function() {
obj.empty().html( random_array( textArray ) );
obj.fadeIn( 'slow' );
alignarray()
});

timeOut = setTimeout( function(){ obj.loadText( textArray, interval )}, interval );

});
}
//public function
function random_array( aArray ) {
var rand = Math.floor( Math.random() * aArray.length + aArray.length );
var randArray = aArray[ rand - aArray.length ];
return randArray;
}

function nameoffunction(){
    //code in this function will be done after the window loads
    alert("random_array");
}

function alignarray(){
    var alignarray=['left','center','right'];
    var elem=document.getElementById('text-content');
    elem.style.textAlign=alignarray[Math.round(Math.random()*2)];
    nameoffunction();
}
</script>
</html>


问:
Loading socket.io into JavaScriptCore for iOS
I'm writing an iOS/JavaScriptCore app that calls code from a Javascript file. My Javascript code depends on the 'io' variable created by importing socket.io.js. The Javascript all works fine when loaded from an HTML file, but when I load socket.io.js into JavaScriptCore the io variable is not defined and my own Javascript can't run.

My JSCore code looks like this...

```<code>NSString *socketPath = [[NSBundle mainBundle] pathForResource:@"socket.io" ofType:@"js"];
NSString *socketJS = [NSString stringWithContentsOfFile:socketPath encoding:NSUTF8StringEncoding error:nil];
JSValue  *socketEval = [context evaluateScript: socketJS];

NSString *arPath = [[NSBundle mainBundle] pathForResource:@"arFunctions" ofType:@"js"];
NSString *arJS = [NSString stringWithContentsOfFile:arPath encoding:NSUTF8StringEncoding error:nil];
JSValue  *arEval = [context evaluateScript: arJS];

JSValue *function = context[@"connectToServer"];
JSValue *result = [function callWithArguments:nil];
</code>```

The exception handler defined for the context returns these errors when evaluateScript runs on the imported socket.io file...

    TypeError: undefined is not an object (evaluating 'Object.prototype')
    runInContext
    webpack_require
    webpack_require
    webpack_require
    webpackUniversalModuleDefinition

The connectToServer function fails because it expects the io variable to have been defined. anyone know why the io variable is not created in the context when I call evaluateScript on socket.io.js? It looks like socket.io is missing expected definitions or other resources when runInContext and webpackUniversalModuleDefinition is evaluated, but I'm loading the exact same Javascript files in the same order as in my HTML file. What am I missing here?

I'm developing on Xcode 9 on macOS High Sierra for iOS 11.

Thanks!

答:
I've come across possibly the same issue when migrating working JavaScriptCore code to High Sierra.

In my case the issue came from my unwitting reliance on -[NSFileManager enumeratorAtURL: includingPropertiesForKeys: options: errorHandler:] returning an enumerator that had sorted its contents based on the path of the urls. This used to be the case in macOS 10.12, but doesn't seem to be the case in 10.13, where the ordering seems to be decided by some unknown filesystem property.

Body:
I'm writing an iOS/JavaScriptCore app that calls code from a Javascript file. My Javascript code depends on the 'io' variable created by importing socket.io.js. The Javascript all works fine when loaded from an HTML file, but when I load socket.io.js into JavaScriptCore the io variable is not defined and my own Javascript can't run.

My JSCore code looks like this...

NSString *socketPath = [[NSBundle mainBundle] pathForResource:@"socket.io" ofType:@"js"];
NSString *socketJS = [NSString stringWithContentsOfFile:socketPath encoding:NSUTF8StringEncoding error:nil];
JSValue  *socketEval = [context evaluateScript: socketJS];

NSString *arPath = [[NSBundle mainBundle] pathForResource:@"arFunctions" ofType:@"js"];
NSString *arJS = [NSString stringWithContentsOfFile:arPath encoding:NSUTF8StringEncoding error:nil];
JSValue  *arEval = [context evaluateScript: arJS];

JSValue *function = context[@"connectToServer"];
JSValue *result = [function callWithArguments:nil];

The exception handler defined for the context returns these errors when evaluateScript runs on the imported socket.io file...

    TypeError: undefined is not an object (evaluating 'Object.prototype')
    runInContext
    webpack_require
    webpack_require
    webpack_require
    webpackUniversalModuleDefinition

The connectToServer function fails because it expects the io variable to have been defined. anyone know why the io variable is not created in the context when I call evaluateScript on socket.io.js? It looks like socket.io is missing expected definitions or other resources when runInContext and webpackUniversalModuleDefinition is evaluated, but I'm loading the exact same Javascript files in the same order as in my HTML file. What am I missing here?

I'm developing on Xcode 9 on macOS High Sierra for iOS 11.

Thanks!


问:
Python/Sklearn - IndexError - Index out of bounds
I'm trying to run a kNN classifier across my dataset using 10-fold CV. I have some experience with models in WEKA but struggling to transfer this over to Sklearn.

Below is my code

```<code>filename = 'train4.csv'
names = ['attribut names are here']
dataframe = read_csv(filename, names=names)
array = dataframe.values
X = array[:,0:47]
Y = array[:,47]
num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model, X, Y, cv=kfold)
print(results.mean())
</code>```

I get the error

```<code>>IndexError                                Traceback (most recent call last)
<ipython-input-19-8d9596c3368b> in <module>()
      4 array = dataframe.values
      5 X = array[:,0:47]
----> 6 Y = array[:,47]
      7 num_folds = 10
      8 kfold = KFold(n_splits=10, random_state=7)

> IndexError: index 47 is out of bounds for axis 1 with size 47
</code>```

In my CSV the 47th attribute is the target label - hence the 48 (am I wrong here?).

I am running pandas/sklearn in Jupyter notebook.

Thanks

答:
Try this:</p>

```<code>import pandas as pd

filename = 'train4.csv'
names = ['attribut names are here']
target_col_name = 'name_of_your_target_column'

df = pd.read_csv(filename, names=names)

num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model,
                          df.drop(target_col_name, axis=1),
                          df[target_col_name],
                          cv=kfold)
print(results.mean())
</code>```

Body:
I'm trying to run a kNN classifier across my dataset using 10-fold CV. I have some experience with models in WEKA but struggling to transfer this over to Sklearn.

Below is my code

filename = 'train4.csv'
names = ['attribut names are here']
dataframe = read_csv(filename, names=names)
array = dataframe.values
X = array[:,0:47]
Y = array[:,47]
num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model, X, Y, cv=kfold)
print(results.mean())

I get the error

>IndexError                                Traceback (most recent call last)
<ipython-input-19-8d9596c3368b> in <module>()
      4 array = dataframe.values
      5 X = array[:,0:47]
----> 6 Y = array[:,47]
      7 num_folds = 10
      8 kfold = KFold(n_splits=10, random_state=7)

> IndexError: index 47 is out of bounds for axis 1 with size 47

In my CSV the 47th attribute is the target label - hence the 48 (am I wrong here?).

I am running pandas/sklearn in Jupyter notebook.

Thanks

Body:
Try this:

import pandas as pd

filename = 'train4.csv'
names = ['attribut names are here']
target_col_name = 'name_of_your_target_column'

df = pd.read_csv(filename, names=names)

num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model,
                          df.drop(target_col_name, axis=1),
                          df[target_col_name],
                          cv=kfold)
print(results.mean())


问:
How to make a nested ordered list from array data
I have data like this:

```<code>var array = ["a", "b", "c", "d", "e"];
</code>```

I want this data converted like this:

```<code><ol>
 <li>a</li>
   <ol>
    <li>b</li>
     <ol>
      <li>c</li>
       <ol>
        <li>d</li>
       </ol>
     </ol>
  </ol>
</code>```

I will try this:

```<code>var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '<ol>';
    nested += '<li>' + el + '</li>';
    makeNestedList();
    nested += '</ol>';
  });
};
</code>```

But why is the result empty?

答:
You have number of problems in your code. You need to pass input array into function and return something from it. Then you don't need loop inside, since you are using recursion anyway.

Something like this I think will fix it:

var array = ["a", "b", "c", "d", "e"];

var makeNestedList = (arr) => {
  let nested = '
'
  nested += '
' + arr[0];
  if (arr.length > 1) {
    nested += makeNestedList(arr.slice(1));
  }
  nested += '

';
  return nested
};

document.body.innerHTML = makeNestedList(array)```

Body:
I have data like this:

var array = ["a", "b", "c", "d", "e"];

I want this data converted like this:

a

b

c

d

I will try this:

var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '
';
    nested += '
' + el + '
';
    makeNestedList();
    nested += '
';
  });
};

But why is the result empty?

Body:
You have number of problems in your code. You need to pass input array into function and return something from it. Then you don't need loop inside, since you are using recursion anyway.

Something like this I think will fix it:

var array = ["a", "b", "c", "d", "e"];

var makeNestedList = (arr) => {
  let nested = '<ol>'
  nested += '<li>' + arr[0];
  if (arr.length > 1) {
    nested += makeNestedList(arr.slice(1));
  }
  nested += '</li></ol>';
  return nested
};

document.body.innerHTML = makeNestedList(array)


问:
How do I do simple user input in python?
I'm just playing with input and variables. I'm trying to run a simple function:

```<code>slope = (y2-y1)/(x2-x1)
</code>```

I'd like to prompt the user to enter y2, y1, x2 and x1. What is the simplest, cleanest way to do this?

答:
This is the simplest way:

```<code> x1 = float(raw_input("Enter x1: "))
</code>```

Note that the raw_input() function returns a string, which is converted to a floating point number with float(). If you type something other than a number, you will get an exception:

```<code>>>> float(raw_input())
a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for float(): a
</code>```

If you're using Python 3 (it sounds like you are), use input instead of raw_input.

Body:
I'm just playing with input and variables. I'm trying to run a simple function:

slope = (y2-y1)/(x2-x1)

I'd like to prompt the user to enter y2, y1, x2 and x1. What is the simplest, cleanest way to do this?

Body:
This is the simplest way:

 x1 = float(raw_input("Enter x1: "))

Note that the raw_input() function returns a string, which is converted to a floating point number with float(). If you type something other than a number, you will get an exception:

>>> float(raw_input())
a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for float(): a

If you're using Python 3 (it sounds like you are), use input instead of raw_input.


问:
XmlDocument and the Formal Public Identifier
Why is my GetEntity function in my overloaded XmlResolver being passed the Formal Public Identifier when I load an xml file into an XmlDocument?  Is this a bug or am I supposed to deal with this some how?

edit: Here's some code.

Say for example I do this:

```<code>XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.XmlResolver = new MyXmlResolver();
myXmlDoc.Load("myxmlfile.xml");
</code>```

In MyXmlResolver I have the following code:

```<code>public override object GetEntity(Uri absUri, string role, Type typeToRet)
{
  if (typeToRet == null || typeToRet == typeof(Stream))
     return GetStream(absUri);
  else
     throw new XmlException("Unsupported class type: " + typeToRet);
}
</code>```

I get passed "file://path/to/xmldoc/-//W3C//DTD XHTML 1.1//EN", in absUri which doesn't make any sense to me.  Am I just supposed to ignore it?

答: I am using one to locally cache the dtd, mod files etc (see this question).  My problem with it doing what it does, is that the FPI it passes me isn't really an external reference, and I can't distinguish it from a real external reference.</p>

OwnerDisplayName: Sprintstar

Body:
Why is my GetEntity function in my overloaded XmlResolver being passed the Formal Public Identifier when I load an xml file into an XmlDocument?  Is this a bug or am I supposed to deal with this some how?

edit: Here's some code.

Say for example I do this:

XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.XmlResolver = new MyXmlResolver();
myXmlDoc.Load("myxmlfile.xml");

In MyXmlResolver I have the following code:

public override object GetEntity(Uri absUri, string role, Type typeToRet)
{
  if (typeToRet == null || typeToRet == typeof(Stream))
     return GetStream(absUri);
  else
     throw new XmlException("Unsupported class type: " + typeToRet);
}

I get passed "file://path/to/xmldoc/-//W3C//DTD XHTML 1.1//EN", in absUri which doesn't make any sense to me.  Am I just supposed to ignore it?

LastEditorDisplayName: Sprintstar


问:
Copy database from one server to another using c#
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

```<code>            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);
</code>```

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

```<code> Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);
</code>```

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User

答:
Could you possibly create a sql command object with the following command? </p>

```<code>BACKUP DATABASE DatabaseName
TO DISK = 'path\DatabaseName_Backup.bak'
WITH FORMAT, COPY_ONLY
</code>```

<p>and then restore using </p>

```<code>RESTORE DATABASE SomeDatabase
  FROM DISK = 'path\DatabaseName_Backup.bak'
  WITH FILE=1,
    NORECOVERY;
</code>```

Body:
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

 Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User

Body:
Could you possibly create a sql command object with the following command?

BACKUP DATABASE DatabaseName
TO DISK = 'path\DatabaseName_Backup.bak'
WITH FORMAT, COPY_ONLY

and then restore using

RESTORE DATABASE SomeDatabase
  FROM DISK = 'path\DatabaseName_Backup.bak'
  WITH FILE=1,
    NORECOVERY;


问:
How to determine the file extension of a file from a URL (Objective-C)
I have a URL of type: http://example.com/files/
And I need to determine what file is there (extension and name of file). Depending on extensions, I'll do something.
How can I determine it?</p>

答:
Try

```<code>NSString *ext = [[url lastPathComponent] pathExtension];
</code>```

See https://developer.apple.com/documentation/foundation/nsstring/1407801-pathextension

Body:
Try

NSString *ext = [[url lastPathComponent] pathExtension];

See https://developer.apple.com/documentation/foundation/nsstring/1407801-pathextension


问:
Optional parameters in python dict
Is there a way to include optional parameters into Python dictionary?

For example, I have the following return statements for get requests. They are dependent on the input and mostly identical.

If the region is passed as an input parameter, we have:

```<code>if region:
    return {
        'success': True,
        'result': {
            'country': country,
            'region': region, #  optional region param
            'cities': cities
        }
    }
</code>```

If the city is passed:

```<code>if city:
    return {
        'success': True,
        'result': {
            'country': country,
            'city': city, #  optional city param
            'cities': cities
        }
    }
</code>```

If nor city or region are passed:

```<code>return {
    'success': True,
    'result': {
        'country': country,
        'cities': cities
    }
}
</code>```

What I want is to have one return statement:

```<code>return {
    'success': True,
    'result': {
        'country': country,
        if region: 'region': region, #  I know this and the next lines don't work
        if city: 'city': city,
        'cities': cities
    }
}
</code>```

答:
Control statement is not allowed with dict literal, but it is trivial to do this:</p>

```<code>r = {
    'country': country,
    'cities': cities
}

if region:
    r['region'] = region
if city:
    r['city'] = city

return {
    'success': True,
    'result': r
}
</code>```

Title: Optional parameters in python dict

Body:
Is there a way to include optional parameters into Python dictionary?

For example, I have the following return statements for get requests. They are dependent on the input and mostly identical.

If the region is passed as an input parameter, we have:

if region:
    return {
        'success': True,
        'result': {
            'country': country,
            'region': region, #  optional region param
            'cities': cities
        }
    }

If the city is passed:

if city:
    return {
        'success': True,
        'result': {
            'country': country,
            'city': city, #  optional city param
            'cities': cities
        }
    }

If nor city or region are passed:

return {
    'success': True,
    'result': {
        'country': country,
        'cities': cities
    }
}

What I want is to have one return statement:

return {
    'success': True,
    'result': {
        'country': country,
        if region: 'region': region, #  I know this and the next lines don't work
        if city: 'city': city,
        'cities': cities
    }
}

Body:
Control statement is not allowed with dict literal, but it is trivial to do this:

r = {
    'country': country,
    'cities': cities
}

if region:
    r['region'] = region
if city:
    r['city'] = city

return {
    'success': True,
    'result': r
}


问:
Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)
I'm trying to make a mobile app that downloads info from the openweathermap.org apis.  For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA.  My code seems to work up to the point where I have to convert the input stream to a string variable.  When I do that, I get garbage.  Is there a particular way to do this seemingly simple task in a proper way?  Here is my code so far...</p>

```<code>      private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return null;
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        TextView test = (TextView) findViewById(R.id.test);
        if(result!=null) test.setText(result);
        else{
            Log.i(DEBUG_TAG, "returned result is null");}
    }
}

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.i(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();
        String text = getStringFromInputStream(is);
        //JSONObject json = new JSONObject(text);

        //try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
        //text = scanner.useDelimiter("\\A").next();
        //}

        //Bitmap bitmap = BitmapFactory.decodeStream(is);
        return text;
    }catch(Exception e) {
        Log.i(DEBUG_TAG, e.toString());
    }finally {
        if (is != null) {
            is.close();
        }
    }

    return null;
}

private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}
</code>```

答: Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.</p>

Body:
I'm trying to make a mobile app that downloads info from the openweathermap.org apis.  For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA.  My code seems to work up to the point where I have to convert the input stream to a string variable.  When I do that, I get garbage.  Is there a particular way to do this seemingly simple task in a proper way?  Here is my code so far...

      private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return null;
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        TextView test = (TextView) findViewById(R.id.test);
        if(result!=null) test.setText(result);
        else{
            Log.i(DEBUG_TAG, "returned result is null");}
    }
}

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.i(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();
        String text = getStringFromInputStream(is);
        //JSONObject json = new JSONObject(text);

        //try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
        //text = scanner.useDelimiter("\\A").next();
        //}

        //Bitmap bitmap = BitmapFactory.decodeStream(is);
        return text;
    }catch(Exception e) {
        Log.i(DEBUG_TAG, e.toString());
    }finally {
        if (is != null) {
            is.close();
        }
    }

    return null;
}

private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}


问:
Efficient method for building a promise object
At the moment what I have is this :

```<code>    getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
            .then(resp => {
                let promises = [];
                let data = resp.data.weeklychartlist.chart;
                for (let i = data.length - 4; i < data.length; i++) {
                    promises.push(
                        this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
                        .then(resp => {
                            return resp.data.weeklytrackchart.track.length;
                        })
                    );
                }

                return this.$q.all(promises);
            })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

But I'm thinking there may be a more functional approach to building this promise object, because a lot of code is getting repeated. So I tried to come up with a better solution:

```<code>    buildPromiseObj(target) {
     const methods = ['getinfo', 'gettopartists', 'getweeklychartlist'];
     let obj = {};
     for ( let method in methods ) {
        obj[`${methods[method]}`] = this.$http.get(this.buildUrl(`${target}.${methods[method]}`, target))
    }
}
</code>```

Does this approach make sense and should I use it ?

You can see that the 3rd request I make in the first function has other nested requests. Is there any way I can integrate that in the approach I've written above ?

答:
Yes, it's always a good idea to generalise like this. However:

Don't use for…in enumerations on arrays!

`${methods[method]}` is pointless use of template strings

your method/property names are inconsistent about capitalisation and prefix (user… vs get…)

Drop the pointless .then(resp => { return resp; })!

Your catch callback doesn't do anything. It should at least have returned the rejected promise - or simply thrown the error. Also you should not reject with strings.

Regarding the chart list, you can just append another then to the promise before calling all. Also you can greatly simplify the callback by using a more functional approach:

```<code>getData(user) {
    const methods = ['Info', 'TopArtists', 'WeeklyChartList'];
    let promises = {};
    for (let method of methods) {
        obj['user' + method] = this.$http.get(this.buildUrl('user.get'+method.toLowerCase(), target));
    }
    promises.userWeeklyChartList = promises.userWeeklyChartList.then(resp =>
         this.$q.all(resp.data.weeklychartlist.chart.slice(-4).map(val =>
             this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${val.from}&to=${val.to}`)
         ).then(resp =>
             resp.data.weeklytrackchart.track.length
         ))
    );
    return this.$q.all(promises).catch(err => {
        throw new Error(err.status);
    });
}
</code>```

Body:
At the moment what I have is this :

    getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
            .then(resp => {
                let promises = [];
                let data = resp.data.weeklychartlist.chart;
                for (let i = data.length - 4; i < data.length; i++) {
                    promises.push(
                        this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
                        .then(resp => {
                            return resp.data.weeklytrackchart.track.length;
                        })
                    );
                }

                return this.$q.all(promises);
            })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

But I'm thinking there may be a more functional approach to building this promise object, because a lot of code is getting repeated. So I tried to come up with a better solution:

    buildPromiseObj(target) {
     const methods = ['getinfo', 'gettopartists', 'getweeklychartlist'];
     let obj = {};
     for ( let method in methods ) {
        obj[`${methods[method]}`] = this.$http.get(this.buildUrl(`${target}.${methods[method]}`, target))
    }
}

Does this approach make sense and should I use it ?

You can see that the 3rd request I make in the first function has other nested requests. Is there any way I can integrate that in the approach I've written above ?

Body:
Yes, it's always a good idea to generalise like this. However:

Don't use for…in enumerations on arrays!

`${methods[method]}` is pointless use of template strings

your method/property names are inconsistent about capitalisation and prefix (user… vs get…)

Drop the pointless .then(resp => { return resp; })!

Your catch callback doesn't do anything. It should at least have returned the rejected promise - or simply thrown the error. Also you should not reject with strings.

Regarding the chart list, you can just append another then to the promise before calling all. Also you can greatly simplify the callback by using a more functional approach:

getData(user) {
    const methods = ['Info', 'TopArtists', 'WeeklyChartList'];
    let promises = {};
    for (let method of methods) {
        obj['user' + method] = this.$http.get(this.buildUrl('user.get'+method.toLowerCase(), target));
    }
    promises.userWeeklyChartList = promises.userWeeklyChartList.then(resp =>
         this.$q.all(resp.data.weeklychartlist.chart.slice(-4).map(val =>
             this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${val.from}&to=${val.to}`)
         ).then(resp =>
             resp.data.weeklytrackchart.track.length
         ))
    );
    return this.$q.all(promises).catch(err => {
        throw new Error(err.status);
    });
}


答:
You can use the input() function to prompt the user for input, and float to convert the user input from a string to a float:

```<code>x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))
</code>```

If you're using python 2, use raw_input() instead.

Title: How do I do simple user input in python?

Body:
You can use the input() function to prompt the user for input, and float to convert the user input from a string to a float:

x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))

If you're using python 2, use raw_input() instead.

ContentLicense: CC BY-SA 4.0


问:
Google analytics for multiple tenant tracking
I have a multi tenant setup using the same HTML but different web urls
eg. tenant1.company.com , tenant2.company.com
since both use the same htmls the analytics code is same. How do i set up different codes for different tenants to get different data in GA</p>

答:
Unless you intend to analytics between the two tenants you should be using a different web property id for each one.   There is really no reason to be storing the data in the same Google Analytics account.

Its just a simple matter of changing the javascript snippet on each site.


问:
Getting the count of 2 fields in a collection using Mongodb

I have a collection called ActivityCollection. There are many fields
  in it but I want to get only two fields name Acitivity and
  Tags of all activities. I also want to calculate the total
  number of counts of each Activity and Tag. For more clear
  understanding see this image given below

.Click this link to view the image.

答:
Assuming following data model in your ActivityCollection:

```<code>{
    "_id" : ObjectId("5a0c4894e465dc895af90d2c"),
    "activity" : "Phone Call",
    "tag" : "Addiction"
}
{
    "_id" : ObjectId("5a0c48a2e465dc895af90d2d"),
    "activity" : "Phone Call",
    "tag" : "Family Issue"
}
{
    "_id" : ObjectId("5a0c48aee465dc895af90d2e"),
    "activity" : "Email",
    "tag" : "Family Issue"
}
{
    "_id" : ObjectId("5a0c48b9e465dc895af90d2f"),
    "activity" : "Email",
    "tag" : "Depression"
}
</code>```

Following aggregate jobs will return the data required for your dashboard:

For count based on activity:

```<code>db.ActivityCollection.aggregate([{$group:{_id:"$activity", count:{$sum:1}}}])
</code>```

For count based on tag:

```<code> db.ActivityCollection.aggregate([{$group:{_id:"$tag", count:{$sum:1}}}])
</code>```

The following will result respectively:

For activity based:

```<code>{ "_id" : "Email", "count" : 2 }
{ "_id" : "Phone Call", "count" : 2 }
</code>```

For tag based:

```<code>{ "_id" : "Depression", "count" : 1 }
{ "_id" : "Family Issue", "count" : 2 }
{ "_id" : "Addiction", "count" : 1 }
</code>```

Body:
Assuming following data model in your ActivityCollection:

{
    "_id" : ObjectId("5a0c4894e465dc895af90d2c"),
    "activity" : "Phone Call",
    "tag" : "Addiction"
}
{
    "_id" : ObjectId("5a0c48a2e465dc895af90d2d"),
    "activity" : "Phone Call",
    "tag" : "Family Issue"
}
{
    "_id" : ObjectId("5a0c48aee465dc895af90d2e"),
    "activity" : "Email",
    "tag" : "Family Issue"
}
{
    "_id" : ObjectId("5a0c48b9e465dc895af90d2f"),
    "activity" : "Email",
    "tag" : "Depression"
}

Following aggregate jobs will return the data required for your dashboard:

For count based on activity:

db.ActivityCollection.aggregate([{$group:{_id:"$activity", count:{$sum:1}}}])

For count based on tag:

 db.ActivityCollection.aggregate([{$group:{_id:"$tag", count:{$sum:1}}}])

The following will result respectively:

For activity based:

{ "_id" : "Email", "count" : 2 }
{ "_id" : "Phone Call", "count" : 2 }

For tag based:

{ "_id" : "Depression", "count" : 1 }
{ "_id" : "Family Issue", "count" : 2 }
{ "_id" : "Addiction", "count" : 1 }


问:
Hide Feign client endpoints in Swagger
I am using Springboot autoconfiguration, and currently all my Feign endpoints are exposed in swagger-ui. How can I disable this feature?</p>

答:
You can set this in your application.properties as:

```<code>endpoints.enabled=false
endpoints.health.enabled=true
endpoints.loggers.enabled=true
</code>```

In your case it will be something like

```<code>endpoints.feign.***=true
</code>```

But this is not disabling for swagger but endpoints exposure themselves. For Swagger you have to markup them explicitly with @Api#hidden() for example.

Title: Hide Feign client endpoints in Swagger

Body:
You can set this in your application.properties as:

endpoints.enabled=false
endpoints.health.enabled=true
endpoints.loggers.enabled=true

In your case it will be something like

endpoints.feign.***=true

But this is not disabling for swagger but endpoints exposure themselves. For Swagger you have to markup them explicitly with @Api#hidden() for example.


问:
How to use DigestInputStream to calculate MD5 sum when using FileChannel?
I'm doing multiple parallel HTTP range requests and want to calculate the MD5 sum of each response using DigestInputStream. I also want to write the data from the HTTP stream to a file without creating intermediate files. Therefore I'm using FileChannel and access regions of a file. This is basically a Download Manager application.

Saving the HTTP Stream to the file is working, but if I try to use the DigestInputStream to calculate the MD5 sum on the fly, it seems the DigestInputStream is never read. I'm probably missing some important part of how FileChannel uses the InputStream and I hope this can be easily fixed.

I'd also be glad for suggestions for optimizations to achieve the goal outlined above.

Here's the class implementing the download tasks

```<code>private class MultiHttpClientConnThread extends Thread {
    private final Logger logger = Logger.getLogger(getClass());
    private final CloseableHttpClient client;
    private final HttpGet get;
    private final String md5sum;
    private File destinationFile;

    public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final File destinationFile) {
        this.client = client;
        this.get = get;
        this.destinationFile = destinationFile;
    }

    @Override
    public final void run() {
        try {
            logger.debug("Thread Running: " + getName());

            CloseableHttpResponse response = client.execute(get);

            String contentRange = response.getFirstHeader("Content-Range").getValue();
            Long startByte = Long.parseLong(contentRange.split("[ -]")[1]);

            Long length = response.getEntity().getContentLength();

            InputStream inputStream = response.getEntity().getContent();

            ReadableByteChannel readableByteChannel;

            MessageDigest messageDigest = MessageDigest.getInstance("MD5");

            DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
            readableByteChannel = Channels.newChannel(digestInputStream);

            RandomAccessFile randomAccessFile = new RandomAccessFile(destinationFile, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();

            fileChannel.transferFrom(readableByteChannel, startByte, length);

            md5sum = Hex.encodeHexString(messageDigest.digest());
            logger.info("Part MD5 sum: " + md5sum);

            logger.debug("Thread Finished: " + getName());

            response.close();
            fileChannel.close();
            randomAccessFile.close();
        } catch (final ClientProtocolException ex) {
            logger.error("", ex);
        } catch (final IOException ex) {
            logger.error("", ex);
        } catch (final NoSuchAlgorithmException ex) {
            logger.error("", ex);
        }
    }
}
</code>```

Update

This is a bit embarassing as the code seems to be working fine. The problem was with the uploaded file I used for testing. As asked in How to create a repeatable incompressible fast InputStream in Java? I required a repeatable random input stream and I used the one from here which unfortunately seems to repeat itself. Therefore all threads had the same data and were providing the same MD5 sums and the MD5 sums were looking very similar (but not identical) to an empty file.

答:
In the method "transferFrom", the second argument is the position where to start writing in the destination. If this is a new file, try setting it to zero instead of using the variable "startByte" (which is where to start reading from the source).

transferFrom

Body:
I'm doing multiple parallel HTTP range requests and want to calculate the MD5 sum of each response using DigestInputStream. I also want to write the data from the HTTP stream to a file without creating intermediate files. Therefore I'm using FileChannel and access regions of a file. This is basically a Download Manager application.

Saving the HTTP Stream to the file is working, but if I try to use the DigestInputStream to calculate the MD5 sum on the fly, it seems the DigestInputStream is never read. I'm probably missing some important part of how FileChannel uses the InputStream and I hope this can be easily fixed.

I'd also be glad for suggestions for optimizations to achieve the goal outlined above.

Here's the class implementing the download tasks

private class MultiHttpClientConnThread extends Thread {
    private final Logger logger = Logger.getLogger(getClass());
    private final CloseableHttpClient client;
    private final HttpGet get;
    private final String md5sum;
    private File destinationFile;

    public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final File destinationFile) {
        this.client = client;
        this.get = get;
        this.destinationFile = destinationFile;
    }

    @Override
    public final void run() {
        try {
            logger.debug("Thread Running: " + getName());

            CloseableHttpResponse response = client.execute(get);

            String contentRange = response.getFirstHeader("Content-Range").getValue();
            Long startByte = Long.parseLong(contentRange.split("[ -]")[1]);

            Long length = response.getEntity().getContentLength();

            InputStream inputStream = response.getEntity().getContent();

            ReadableByteChannel readableByteChannel;

            MessageDigest messageDigest = MessageDigest.getInstance("MD5");

            DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
            readableByteChannel = Channels.newChannel(digestInputStream);

            RandomAccessFile randomAccessFile = new RandomAccessFile(destinationFile, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();

            fileChannel.transferFrom(readableByteChannel, startByte, length);

            md5sum = Hex.encodeHexString(messageDigest.digest());
            logger.info("Part MD5 sum: " + md5sum);

            logger.debug("Thread Finished: " + getName());

            response.close();
            fileChannel.close();
            randomAccessFile.close();
        } catch (final ClientProtocolException ex) {
            logger.error("", ex);
        } catch (final IOException ex) {
            logger.error("", ex);
        } catch (final NoSuchAlgorithmException ex) {
            logger.error("", ex);
        }
    }
}

Update

This is a bit embarassing as the code seems to be working fine. The problem was with the uploaded file I used for testing. As asked in How to create a repeatable incompressible fast InputStream in Java? I required a repeatable random input stream and I used the one from here which unfortunately seems to repeat itself. Therefore all threads had the same data and were providing the same MD5 sums and the MD5 sums were looking very similar (but not identical) to an empty file.


问:
Nested class has unstable name. Fix with @objc with strange param
We have some code where a class is nested in an extension. After opening the project in Xcode 9, we get the 'Nested class has unstable name' warning.
When using Xcode auto-fix, it generate an @objc with some (generated?) param.

For example:

```<code>struct Something {
}

extension Something {

    @objc(_TtCV16MyProject9Something4Some) class Some: NSObject, NSCoding {

        required init?(coder aDecoder: NSCoder) {

        }

        func encode(with aCoder: NSCoder) {

        }

    }
}
</code>```

All this compiles. But what the heck is this _TtCV16MyProject9Something4Some?

It seems to be unique because if we use the same one in two places, it will not compile (some generic project level compiler error).

If I replace the _TtCV16MyProject9Something4Some with anything else (say @objc(Something)), the project compiles fine, but that does not shad any more light really.

One important question, is the param randomly generated or is it an actual link to a real bridging name?

答:
I think your class' name might contain a character not supported by Objective-C. In those cases, you can use the @objc(name) attribute to provide an alternative name to use in Objective-C, and what you are seeing is an autogenerated unique name. This is also why you can change that with anything you like and it will compile just fine.

There's a section in Apple's docs explaining this, Configuring Swift Interfaces in Objective-C in https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-ID55

Body:
We have some code where a class is nested in an extension. After opening the project in Xcode 9, we get the 'Nested class has unstable name' warning.
When using Xcode auto-fix, it generate an @objc with some (generated?) param.

For example:

struct Something {
}

extension Something {

    @objc(_TtCV16MyProject9Something4Some) class Some: NSObject, NSCoding {

        required init?(coder aDecoder: NSCoder) {

        }

        func encode(with aCoder: NSCoder) {

        }

    }
}

All this compiles. But what the heck is this _TtCV16MyProject9Something4Some?

It seems to be unique because if we use the same one in two places, it will not compile (some generic project level compiler error).

If I replace the _TtCV16MyProject9Something4Some with anything else (say @objc(Something)), the project compiles fine, but that does not shad any more light really.

One important question, is the param randomly generated or is it an actual link to a real bridging name?


问:
How do I use flow type to constrain the return value of this function?
I want to say "mySelector returns a string". Can I do this with Flowtype?

```<code>import { createSelector } from 'reselect';

const mySelector = createSelector([anotherSelector], () => 'foo');
</code>```

答:
If you have not already done so, it might be helpful to get type definitions for reselect into your project. You can fetch type definitions for your npm depenencies automatically using flow-typed. (Reselect does ship with Typescript type definitions, and Flow may be able to read Typescript definitions in the future; but AFAIK Flow cannot read Typescript definitions at this time.)

Whether or not Flow correctly infers the type for mySelector, it may be useful to explicitly state the type that you expect. You can do that by putting a type annotation on const declaration:

const mySelector: () => string = createSelector([anotherSelector], () => 'foo');
```

Explicit annotations like that can help to make sure that you are on the same page with the type checker. Flow will enforce the signature that you specify when you reference mySelector, unless Flow infers a contradictory type for mySelector in which case it will report an error.

Body:
I want to say "mySelector returns a string". Can I do this with Flowtype?

import { createSelector } from 'reselect';

const mySelector = createSelector([anotherSelector], () => 'foo');

Body:
If you have not already done so, it might be helpful to get type definitions for reselect into your project. You can fetch type definitions for your npm depenencies automatically using flow-typed. (Reselect does ship with Typescript type definitions, and Flow may be able to read Typescript definitions in the future; but AFAIK Flow cannot read Typescript definitions at this time.)

Whether or not Flow correctly infers the type for mySelector, it may be useful to explicitly state the type that you expect. You can do that by putting a type annotation on const declaration:

const mySelector: () => string = createSelector([anotherSelector], () => 'foo');

Explicit annotations like that can help to make sure that you are on the same page with the type checker. Flow will enforce the signature that you specify when you reference mySelector, unless Flow infers a contradictory type for mySelector in which case it will report an error.