答:
tldr;

Your time series data resemble (mean-shifted) white noise; data do not support any evidence of an underlying auto-regressive (AR) or moving average (MA) process. As such an ARIMA(0,0,0) model (with a non-zero mean) is consistent with your data.

Data visualisation

Prior to fitting (S)ARIMA models, it is always instructive to take a look at the raw data.

import matplotlib.pyplot as plt
import matplotlib.dates as dates

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(data.Date, data.Births)
ax.xaxis.set_major_locator(dates.DayLocator(interval = 10))
ax.xaxis.set_major_formatter(dates.DateFormatter('%d/%m'))
ax.set_xlabel('DD/MM in 1959')
ax.set_ylabel("Births")
plt.show()
```

<p><img src="https://i.stack.imgur.com/F8n7R.png" alt="enter image description here"></p>

<p>Already here we see that data more-or-less resemble white noise. </p>

<h2>Auto-correlation and partial auto-correlation functions</h2>

<p>We can explore this further, by plotting the ACF and PACF</p>

<pre class="lang-py prettyprint-override"><code>from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
plt.figure()
plt.subplot(211)
plot_acf(data["Births"], ax = plt.gca())
plt.subplot(212)
plot_pacf(data["Births"], ax = plt.gca())
plt.show()
</code>```

There is no significant (partial) auto-correlation at lags < 10; the few significant spikes at higher lags in the PACF may be as expected (since we're plotting 95% CIs), or could be due to some other time series "abnormality". IMO, given the sparsity of the data, there is just not enough information to say much more.

Auto ARIMA

Let's re-run auto_arima:

from pmdarima import auto_arima
auto_arima(
    data["Births"],
    start_p = 1, max_p = 6,
    start_q = 1, max_q = 6,
    seasonal = False, trace = True).summary()
#Performing stepwise search to minimize aic
#/Users/maurits/miniconda3/lib/python3.5/site-packages/statsmodels/base/model.py:568: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
#  "Check mle_retvals", ConvergenceWarning)
#Fit ARIMA: (1, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=422.260, BIC=430.637, Time=0.255 seconds
#Fit ARIMA: (0, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=419.527, BIC=423.716, Time=0.010 seconds
#Fit ARIMA: (1, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=421.148, BIC=427.431, Time=0.040 seconds
#Fit ARIMA: (0, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=421.238, BIC=427.521, Time=0.058 seconds
#Fit ARIMA: (0, 0, 0)x(0, 0, 0, 0) (constant=False); AIC=616.939, BIC=619.034, Time=0.010 seconds
#Total fit time: 0.383 seconds
#<class 'statsmodels.iolib.summary.Summary'>
#"""
#                               SARIMAX Results
#==============================================================================
#Dep. Variable:                      y   No. Observations:                   60
#Model:                        SARIMAX   Log Likelihood                -207.764
#Date:                Wed, 19 Feb 2020   AIC                            419.527
#Time:                        20:20:11   BIC                            423.716
#Sample:                             0   HQIC                           421.166
#                                 - 60
#Covariance Type:                  opg
#==============================================================================
#                 coef    std err          z      P>|z|      [0.025      0.975]
#------------------------------------------------------------------------------
#intercept     39.9333      0.997     40.068      0.000      37.980      41.887
#sigma2        59.5956     13.897      4.288      0.000      32.358      86.833
#===================================================================================
#Ljung-Box (Q):                       51.46   Jarque-Bera (JB):                 1.50
#Prob(Q):                              0.11   Prob(JB):                         0.47
#Heteroskedasticity (H):               0.80   Skew:                            -0.01
#Prob(H) (two-sided):                  0.63   Kurtosis:                         2.23
#===================================================================================
#
#Warnings:
#[1] Covariance matrix calculated using the outer product of gradients (complex-step).
#"""
```

<p>The best model is that of a mean-shifted white-noise model (the shift in mean is given by the <code>intercept</code> parameter).</p>

<hr>

<h2>Sample data</h2>

<pre class="lang-py prettyprint-override"><code>import pandas as pd

data = pd.DataFrame({
    "Date": ["1959-01-01", "1959-01-02", "1959-01-03",
"1959-01-04", "1959-01-05", "1959-01-06", "1959-01-07", "1959-01-08",
"1959-01-09", "1959-01-10", "1959-01-11", "1959-01-12", "1959-01-13",
"1959-01-14", "1959-01-15", "1959-01-16", "1959-01-17", "1959-01-18",
"1959-01-19", "1959-01-20", "1959-01-21", "1959-01-22", "1959-01-23",
"1959-01-24", "1959-01-25", "1959-01-26", "1959-01-27", "1959-01-28",
"1959-01-29", "1959-01-30", "1959-01-31", "1959-02-01", "1959-02-02",
"1959-02-03", "1959-02-04", "1959-02-05", "1959-02-06", "1959-02-07",
"1959-02-08", "1959-02-09", "1959-02-10", "1959-02-11", "1959-02-12",
"1959-02-13", "1959-02-14", "1959-02-15", "1959-02-16", "1959-02-17",
"1959-02-18", "1959-02-19", "1959-02-20", "1959-02-21", "1959-02-22",
"1959-02-23", "1959-02-24", "1959-02-25", "1959-02-26", "1959-02-27",
"1959-02-28", "1959-03-01"],
    "Births": [35, 32, 30, 31, 44, 29, 45, 43, 38, 27, 38, 33, 55, 47, 45,
37, 50, 43, 41, 52, 34, 53, 39, 32, 37, 43, 39, 35, 44, 38, 24,
23, 31, 44, 38, 50, 38, 51, 31, 31, 51, 36, 45, 51, 34, 52, 47,
45, 46, 39, 48, 37, 35, 52, 42, 45, 39, 37, 30, 35]
})
data["Date"] = pd.to_datetime(data["Date"])
</code>```

Title: auto_arima() returning best value of (p,d,q) as (0,0,0)

Body:
I have a Daily frequency time series dataset.

Dataset:

           Births
Date
1959-01-01  35
1959-01-02  32
1959-01-03  30
1959-01-04  31
1959-01-05  44
1959-01-06  29
1959-01-07  45
1959-01-08  43
1959-01-09  38
1959-01-10  27
1959-01-11  38
1959-01-12  33
1959-01-13  55
1959-01-14  47
1959-01-15  45
1959-01-16  37
1959-01-17  50
1959-01-18  43
1959-01-19  41
1959-01-20  52
1959-01-21  34
1959-01-22  53
1959-01-23  39
1959-01-24  32
1959-01-25  37
1959-01-26  43
1959-01-27  39
1959-01-28  35
1959-01-29  44
1959-01-30  38
1959-01-31  24
1959-02-01  23
1959-02-02  31
1959-02-03  44
1959-02-04  38
1959-02-05  50
1959-02-06  38
1959-02-07  51
1959-02-08  31
1959-02-09  31
1959-02-10  51
1959-02-11  36
1959-02-12  45
1959-02-13  51
1959-02-14  34
1959-02-15  52
1959-02-16  47
1959-02-17  45
1959-02-18  46
1959-02-19  39
1959-02-20  48
1959-02-21  37
1959-02-22  35
1959-02-23  52
1959-02-24  42
1959-02-25  45
1959-02-26  39
1959-02-27  37
1959-02-28  30
1959-03-01  35

For Stationarity, I checked using Augmented Dickey-fuller test, it turned out to be Stationary.

I wanted to apply ARMA model on it, given that my seasonal component was absent and data is stationary.
To get best value of (p,q) I used:

from pmdarima import auto_arima
auto_arima(df1['Births'],start_p=1,max_p=6, start_q=1, max_q=6, seasonal=False, trace = True).summary()

It returned me:

Fit ARIMA: (0, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=419.527, BIC=423.716, Time=0.032 seconds
Fit ARIMA: (0, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=421.238, BIC=427.521, Time=0.082 seconds
Fit ARIMA: (0, 0, 2)x(0, 0, 0, 0) (constant=True); AIC=421.309, BIC=429.687, Time=0.095 seconds
Fit ARIMA: (0, 0, 3)x(0, 0, 0, 0) (constant=True); AIC=422.696, BIC=433.168, Time=0.135 seconds
Fit ARIMA: (0, 0, 4)x(0, 0, 0, 0) (constant=True); AIC=424.376, BIC=436.942, Time=0.185 seconds
Fit ARIMA: (0, 0, 5)x(0, 0, 0, 0) (constant=True); AIC=426.365, BIC=441.026, Time=0.258 seconds
Fit ARIMA: (1, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=421.148, BIC=427.431, Time=0.016 seconds
Fit ARIMA: (1, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=422.261, BIC=430.639, Time=0.244 seconds
Fit ARIMA: (1, 0, 2)x(0, 0, 0, 0) (constant=True); AIC=423.047, BIC=433.519, Time=0.282 seconds
Fit ARIMA: (1, 0, 3)x(0, 0, 0, 0) (constant=True); AIC=424.396, BIC=436.962, Time=0.427 seconds
Fit ARIMA: (1, 0, 4)x(0, 0, 0, 0) (constant=True); AIC=426.380, BIC=441.041, Time=0.228 seconds
Fit ARIMA: (2, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=421.586, BIC=429.963, Time=0.144 seconds
Fit ARIMA: (2, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=423.493, BIC=433.965, Time=0.226 seconds
Fit ARIMA: (2, 0, 2)x(0, 0, 0, 0) (constant=True); AIC=422.342, BIC=434.908, Time=0.469 seconds
Fit ARIMA: (2, 0, 3)x(0, 0, 0, 0) (constant=True); AIC=422.484, BIC=437.144, Time=0.517 seconds
Fit ARIMA: (3, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=423.349, BIC=433.821, Time=0.232 seconds
Fit ARIMA: (3, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=424.792, BIC=437.358, Time=0.438 seconds
Fit ARIMA: (3, 0, 2)x(0, 0, 0, 0) (constant=True); AIC=422.814, BIC=437.475, Time=0.518 seconds
Fit ARIMA: (4, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=424.320, BIC=436.886, Time=0.356 seconds
Fit ARIMA: (4, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=426.278, BIC=440.938, Time=0.347 seconds
Fit ARIMA: (5, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=426.249, BIC=440.909, Time=0.574 seconds
Total fit time: 5.839 seconds

SARIMAX Results
Dep. Variable:  y   No. Observations:   60
Model:  SARIMAX     Log Likelihood  -207.764
Date:   Wed, 19 Feb 2020    AIC 419.527
Time:   12:06:46            BIC 423.716
Sample: 0                   HQIC 421.166
        - 60
Covariance Type:    opg
              coef  std err    z    P>|z|   [0.025  0.975]
intercept   39.9333 0.997   40.068  0.000   37.980  41.887
sigma2      59.5956 13.897  4.288   0.000   32.358  86.833
Ljung-Box(Q):51.46              Jarque-Bera (JB):   1.50
Prob(Q):    0.11                Prob(JB):   0.47
Heteroskedasticity (H): 0.80    Skew:   -0.01
Prob(H) (two-sided):    0.63    Kurtosis:   2.23

The result having lowest AIC score is SARIMAX(0,0,0).

d=0, is understandable that differencing is not required.
But, with p,q also 0, what does that technically signify? Is it okay to have p and q as 0?
Please let me know if anything is unclear.

Body:
tldr;

Your time series data resemble (mean-shifted) white noise; data do not support any evidence of an underlying auto-regressive (AR) or moving average (MA) process. As such an ARIMA(0,0,0) model (with a non-zero mean) is consistent with your data.

Data visualisation

Prior to fitting (S)ARIMA models, it is always instructive to take a look at the raw data.

import matplotlib.pyplot as plt
import matplotlib.dates as dates

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(data.Date, data.Births)
ax.xaxis.set_major_locator(dates.DayLocator(interval = 10))
ax.xaxis.set_major_formatter(dates.DateFormatter('%d/%m'))
ax.set_xlabel('DD/MM in 1959')
ax.set_ylabel("Births")
plt.show()

Already here we see that data more-or-less resemble white noise.

Auto-correlation and partial auto-correlation functions

We can explore this further, by plotting the ACF and PACF

from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
plt.figure()
plt.subplot(211)
plot_acf(data["Births"], ax = plt.gca())
plt.subplot(212)
plot_pacf(data["Births"], ax = plt.gca())
plt.show()

There is no significant (partial) auto-correlation at lags < 10; the few significant spikes at higher lags in the PACF may be as expected (since we're plotting 95% CIs), or could be due to some other time series "abnormality". IMO, given the sparsity of the data, there is just not enough information to say much more.

Auto ARIMA

Let's re-run auto_arima:

from pmdarima import auto_arima
auto_arima(
    data["Births"],
    start_p = 1, max_p = 6,
    start_q = 1, max_q = 6,
    seasonal = False, trace = True).summary()
#Performing stepwise search to minimize aic
#/Users/maurits/miniconda3/lib/python3.5/site-packages/statsmodels/base/model.py:568: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
#  "Check mle_retvals", ConvergenceWarning)
#Fit ARIMA: (1, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=422.260, BIC=430.637, Time=0.255 seconds
#Fit ARIMA: (0, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=419.527, BIC=423.716, Time=0.010 seconds
#Fit ARIMA: (1, 0, 0)x(0, 0, 0, 0) (constant=True); AIC=421.148, BIC=427.431, Time=0.040 seconds
#Fit ARIMA: (0, 0, 1)x(0, 0, 0, 0) (constant=True); AIC=421.238, BIC=427.521, Time=0.058 seconds
#Fit ARIMA: (0, 0, 0)x(0, 0, 0, 0) (constant=False); AIC=616.939, BIC=619.034, Time=0.010 seconds
#Total fit time: 0.383 seconds
#<class 'statsmodels.iolib.summary.Summary'>
#"""
#                               SARIMAX Results
#==============================================================================
#Dep. Variable:                      y   No. Observations:                   60
#Model:                        SARIMAX   Log Likelihood                -207.764
#Date:                Wed, 19 Feb 2020   AIC                            419.527
#Time:                        20:20:11   BIC                            423.716
#Sample:                             0   HQIC                           421.166
#                                 - 60
#Covariance Type:                  opg
#==============================================================================
#                 coef    std err          z      P>|z|      [0.025      0.975]
#------------------------------------------------------------------------------
#intercept     39.9333      0.997     40.068      0.000      37.980      41.887
#sigma2        59.5956     13.897      4.288      0.000      32.358      86.833
#===================================================================================
#Ljung-Box (Q):                       51.46   Jarque-Bera (JB):                 1.50
#Prob(Q):                              0.11   Prob(JB):                         0.47
#Heteroskedasticity (H):               0.80   Skew:                            -0.01
#Prob(H) (two-sided):                  0.63   Kurtosis:                         2.23
#===================================================================================
#
#Warnings:
#[1] Covariance matrix calculated using the outer product of gradients (complex-step).
#"""

The best model is that of a mean-shifted white-noise model (the shift in mean is given by the intercept parameter).

Sample data

import pandas as pd

data = pd.DataFrame({
    "Date": ["1959-01-01", "1959-01-02", "1959-01-03",
"1959-01-04", "1959-01-05", "1959-01-06", "1959-01-07", "1959-01-08",
"1959-01-09", "1959-01-10", "1959-01-11", "1959-01-12", "1959-01-13",
"1959-01-14", "1959-01-15", "1959-01-16", "1959-01-17", "1959-01-18",
"1959-01-19", "1959-01-20", "1959-01-21", "1959-01-22", "1959-01-23",
"1959-01-24", "1959-01-25", "1959-01-26", "1959-01-27", "1959-01-28",
"1959-01-29", "1959-01-30", "1959-01-31", "1959-02-01", "1959-02-02",
"1959-02-03", "1959-02-04", "1959-02-05", "1959-02-06", "1959-02-07",
"1959-02-08", "1959-02-09", "1959-02-10", "1959-02-11", "1959-02-12",
"1959-02-13", "1959-02-14", "1959-02-15", "1959-02-16", "1959-02-17",
"1959-02-18", "1959-02-19", "1959-02-20", "1959-02-21", "1959-02-22",
"1959-02-23", "1959-02-24", "1959-02-25", "1959-02-26", "1959-02-27",
"1959-02-28", "1959-03-01"],
    "Births": [35, 32, 30, 31, 44, 29, 45, 43, 38, 27, 38, 33, 55, 47, 45,
37, 50, 43, 41, 52, 34, 53, 39, 32, 37, 43, 39, 35, 44, 38, 24,
23, 31, 44, 38, 50, 38, 51, 31, 31, 51, 36, 45, 51, 34, 52, 47,
45, 46, 39, 48, 37, 35, 52, 42, 45, 39, 37, 30, 35]
})
data["Date"] = pd.to_datetime(data["Date"])


来源: stackexchange

问:
How to add a label component in google app script
I am trying to develop an add on for google calendar  using google app script
I am totally new to google app script
I am unable to find how to set a label component in gas
I just need to add a label as a title of the division </p>

答:
If you want to set the title of a text input you can just use .setTitle(), like this:

```<code>var textInput = CardService.newTextInput()
    .setFieldName("text_input_form_input_key")
    .setTitle("The title of the text input");
</code>```

Moreover, you can check this link since it might be of help to you:

Card Service Class Apps Script

ContentLicense: CC BY-SA 4.0

Body:
If you want to set the title of a text input you can just use .setTitle(), like this:

var textInput = CardService.newTextInput()
    .setFieldName("text_input_form_input_key")
    .setTitle("The title of the text input");

Moreover, you can check this link since it might be of help to you:

Card Service Class Apps Script


问:
Character references (Entities) to UTF Characters
I am facing a character reference problem. My CKEditor converts the special characters to corresponding Entities (in CKEditor I can't change the settings.) And this looks like as under.

```<code>"Ö" => "Ö"
"ö" => "ö"
"Ä" => "Ä"
"ä" => "ä"
"Ü" => "Ü"
"ü" => "ü"
</code>```

Now In my Java, PHP or Coldfusion script I want again to replace all the Entities with special characters.
Is there any method available for such replacements?

答:
For Java, the Apache Commons StringEscapeUtils.unescapeHTML(String) method understands all standard entity attributes in a number of versions of HTML, including the numeric ones.

By the way, this has nothing to do with UTF-8.  What you will get will be a Java String which contains a modified form of UTF-16.

ContentLicense: CC BY-SA 3.0

Body:
I am facing a character reference problem. My CKEditor converts the special characters to corresponding Entities (in CKEditor I can't change the settings.) And this looks like as under.

"Ö" => "Ö"
"ö" => "ö"
"Ä" => "Ä"
"ä" => "ä"
"Ü" => "Ü"
"ü" => "ü"

Now In my Java, PHP or Coldfusion script I want again to replace all the Entities with special characters.
Is there any method available for such replacements?


问:
Reset offset, onTapGesture works, but onRotated does not work, why?
I want the view containing 2 rectangles floating in the bottom of the screen, whatever the orientation is portrait or landscape.

code is a test, when orientationDidChangeNotification happened, I Found UIDevice.current.orientation.isPortrait and UIScreen.main.bounds.height often have wrong value, why?

Anyway, test code is just reset offset = 0 in onRotated(). but it doesn't work; otherwise onTapGesture works fine.

Q1: Is it a wrong way for SwiftUI? SceneDelegate.orientationDidChangeNotification -> contentView.onRotated()?

Q2: why do UIDevice.current.orientation.isPortrait and UIScreen.main.bounds.height often have wrong value?

Q3: How to let a view float at the bottom of screen in both portrait and landscape?

```<code>let height: CGFloat = 100

struct TestView: View {
    @State var offset = (UIScreen.main.bounds.height - height) / 2

    var body: some View {
        ZStack {
            Text("+")
            VStack(spacing: 0) {
                Rectangle().fill(Color.blue)
                Rectangle().fill(Color.red)
            }
            .frame(width: 100, height: height)
            .offset(y: offset)
            .onTapGesture {
                self.offset = 0
            }
        }
    }

    func onRotated() {
//        let isPortrait =  UIDevice.current.orientation.isPortrait
        offset = 0//(UIScreen.main.bounds.height - height) / 2
//        print("\(isPortrait), screen height = \(UIScreen.main.bounds.height)")
    }
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = TestView()
        if let windowScene = scene as? UIWindowScene {
            NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { notification in
                contentView.onRotated()
            }

            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
    ...
}
</code>```

答:
contentView is not a reference, it is a value, so you call .onRotated on own copy of contentView value that lives only within callback

```<code>    let contentView = TestView()
    if let windowScene = scene as? UIWindowScene {
        NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { notification in
            contentView.onRotated() // local copy!!!
        }
</code>```

instead create listener for notification publisher inside TestView, so it can change self internally.

Moreover, it is not clear the intention but SwiftUI gives possibility to track size classes via EnvironmentValues.horizontalSizeClass and EnvironmentValues.verticalSizeClass which are automatically changed on device orientation, so it is possible to make your view layout depending on those environment values even w/o notification.

See here good example on how to use size classes

Body:
I want the view containing 2 rectangles floating in the bottom of the screen, whatever the orientation is portrait or landscape.

code is a test, when orientationDidChangeNotification happened, I Found UIDevice.current.orientation.isPortrait and UIScreen.main.bounds.height often have wrong value, why?

Anyway, test code is just reset offset = 0 in onRotated(). but it doesn't work; otherwise onTapGesture works fine.

Q1: Is it a wrong way for SwiftUI? SceneDelegate.orientationDidChangeNotification -> contentView.onRotated()?

Q2: why do UIDevice.current.orientation.isPortrait and UIScreen.main.bounds.height often have wrong value?

Q3: How to let a view float at the bottom of screen in both portrait and landscape?

let height: CGFloat = 100

struct TestView: View {
    @State var offset = (UIScreen.main.bounds.height - height) / 2

    var body: some View {
        ZStack {
            Text("+")
            VStack(spacing: 0) {
                Rectangle().fill(Color.blue)
                Rectangle().fill(Color.red)
            }
            .frame(width: 100, height: height)
            .offset(y: offset)
            .onTapGesture {
                self.offset = 0
            }
        }
    }

    func onRotated() {
//        let isPortrait =  UIDevice.current.orientation.isPortrait
        offset = 0//(UIScreen.main.bounds.height - height) / 2
//        print("\(isPortrait), screen height = \(UIScreen.main.bounds.height)")
    }
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = TestView()
        if let windowScene = scene as? UIWindowScene {
            NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { notification in
                contentView.onRotated()
            }

            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
    ...
}

Body:
contentView is not a reference, it is a value, so you call .onRotated on own copy of contentView value that lives only within callback

    let contentView = TestView()
    if let windowScene = scene as? UIWindowScene {
        NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { notification in
            contentView.onRotated() // local copy!!!
        }

instead create listener for notification publisher inside TestView, so it can change self internally.

Moreover, it is not clear the intention but SwiftUI gives possibility to track size classes via EnvironmentValues.horizontalSizeClass and EnvironmentValues.verticalSizeClass which are automatically changed on device orientation, so it is possible to make your view layout depending on those environment values even w/o notification.

See here good example on how to use size classes


答:
You can join all the values with ',' and then adding a ' before and after the string like this:

"'{0}'".format("','".join(list1))
```

Title: Coverting a python list into string with comma separated in efficient way

Body:
I have a list of acc nos:

list1 = ['1234','3456','2345','5543','1344','5679','6433','3243','0089']

Output I need is a string:

print(output): '1234','3456','2345','5543','1344','5679','6433','3243','0089'


问:
Is there a way to use the aws_ec2 ansible inventory plugin to define a prometheus target group dynamicly?
I'm trying to configure a prometheus server working with ansible. I want to monitor some aws instances (ec2) but I'm stuck with the targets of prometheus. I probably should use a json file to define my targets but I don't know how to update the file when I create a new instance with ansible. Also I'm using the aws_ec2 plugin for the dynamic inventory on ansible.

So my question is: how can I use the inventory plugin to keep update the target file of prometheus without doing it manually?

答:
You can use prometheus service discovery with the same / similar filters that you use for aws_ec2 inventory. I spent time on this issue as well but am very happy with the outcome. Basic example:

```<code>scrape_configs:
- ec2_sd_configs:
  - filters:
    - name: tag:Environment
      values:
      - PROD
  job_name: ec2
  relabel_configs:
  - replacement: ${1}.prod.yourdomain.com:9100
    source_labels:
    - __meta_ec2_tag_dnsname
    target_label: __address__
  - source_labels:
    - __meta_ec2_tag_Name
    target_label: instance
- ec2_sd_configs:
  - filters:
    - name: tag:Environment
      values:
      - PROD
  job_name: application_actuators
  relabel_configs:
  - replacement: ${1}.prod.yourdomain.com:9001
    source_labels:
    - __meta_ec2_tag_dnsname
    target_label: __address__
  - source_labels:
    - __meta_ec2_tag_Name
    target_label: instance
  - action: drop
    regex: ^$
    source_labels:
    - __meta_ec2_tag_application
  - regex: (.+)
    replacement: /$1/api/actuator/prometheus
    source_labels:
    - __meta_ec2_tag_application
    target_label: __metrics_path__
</code>```

ec2_sd_config documentation

This config is generated by ansible.

Body:
You can use prometheus service discovery with the same / similar filters that you use for aws_ec2 inventory. I spent time on this issue as well but am very happy with the outcome. Basic example:

scrape_configs:
- ec2_sd_configs:
  - filters:
    - name: tag:Environment
      values:
      - PROD
  job_name: ec2
  relabel_configs:
  - replacement: ${1}.prod.yourdomain.com:9100
    source_labels:
    - __meta_ec2_tag_dnsname
    target_label: __address__
  - source_labels:
    - __meta_ec2_tag_Name
    target_label: instance
- ec2_sd_configs:
  - filters:
    - name: tag:Environment
      values:
      - PROD
  job_name: application_actuators
  relabel_configs:
  - replacement: ${1}.prod.yourdomain.com:9001
    source_labels:
    - __meta_ec2_tag_dnsname
    target_label: __address__
  - source_labels:
    - __meta_ec2_tag_Name
    target_label: instance
  - action: drop
    regex: ^$
    source_labels:
    - __meta_ec2_tag_application
  - regex: (.+)
    replacement: /$1/api/actuator/prometheus
    source_labels:
    - __meta_ec2_tag_application
    target_label: __metrics_path__

ec2_sd_config documentation

This config is generated by ansible.


问:
CommandManager.InvalidateRequerySuggested does not cause a requery on CanExecute in MVVM-Light
I am using MVVM-Light RelayCommand

```<code>private ICommand myRevertCmd;
public ICommand Revert
    {
        get
        {
            if (myRevertCmd == null)
            {
                myRevertCmd = new RelayCommand(RevertExecute, CanRevertExecute);
            }

            return myRevertCmd;
        }
    }

    private void RevertExecute()
    {
        searchType = SearchType.Revert;
        SearchStart();
    }

    private bool CanRevertExecute()
    {
        return isRevertEnabled;
    }
</code>```

I have some code that changes the value of isRevertEnabled but the linked button does not change. After some searching I found that you can use to force the re-evaluation of the button states

```<code>// force the GUI to re-evaluate the state of the buttons
CommandManager.InvalidateRequerySuggested();
</code>```

But this doesn't work. Does any one have any suggestions?

答:
There are a lot suggestions out there (here, here, here).

I use a simple but not so beautiful workaround. I simply call OnPropertyChanged("MyICommand") for my commands in my BackgroundWorker Completed Event.

Body:
I am using MVVM-Light RelayCommand

private ICommand myRevertCmd;
public ICommand Revert
    {
        get
        {
            if (myRevertCmd == null)
            {
                myRevertCmd = new RelayCommand(RevertExecute, CanRevertExecute);
            }

            return myRevertCmd;
        }
    }

    private void RevertExecute()
    {
        searchType = SearchType.Revert;
        SearchStart();
    }

    private bool CanRevertExecute()
    {
        return isRevertEnabled;
    }

I have some code that changes the value of isRevertEnabled but the linked button does not change. After some searching I found that you can use to force the re-evaluation of the button states

// force the GUI to re-evaluate the state of the buttons
CommandManager.InvalidateRequerySuggested();

But this doesn't work. Does any one have any suggestions?


问:
Combine two files and keep the non match lines
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

```<code>A       1
C       3
E       5
</code>```

file2.txt

```<code>1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers
</code>```

desired output

```<code>1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E
</code>```

I try to make awk script like this:

```<code>awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V
</code>```

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

答:
You should use following code, I have made minor changes in your attempt.

```<code>awk '
FNR==NR{
  val=$1
  $1=""
  sub(/^ +/,"")
  seen[val]=$0
  next
}
$2 in seen{
  print $2,seen[$2],$1
  b[$2]
  next
}
END{
  for(i in seen){
    if(!(i in b)){
      print i,seen[i]
    }
  }
}
' file2.txt file1.txt | sort -V
</code>```

Output will be as follows.

```<code>1 John Lennon A
2 Mariah carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E
</code>```

Problem with OP's attempted code:

OP is making index for seen array as $1(which is correct) BUT making value as ONLY $2 which is NOT right, because $2 will catch only John OR Mariah and so on.

That is the reason why OP's attempt is NOT giving complete output.

Also OP is using $1 index of Input_file1(file1.txt) to check if its present in seen array or not, it should be $2 there.

Body:
I am studying the sed command but I have a problem when combining 2 files.

file1.txt

A       1
C       3
E       5

file2.txt

1 John Lennon
2 Mariah carey
3 Cool & The Gang
4 Westlife
5 Red Hot Chili Peppers

desired output

1 John Lennon A
2 Mariah Carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E

I try to make awk script like this:

awk 'FNR==NR{seen[$1]=$2; next} $1 in seen{seen[$1]=seen[$1] OFS $2} END{ for (e in seen) print e, seen[e]}' file2.txt file1.txt | sort -V

but this output only display one word of the singer (John, Mariah, Cool, Westlife, and Red) and does not display the singer's full name. Is something wrong with my script?

Body:
You should use following code, I have made minor changes in your attempt.

awk '
FNR==NR{
  val=$1
  $1=""
  sub(/^ +/,"")
  seen[val]=$0
  next
}
$2 in seen{
  print $2,seen[$2],$1
  b[$2]
  next
}
END{
  for(i in seen){
    if(!(i in b)){
      print i,seen[i]
    }
  }
}
' file2.txt file1.txt | sort -V

Output will be as follows.

1 John Lennon A
2 Mariah carey
3 Cool & The Gang C
4 Westlife
5 Red Hot Chili Peppers E

Problem with OP's attempted code:

OP is making index for seen array as $1(which is correct) BUT making value as ONLY $2 which is NOT right, because $2 will catch only John OR Mariah and so on.

That is the reason why OP's attempt is NOT giving complete output.

Also OP is using $1 index of Input_file1(file1.txt) to check if its present in seen array or not, it should be $2 there.


问:
How to create checkbox inside the form group selection HTML Javascript?
Currently, I have 200+ countries list in my database. I want to create a checkbox for the countries selection. Even I already put the html type as a checkbox, the checkbox still doesn't exist in my selection form. How to create checkbox actually?

HTML :

```<code><div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label>Country</label>
                    <select class="form-control"  name="country_id[]" multiple  size="10" style="height: 100%;">
                        @foreach ($countries as $item)
                            <option value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>
</code>```

答:
You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript.

var expanded = false;

function showCheckboxes() {
  var checkboxes = document.getElementById("checkboxes");
  if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.multiselect {
  width: 200px;
}

.selectBox {
  position: relative;
}

.selectBox select {
  width: 100%;
  font-weight: bold;
}

.overSelect {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

#checkboxes {
  display: none;
  border: 1px #dadada solid;
}

#checkboxes label {
  display: block;
}

#checkboxes label:hover {
  background-color: #1e90ff;
}</code>```

<form>

      <select>
        <option>Select an option</option>
      </select>

        <input type="checkbox" id="one" />First checkbox

        <input type="checkbox" id="two" />Second checkbox

        <input type="checkbox" id="three" />Third checkbox

</form>```

Also you can use Bootstrap Multiselect plugin.

Body:
Currently, I have 200+ countries list in my database. I want to create a checkbox for the countries selection. Even I already put the html type as a checkbox, the checkbox still doesn't exist in my selection form. How to create checkbox actually?

HTML :

                    Country
                    <select class="form-control"  name="country_id[]" multiple  size="10" style="height: 100%;">
                        @foreach ($countries as $item)
                            <option value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>

Body:
You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript.

var expanded = false;

function showCheckboxes() {
  var checkboxes = document.getElementById("checkboxes");
  if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
}

.multiselect {
  width: 200px;
}

.selectBox {
  position: relative;
}

.selectBox select {
  width: 100%;
  font-weight: bold;
}

.overSelect {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

#checkboxes {
  display: none;
  border: 1px #dadada solid;
}

#checkboxes label {
  display: block;
}

#checkboxes label:hover {
  background-color: #1e90ff;
}

<form>
  <div class="multiselect">
    <div class="selectBox" onclick="showCheckboxes()">
      <select>
        <option>Select an option</option>
      </select>
      <div class="overSelect"></div>
    </div>
    <div id="checkboxes">
      <label for="one">
        <input type="checkbox" id="one" />First checkbox</label>
      <label for="two">
        <input type="checkbox" id="two" />Second checkbox</label>
      <label for="three">
        <input type="checkbox" id="three" />Third checkbox</label>
    </div>
  </div>
</form>

Also you can use Bootstrap Multiselect plugin.


问:
pointer not updating the value it is pointing to inside void function
I've made a simple function that simple does the addition and absolute difference between the parameters using pointers, but when I try to update the pointer, the pointer still has the old value. why is this so, or what am I doing wrong:

```<code>#include <stdio.h>
#include <cstdlib>

void update(int *a,int *b) {
int temp = *a;
int temp2 = *b;
int temp3 =0;
temp3 = temp + temp2;
printf("%d",temp3);
*b = abs(*a - *b);
 a = &temp3; // it is not updating
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}
</code>```

the pointer a is not updating and still retains its old value inside the function update

答: Simple answer is because in a = &temp3; you're assigning an memory address of parameter temp3 which is probably in a function stack call, to *a parameter of function which also is laying on the function stack call.

Body:
I've made a simple function that simple does the addition and absolute difference between the parameters using pointers, but when I try to update the pointer, the pointer still has the old value. why is this so, or what am I doing wrong:

#include <stdio.h>
#include <cstdlib>

void update(int *a,int *b) {
int temp = *a;
int temp2 = *b;
int temp3 =0;
temp3 = temp + temp2;
printf("%d",temp3);
*b = abs(*a - *b);
 a = &temp3; // it is not updating
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}

the pointer a is not updating and still retains its old value inside the function update


问:
Avoid sign-in popup when running hmtl page with node.js
We're creating a web app in node.js. For this we're following this example to see how things are done. Whenever we work with an express-session there is a credential pop-up displayed when accessing the page in the browser.

  app.use(session({
    proxy: true,
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    rolling: true,
    name: 'sid',
    cookie: {
      maxAge: 20 * 60 * 1000
    }
  }));
```

Searching the web I found this which talks about setting the proxy setting in the session. However, after trying all options we still get the pop-up. Installing stuff through npm works fine without issue, even loading pages where no express-session are used.

How can we avoid this pop-up? Thank you for your help.

答:
I finally nailed this down. It was something completely unrelated. As we are using bootstrap 4 we get the sign in pop up when we don't include the correct javascript files required by bootstrap at the end of the HTML page:

```

Including this at the end of the page removed the annoying pop-up.

Body:
We're creating a web app in node.js. For this we're following this example to see how things are done. Whenever we work with an express-session there is a credential pop-up displayed when accessing the page in the browser.

  app.use(session({
    proxy: true,
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    rolling: true,
    name: 'sid',
    cookie: {
      maxAge: 20 * 60 * 1000
    }
  }));

Searching the web I found this which talks about setting the proxy setting in the session. However, after trying all options we still get the pop-up. Installing stuff through npm works fine without issue, even loading pages where no express-session are used.

How can we avoid this pop-up? Thank you for your help.

Body:
I finally nailed this down. It was something completely unrelated. As we are using bootstrap 4 we get the sign in pop up when we don't include the correct javascript files required by bootstrap at the end of the HTML page:

<body>
    <!-- Other html code -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="/js/jquery.min.js"></script>
    <script src="/js/popper.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
</body>

Including this at the end of the page removed the annoying pop-up.


问:
Cannot restore SQL Server snapshot
For some reason I cannot restore my SQL Server snapshot.

I have the a database DB01 with a snapshot DB01_SS.

When trying to restore the snapshot with the following query:

```<code>USE master
GO

ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO

ALTER DATABASE DB01 SET MULTI_USER
GO
</code>```

I get this error message:

Msg 3137, Level 16, State 1, Line 5

  Database cannot be reverted. Either the primary or the snapshot names are improperly specified, all other snapshots have not been dropped, or there are missing files.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

I have checked, the name is properly specified. There are no other snapshots available on the server. The only strange thing I came across was when I logged on the SQL Server to look up the snapshot file. And it had a different name then in the SSMS gui. It was named DB_SS_2017.SS. When trying to restore with that name, I get the following error:

Msg 911, Level 16, State 4, Line 5

  Database DB_SS_2017.SS does not exist. Make sure that the name is entered correctly.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

And last but not least, when trying to check the properties of the snapshot, again in SSMS. The properties button is greyed out! How can I restore the SQL Server snapshot?

答:
Need a much more "harder" connection drop :):):)</p>

```<code>USE master
GO
ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE DB01 SET OFFLINE
GO
ALTER DATABASE DB01 SET ONLINE
GO
RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO
ALTER DATABASE DB01 SET MULTI_USER
GO
</code>```

Title: Cannot restore SQL Server snapshot

Body:
For some reason I cannot restore my SQL Server snapshot.

I have the a database DB01 with a snapshot DB01_SS.

When trying to restore the snapshot with the following query:

USE master
GO

ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO

ALTER DATABASE DB01 SET MULTI_USER
GO

I get this error message:

Msg 3137, Level 16, State 1, Line 5

  Database cannot be reverted. Either the primary or the snapshot names are improperly specified, all other snapshots have not been dropped, or there are missing files.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

I have checked, the name is properly specified. There are no other snapshots available on the server. The only strange thing I came across was when I logged on the SQL Server to look up the snapshot file. And it had a different name then in the SSMS gui. It was named DB_SS_2017.SS. When trying to restore with that name, I get the following error:

Msg 911, Level 16, State 4, Line 5

  Database DB_SS_2017.SS does not exist. Make sure that the name is entered correctly.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

And last but not least, when trying to check the properties of the snapshot, again in SSMS. The properties button is greyed out! How can I restore the SQL Server snapshot?

Body:
Need a much more "harder" connection drop :):):)

USE master
GO
ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE DB01 SET OFFLINE
GO
ALTER DATABASE DB01 SET ONLINE
GO
RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO
ALTER DATABASE DB01 SET MULTI_USER
GO


问:
Dropdown List deduction
I have a list of 100 employees and 50 dropdowns. I want to select some of the employees in the dropdowns but I want to prevent the user from choosing the same employee more than once.
I want to deduct the chosen employees from the possible dropdown answers. How can I manage to do so?

I tried to filter out the selected employees but it shows an ugly warning sign for those who were selected

you can view my spreadsheet here:
https://docs.google.com/spreadsheets/d/1bzMPC3-SDOjsgZVXHQgmfBnkiTEsa1Pei7p_DybIebY/edit?usp=sharing

答:
You can use the Simple Trigger onEdit(e) to automatically do the job:

The onEdit(e) trigger runs automatically when a user changes the value
  of any cell in a spreadsheet [...]

It's not exactly the same as you had before, because the selected values will still be displayed on the list. They just will be removed if they are repeated.

The only change you should do is to remove the current Data Validation from Column D and set a new one with values from Column A.

```<code>function onEdit(event){

  if (event.range.getColumn() == 4){   //Run only if the edited cell is from column D

    var sheet = SpreadsheetApp.getActiveSheet();
    var selection = sheet.getRange("D2:D22").getValues();
    var editedRow = event.range.getRow(); //Gets the edited row

    for (var i = 0; i < selection.length; i++){

      //If some value from D is equal to the edited value but in a different Row (so it ignores the inputted value)
      if ((i + 2) != editedRow &&  selection[i][0] == event.value){

          sheet.getRange(event.range.getA1Notation()).setValue(""); //Change the new value to empty

      }

    }
  }
}
</code>```

The function will run every time you select an item in the column D.

Result:

References:

Range

Sheet

setValue

Title: Dropdown List deduction

Body:
You can use the Simple Trigger onEdit(e) to automatically do the job:

The onEdit(e) trigger runs automatically when a user changes the value
  of any cell in a spreadsheet [...]

It's not exactly the same as you had before, because the selected values will still be displayed on the list. They just will be removed if they are repeated.

The only change you should do is to remove the current Data Validation from Column D and set a new one with values from Column A.

function onEdit(event){

  if (event.range.getColumn() == 4){   //Run only if the edited cell is from column D

    var sheet = SpreadsheetApp.getActiveSheet();
    var selection = sheet.getRange("D2:D22").getValues();
    var editedRow = event.range.getRow(); //Gets the edited row

    for (var i = 0; i < selection.length; i++){

      //If some value from D is equal to the edited value but in a different Row (so it ignores the inputted value)
      if ((i + 2) != editedRow &&  selection[i][0] == event.value){

          sheet.getRange(event.range.getA1Notation()).setValue(""); //Change the new value to empty

      }

    }
  }
}

The function will run every time you select an item in the column D.

Result:

References:

Range

Sheet

setValue


问:
Visual Studio 2010 - Debug Breakpoint
Ive just created a new web site project , added a few lines of code in my .cs file set a break point, and nada, website works, but debug point is not hit.
Any ideas?

Im starting the project with Debugging, running on windows 7 64bit

thanks

答: Are you running in debug mode? Check out the configuration under project properties -> build, make sure it is running under "any cpu" and with debug configuration</p>

Title: Visual Studio 2010 - Debug Breakpoint


问:
Uploaded an Application to the play store but it won't open
So I recently uploaded my Android application to the Google Play store and it published successfully. This is the application here: https://play.google.com/store/apps/details?id=com.kyoudai.sudioku

The problem is, when anyone installs thiis application, they cannot open it i.e. the open option does not appear on the playstore, only the uninstall option. This application also cannot be found in the application drawer on any device, or in the list of installed applications. I've tried editing my manifest and included everything necessary but I have no idea why this happens. I generally believe if there was an issue with my code that should not be possible for an android application, the play store would flag it. When I was developing this, it showed up on the emulator application drawer so I assumed it was fine. I'm not sure why this happens, and I'm not even sure where to contact google regarding this. Any help is appreciated.

Given people are gonna jump on the manifest configuration, here it is: https://github.com/BerserkerLan/Sudoku-Android/blob/master/app/src/main/AndroidManifest.xml

答: make sure that your build is signed APK/Bundle</p>


问:
How can I replace the column labels of a dataframe with values from one of it's rows
I have an xls data file which I've read into python using Pandas as a dataframe, but the data that I would like to form the column headings are in row 5 of the xls file.

Is there a way to extract a row of values from a dataframe and then replace the column labels with those values?

I would like the values in row 3 of the dataframe (update time, PV1 voltage (V), PV1 current (A)) to replace the current column labels. I don't need any of the data in rows 1-4 in the xls file.

I'm a real python beginner and can't figure it out!

```<code>data = pd.read_excel('H1E372F8273057 2020-02-17.xls')
</code>```

data =

```<code>                 site name     richardssite       report type
0                  NaN              NaN               NaN
1                  NaN              NaN               NaN
2          Inverter SN   H1E372F8273056  Registration No.
3          update time  PV1 voltage (V)   PV1 current (A)
4  2020-02-17 00:03:15                0                 0
5  2020-02-17 00:08:15                0                 0
6  2020-02-17 00:13:16                0                 0
7  2020-02-17 00:18:15                0                 0
8  2020-02-17 00:23:15                0                 0
</code>```

答:
The option header should do the job to select the columns name.

```<code>data = pd.read_excel('H1E372F8273057 2020-02-17.xls', header=4)
</code>```

To remove the rows, you can use skiprows option, but not totally sure if the loading function first remove the lines then set the header or the other way, wich can have influence on the number to give in header.

```<code>data = pd.read_excel('H1E372F8273057 2020-02-17.xls', header=4,skiprows=[0,1,2,3])
</code>```

Body:
I have an xls data file which I've read into python using Pandas as a dataframe, but the data that I would like to form the column headings are in row 5 of the xls file.

Is there a way to extract a row of values from a dataframe and then replace the column labels with those values?

I would like the values in row 3 of the dataframe (update time, PV1 voltage (V), PV1 current (A)) to replace the current column labels. I don't need any of the data in rows 1-4 in the xls file.

I'm a real python beginner and can't figure it out!

data = pd.read_excel('H1E372F8273057 2020-02-17.xls')

data =

                 site name     richardssite       report type
0                  NaN              NaN               NaN
1                  NaN              NaN               NaN
2          Inverter SN   H1E372F8273056  Registration No.
3          update time  PV1 voltage (V)   PV1 current (A)
4  2020-02-17 00:03:15                0                 0
5  2020-02-17 00:08:15                0                 0
6  2020-02-17 00:13:16                0                 0
7  2020-02-17 00:18:15                0                 0
8  2020-02-17 00:23:15                0                 0

Body:
The option header should do the job to select the columns name.

data = pd.read_excel('H1E372F8273057 2020-02-17.xls', header=4)

To remove the rows, you can use skiprows option, but not totally sure if the loading function first remove the lines then set the header or the other way, wich can have influence on the number to give in header.

data = pd.read_excel('H1E372F8273057 2020-02-17.xls', header=4,skiprows=[0,1,2,3])


问:
How to fix the conflict when implement two id interfaces?
One interface is 'org.springframework.data.domain.Persistable', it's a java interface with a method ID getId() in 3rd-party lib.

Another interface is a Kotlin interface interface IdEntry { val id: String}.

Now my business entry needs to implement these two interfaces:

```<code>data class MyEntry(
  override val id: String,
  ....// more properties
) : IdEntry, Persistable<String>
</code>```

I use IntelliJ IDE to code and the error is:

```<code>Class 'MyEntry' is not abstract and does not implement abstract member
@Nullable public abstract fun getId(): String!
defined in org.springframework.data.domain.Persistable
</code>```

How can I fix this?

I also tried below code: (idea from here)

```<code>data class MyEntry(
  private val id: String,
  ....// more properties
) : IdEntry, Persistable<String> {
  override fun getId() = id
  ...
}
</code>```

But this also failed:

```<code>Cannot weaken access privilege 'public' for 'id' in 'IdEntry'
</code>```

答:
This is a platform declaration clash that cannot easily be resolved as long as MyEntry implements both IdEntry and Persistable.

However, there is one way, if you declare the property that is inherited by IdEntry as a @JvmField:

```<code>import org.springframework.data.domain.Persistable

data class MyEntry(@JvmField override var id: String) :
        IdEntry, Persistable<String> {

    override fun getId(): String? = this.id

    override fun isNew(): Boolean {
        TODO("not implemented")
    }
}

interface IdEntry {
    val id: String
}
</code>```

This works, because the clash occurs when the Kotlin compiler generates getters and setters for the id property as long as it has no @JvmField annotation.

The getter clashes with the function getId() inherited from Persistable.

By adding @JvmField, the generation of the getter for the id from IdEntry is avoided, thus preventing the clash.

Body:
One interface is 'org.springframework.data.domain.Persistable', it's a java interface with a method ID getId() in 3rd-party lib.

Another interface is a Kotlin interface interface IdEntry { val id: String}.

Now my business entry needs to implement these two interfaces:

data class MyEntry(
  override val id: String,
  ....// more properties
) : IdEntry, Persistable<String>

I use IntelliJ IDE to code and the error is:

Class 'MyEntry' is not abstract and does not implement abstract member
@Nullable public abstract fun getId(): String!
defined in org.springframework.data.domain.Persistable

How can I fix this?

I also tried below code: (idea from here)

data class MyEntry(
  private val id: String,
  ....// more properties
) : IdEntry, Persistable<String> {
  override fun getId() = id
  ...
}

But this also failed:

Cannot weaken access privilege 'public' for 'id' in 'IdEntry'

Body:
This is a platform declaration clash that cannot easily be resolved as long as MyEntry implements both IdEntry and Persistable.

However, there is one way, if you declare the property that is inherited by IdEntry as a @JvmField:

import org.springframework.data.domain.Persistable

data class MyEntry(@JvmField override var id: String) :
        IdEntry, Persistable<String> {

    override fun getId(): String? = this.id

    override fun isNew(): Boolean {
        TODO("not implemented")
    }
}

interface IdEntry {
    val id: String
}

This works, because the clash occurs when the Kotlin compiler generates getters and setters for the id property as long as it has no @JvmField annotation.

The getter clashes with the function getId() inherited from Persistable.

By adding @JvmField, the generation of the getter for the id from IdEntry is avoided, thus preventing the clash.


问:
Json.net serialize/deserialize derived types?
json.net (newtonsoft)

I am looking through the documentation but I can't find anything on this or the best way to do it.

```<code>public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

JsonConvert.Deserialize<List<Base>>(text);
</code>```

Now I have Derived objects in the serialized list. How do I deserialize the list and get back derived types?

答:
Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

```<code>[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}
</code>```

Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

Serialized list example:

```<code>[
    {"Name":"some name", "$type":"base"},
    {"Name":"some name", "Something":"something", "$type":"derived"}
]
</code>```

Body:
json.net (newtonsoft)

I am looking through the documentation but I can't find anything on this or the best way to do it.

public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

JsonConvert.Deserialize<List<Base>>(text);

Now I have Derived objects in the serialized list. How do I deserialize the list and get back derived types?

Body:
Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

Serialized list example:

[
    {"Name":"some name", "$type":"base"},
    {"Name":"some name", "Something":"something", "$type":"derived"}
]


问:
Unable to find image 'jmeter:latest' locally when the image is already available
I am trying to run JMeter in a docker container. To achieve this I initially pulled this JMeter image from the docker hub. Then when I do

docker image ls

It shows the pulled image

But when I execute the below command and try to run the container It gives me the below error:

```<code>export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter -t ${jmeter_path}/factorial.jmx -l ${jmeter_path}/jmeter_results.jtl -q ${jmeter_path}/user.properties  egaillardon/jmeter:latest
</code>```

Unable to find image 'jmeter:latest' locally docker: Error response
  from daemon: pull access denied for jmeter, repository does not exist
  or may require 'docker login': denied: requested access to the
  resource is denied. See 'docker run --help'.

What am I doing wrong?

答:
The error comes from here :

docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter ...
```

At this point you have jmeter in the command and it is interpreted as the image jmeter:latest. The rest of your command will just override your docker image CMD.

That is why the error is referencing image jmeter:latest and not egaillardon/jmeter:latest

Body:
I am trying to run JMeter in a docker container. To achieve this I initially pulled this JMeter image from the docker hub. Then when I do

docker image ls

It shows the pulled image

But when I execute the below command and try to run the container It gives me the below error:

export volume_path=/Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_resource && export jmeter_path=/jmeter && docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter -t ${jmeter_path}/factorial.jmx -l ${jmeter_path}/jmeter_results.jtl -q ${jmeter_path}/user.properties  egaillardon/jmeter:latest

Unable to find image 'jmeter:latest' locally docker: Error response
  from daemon: pull access denied for jmeter, repository does not exist
  or may require 'docker login': denied: requested access to the
  resource is denied. See 'docker run --help'.

What am I doing wrong?

Body:
The error comes from here :

docker run --rm --name jmeterContainer --memory="512m" --cpus=2 --volume ${volume_path}:${jmeter_path} -e JAVA_OPTS="-Xms512 -Xmx512" jmeter ...

At this point you have jmeter in the command and it is interpreted as the image jmeter:latest. The rest of your command will just override your docker image CMD.

That is why the error is referencing image jmeter:latest and not egaillardon/jmeter:latest


问:
How to extract information from pandas dataframe column
I have the dataframe below and I want to extract some information from column A and then create other columns to add them based on their types.
Below is an example to illustrate this.

```<code>In [0]: df
Out[0]:
          A
0 1258GA 25/01/20 TABLE 090626  038272
1 GOODIES 762088 A714816
2 TABLE AA88547 734963 GOODIES
3 WATER 02/450 FROM TOMORROW 48246
4 02H12 ALSCA 00548246B GOODIES
</code>```

And I want to have the result below.

```<code>In [1]: df
Out[1]:
          A                               Category             Date      Hour
0 1258GA 25/01/20 TABLE 090626  038272    TABLE           25/01/20
1 GOODIES 762088 A714816                  GOODIES
2 TABLE AA88547 734963 GOODIES            TABLE GOODIES
3 WATER 02/450 FROM TOMORROW 48246        WATER
4 02H12 ALSCA 00548246B GOODIES           GOODIES                        02H12
</code>```

I've tried many things but haven't got that result

答:
You can certainly do that using Series.str methods,

The Series.str.extract() returns:

Extract capture groups in the regex pat as columns in a DataFrame.

For each subject string in the Series, extract groups from the first
  match of regular expression pat.

The Series.str.findall() returns:

Find all occurrences of pattern or regular expression in the Series/Index.

Here is the code snippet,

EDIT:

```<code>df["Category"] = df['A'].str.findall(r"(\b[A-Za-z]+\b)").str.join(' ')
df["Date"] = df['A'].str.extract(r"(\b[0-9]+/[0-9]+/[0-9]+\b)")
df["Hour"] = df['A'].str.extract(r"(\b[0-9]+H[0-9]+\b)")
</code>```

And output will be,

```<code>                                      A             Category      Date   Hour
0  1258GA 25/01/20 TABLE 090626  038272                TABLE  25/01/20    NaN
1                GOODIES 762088 A714816              GOODIES       NaN    NaN
2          TABLE AA88547 734963 GOODIES        TABLE GOODIES       NaN    NaN
3      WATER 02/450 FROM TOMORROW 48246  WATER FROM TOMORROW       NaN    NaN
4         02H12 ALSCA 00548246B GOODIES        ALSCA GOODIES       NaN  02H12
</code>```

Body:
I have the dataframe below and I want to extract some information from column A and then create other columns to add them based on their types.
Below is an example to illustrate this.

In [0]: df
Out[0]:
          A
0 1258GA 25/01/20 TABLE 090626  038272
1 GOODIES 762088 A714816
2 TABLE AA88547 734963 GOODIES
3 WATER 02/450 FROM TOMORROW 48246
4 02H12 ALSCA 00548246B GOODIES

And I want to have the result below.

In [1]: df
Out[1]:
          A                               Category             Date      Hour
0 1258GA 25/01/20 TABLE 090626  038272    TABLE           25/01/20
1 GOODIES 762088 A714816                  GOODIES
2 TABLE AA88547 734963 GOODIES            TABLE GOODIES
3 WATER 02/450 FROM TOMORROW 48246        WATER
4 02H12 ALSCA 00548246B GOODIES           GOODIES                        02H12

I've tried many things but haven't got that result

Body:
You can certainly do that using Series.str methods,

The Series.str.extract() returns:

Extract capture groups in the regex pat as columns in a DataFrame.

For each subject string in the Series, extract groups from the first
  match of regular expression pat.

The Series.str.findall() returns:

Find all occurrences of pattern or regular expression in the Series/Index.

Here is the code snippet,

EDIT:

df["Category"] = df['A'].str.findall(r"(\b[A-Za-z]+\b)").str.join(' ')
df["Date"] = df['A'].str.extract(r"(\b[0-9]+/[0-9]+/[0-9]+\b)")
df["Hour"] = df['A'].str.extract(r"(\b[0-9]+H[0-9]+\b)")

And output will be,

                                      A             Category      Date   Hour
0  1258GA 25/01/20 TABLE 090626  038272                TABLE  25/01/20    NaN
1                GOODIES 762088 A714816              GOODIES       NaN    NaN
2          TABLE AA88547 734963 GOODIES        TABLE GOODIES       NaN    NaN
3      WATER 02/450 FROM TOMORROW 48246  WATER FROM TOMORROW       NaN    NaN
4         02H12 ALSCA 00548246B GOODIES        ALSCA GOODIES       NaN  02H12


问:
How to reverse sort again after sort an array of objects?
I'm doing a list of items by using a v-for and for each properties i'm trying to sort them by ascending and descending.

The fact is I trigger the sort function on a v-btn to sort by ascending but when i click again nothing happen. I would like to reverse the sort and etc. when I click again on it.

My current method for on of my property is :

```<code>sortByScope()
      {
        this.alerts.sort(function(a, b){
            if(a.scope < b.scope){ return -1 }
            if(a.scope > b.scope){ return 1 }
            return 0
        })
      },
</code>```

Do you have any ideas ?

Thanks for your attention

答:
If I understand your question correctly, you want your button to sort ascending or descending based on the current sorting of the column. You can do so by using a toggle flag:

sortByScope() {
  this.alerts.sort(function (a, b) {
    return this.sortScopeToggle
      ? a - b
      : b - a;
  });
  this.sortScopeToggle = !this.sortScopeToggle;
}
```

Where sortScopeToggle is a boolean that keeps track of the sorting order, and based on this boolean, a ternary operation returns the sorting algorithm.

Body:
I'm doing a list of items by using a v-for and for each properties i'm trying to sort them by ascending and descending.

The fact is I trigger the sort function on a v-btn to sort by ascending but when i click again nothing happen. I would like to reverse the sort and etc. when I click again on it.

My current method for on of my property is :

sortByScope()
      {
        this.alerts.sort(function(a, b){
            if(a.scope  b.scope){ return 1 }
            return 0
        })
      },

Do you have any ideas ?

Thanks for your attention

Body:
If I understand your question correctly, you want your button to sort ascending or descending based on the current sorting of the column. You can do so by using a toggle flag:

sortByScope() {
  this.alerts.sort(function (a, b) {
    return this.sortScopeToggle
      ? a - b
      : b - a;
  });
  this.sortScopeToggle = !this.sortScopeToggle;
}

Where sortScopeToggle is a boolean that keeps track of the sorting order, and based on this boolean, a ternary operation returns the sorting algorithm.


问:
Django Form: Only show manytomany objects from logged in user
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created.

Something like this:

```<code>associated_portfolios manytomany field = ...objects.filter(user=user_id)
</code>```

I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin.

Models.py

```<code>class Portfolio(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=250, blank=True, null=True)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = RichTextUploadingField(blank=True, null=True)
    associated_portfolios = models.ManyToManyField(Portfolio, blank=True)
    created_on = models.DateField(auto_now_add=True, editable=False)
</code>```

Views.py

```<code>class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user)
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
</code>```

forms.py

```<code>class PortfolioCreateForm(ModelForm):
    class Meta:
        model = Portfolio
        fields = ['user', 'name', 'description']

class PostCreateForm(ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'body', 'category', 'associated_portfolios']
</code>```

答:
Did you try this

```<code>self.fields['associated_portfolios'] = Post.objects.filter(associated_portfolios__portfolio__user=request.user)
</code>```

OR

```<code>user_posts = Post.objects.filter(user=request.user)
self.fields['associated_portfolios'] = user_posts.associated_portfolios.all()
</code>```

read more about M2M relationships querying here, because I think your problem may be with it.

Also, I'm not sure about your actual data maybe it's right and it gives a correct result as filtering Portfolio model against current user to get its objects looks right for me, but anyway double check everything again.

And as a final note, add related_name to your model fields so you can use it easily for reverse relations rather than going with Django's default naming, it will be clearer and give a better understanding.

Body:
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created.

Something like this:

associated_portfolios manytomany field = ...objects.filter(user=user_id)

I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin.

Models.py

class Portfolio(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=250, blank=True, null=True)

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = RichTextUploadingField(blank=True, null=True)
    associated_portfolios = models.ManyToManyField(Portfolio, blank=True)
    created_on = models.DateField(auto_now_add=True, editable=False)

Views.py

class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user)
        return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

forms.py

class PortfolioCreateForm(ModelForm):
    class Meta:
        model = Portfolio
        fields = ['user', 'name', 'description']

class PostCreateForm(ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'body', 'category', 'associated_portfolios']

Body:
Did you try this

self.fields['associated_portfolios'] = Post.objects.filter(associated_portfolios__portfolio__user=request.user)

OR

user_posts = Post.objects.filter(user=request.user)
self.fields['associated_portfolios'] = user_posts.associated_portfolios.all()

read more about M2M relationships querying here, because I think your problem may be with it.

Also, I'm not sure about your actual data maybe it's right and it gives a correct result as filtering Portfolio model against current user to get its objects looks right for me, but anyway double check everything again.

And as a final note, add related_name to your model fields so you can use it easily for reverse relations rather than going with Django's default naming, it will be clearer and give a better understanding.


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答:
To get the path in cygwin:

```<code>echo $PATH
</code>```

This will get us on the road to understanding the problem.

Edit:

The next command will tell us where cygwin thinks it should be looking for all those files within windows

```<code>mount
</code>```

The line which includes /usr/bin is the one we need a copy of.

ContentLicense: CC BY-SA 2.5

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

Body:
To get the path in cygwin:

echo $PATH

This will get us on the road to understanding the problem.

Edit:

The next command will tell us where cygwin thinks it should be looking for all those files within windows

mount

The line which includes /usr/bin is the one we need a copy of.

OwnerDisplayName: RobS

LastEditorDisplayName: RobS


问:
how to select row from one of three tables based on fourth table that holds order of those entries from all three tables
so I have three tables with content and one that holds row order of those three tables

here are the tables

```<code>table content_order
id | content_type | content id
1 | content1 | 1
2 | content1 | 2
3 | content3 | 1
4 | content2 | 1

table content1
id | some_text
1 | aaaa
2 | bbb

table content2
id | some_text
1 | text yyyy

table content3
id | some_text
1 | text bbbb
</code>```

so how do I get this?

```<code>content_type | some_text | content_id
content1 | aaaa | 1 |
content2 | bbb | 2 |
content3 | yyyy | 1 |
content2 | bbbb | 1 |
</code>```

答:
This would work on t-sql, there might be slight differences for mysql.</p>

```<code>select co.content_type,
       coalesce(c1.some_text,c2.some_text,c3.some_text) as some_text,
       coalesce(c1.id,c2.id,c3.id) as content_id
from content_order co
left join content1 c1 on co.content_id = c1.id and co.content_type = 'content1'
left join content2 c2 on co.content_id = c2.id and co.content_type = 'content2'
left join content3 c3 on co.content_id = c3.id and co.content_type = 'content3'
order by co.id
</code>```

Body:
so I have three tables with content and one that holds row order of those three tables

here are the tables

table content_order
id | content_type | content id
1 | content1 | 1
2 | content1 | 2
3 | content3 | 1
4 | content2 | 1

table content1
id | some_text
1 | aaaa
2 | bbb

table content2
id | some_text
1 | text yyyy

table content3
id | some_text
1 | text bbbb

so how do I get this?

content_type | some_text | content_id
content1 | aaaa | 1 |
content2 | bbb | 2 |
content3 | yyyy | 1 |
content2 | bbbb | 1 |

Body:
This would work on t-sql, there might be slight differences for mysql.

select co.content_type,
       coalesce(c1.some_text,c2.some_text,c3.some_text) as some_text,
       coalesce(c1.id,c2.id,c3.id) as content_id
from content_order co
left join content1 c1 on co.content_id = c1.id and co.content_type = 'content1'
left join content2 c2 on co.content_id = c2.id and co.content_type = 'content2'
left join content3 c3 on co.content_id = c3.id and co.content_type = 'content3'
order by co.id


答:
I don't really understand what you are doing, it's looks like you are performing a multi-label classification using Sigmoid and binary_crossentropy, which, as the name suggests allows to do a binary classification, with only 2 labels.

In order to have a working model, you have to change your binary model to a multi class one :

Change your last Dense layer to : classifier.add(Dense(output_dim=NB_CLASS, activation='softmax'))

Change your loss to be : classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Change your dataflow to be :

training_set = train_datagen.flow_from_directory(
        'train', target_size=(64, 64), batch_size=32, class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'test', target_size=(64, 64), batch_size=32, class_mode='categorical')
```

Keep me in touch !

Title: Why training accuracy is not improving?

Body:
I'm tying to do some image classification training. Just got to work something.
but no matter what neural network I use, still I get no progress. The accuracy is always stuck.

If you can get me any suggestion I will be very glad. I already tried to tweak batch size, etc...

You can find all the data and content here: https://github.com/marcusdiy/testai

Train for 31 steps, validate for 4 steps
Epoch 1/10
31/31 [==============================] - 11s 352ms/step - loss: -51.9861 - accuracy: 0.0950 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 2/10
31/31 [==============================] - 10s 335ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 3/10
31/31 [==============================] - 10s 334ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 4/10
31/31 [==============================] - 11s 352ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 5/10
31/31 [==============================] - 10s 330ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 6/10
31/31 [==============================] - 10s 331ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 7/10
31/31 [==============================] - 10s 330ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 8/10
31/31 [==============================] - 11s 351ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 9/10
31/31 [==============================] - 11s 355ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833
Epoch 10/10
31/31 [==============================] - 11s 364ms/step - loss: -54.3329 - accuracy: 0.0942 - val_loss: -62.1700 - val_accuracy: 0.0833

Thanks!

Body:
I don't really understand what you are doing, it's looks like you are performing a multi-label classification using Sigmoid and binary_crossentropy, which, as the name suggests allows to do a binary classification, with only 2 labels.

In order to have a working model, you have to change your binary model to a multi class one :

Change your last Dense layer to : classifier.add(Dense(output_dim=NB_CLASS, activation='softmax'))

Change your loss to be : classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

Change your dataflow to be :

training_set = train_datagen.flow_from_directory(
        'train', target_size=(64, 64), batch_size=32, class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'test', target_size=(64, 64), batch_size=32, class_mode='categorical')

Keep me in touch !


问:
Swift and mutating struct
There is something that I don't entirely understand when it comes to mutating value types in Swift.

As the "The Swift Programming Language" iBook states:  By default, the properties of a value type cannot be modified from within its instance methods.

And so to make this possible we can declare methods with the mutating keyword inside structs and enums.

The thing that is not entirely clear to me is this:
You can change a var from outside a struct, but you cannot change it from its own methods. This seems counter-intuitive to me, as in Object Oriented languages, you generally try to encapsulate variables so they can only be changed from within. With structs this appears to be the other way around. To elaborate, here's a code snippet:

```<code>struct Point {
    var x = 0, y = 0
    mutating func moveToX(x: Int, andY y:Int) { //Needs to be a mutating method in order to work
        self.x = x
        self.y = y
    }
}

var p = Point(x: 1, y: 2)
p.x = 3 //Works from outside the struct!
p.moveToX(5, andY: 5)
</code>```

Does anyone know the reason why structs cannot change their content from inside their own context, while the contents can easily be changed elsewhere?

答:
SWIFT : Use of mutating function in Structs

Swift programmers developed Structs in such a way that properties of it can not be modified within Struct methods. For example, Check the code given below

```<code>struct City
{
  var population : Int
  func changePopulation(newpopulation : Int)
  {
      population = newpopulation //error: cannot modify property "popultion"
  }
}
  var mycity = City(population : 1000)
  mycity.changePopulation(newpopulation : 2000)
</code>```

On executing the above code we get an error because we are trying to assign a new value to the property population of the Struct City. By default Structs properties can’t be mutated inside its own methods. This is how Apple Developers have built it, so that the Structs will have a static nature by default.

How do we solve it? What’s the alternative?

Mutating Keyword :

Declaring function as mutating inside Struct allows us to alter properties in Structs.
Line No : 5, of the above code changes to like this,

```<code>mutating changePopulation(newpopulation : Int)
</code>```

Now we can assign the value of the newpopulation to property population to within the scope of the method.

Note :

```<code>let mycity = City(1000)
mycity.changePopulation(newpopulation : 2000)   //error: cannot modify property "popultion"
</code>```

If we use let instead of var for Struct objects, then we can’t mutate the value of any properties, Also this is the reason why we get an error when we try to invoke mutating function using let instance. So it is better to use var whenever you are changing value of a property.

Would love to hear your comments and thoughts…..

Title: Swift and mutating struct

Body:
There is something that I don't entirely understand when it comes to mutating value types in Swift.

As the "The Swift Programming Language" iBook states:  By default, the properties of a value type cannot be modified from within its instance methods.

And so to make this possible we can declare methods with the mutating keyword inside structs and enums.

The thing that is not entirely clear to me is this:
You can change a var from outside a struct, but you cannot change it from its own methods. This seems counter-intuitive to me, as in Object Oriented languages, you generally try to encapsulate variables so they can only be changed from within. With structs this appears to be the other way around. To elaborate, here's a code snippet:

struct Point {
    var x = 0, y = 0
    mutating func moveToX(x: Int, andY y:Int) { //Needs to be a mutating method in order to work
        self.x = x
        self.y = y
    }
}

var p = Point(x: 1, y: 2)
p.x = 3 //Works from outside the struct!
p.moveToX(5, andY: 5)

Does anyone know the reason why structs cannot change their content from inside their own context, while the contents can easily be changed elsewhere?

Body:
SWIFT : Use of mutating function in Structs

Swift programmers developed Structs in such a way that properties of it can not be modified within Struct methods. For example, Check the code given below

struct City
{
  var population : Int
  func changePopulation(newpopulation : Int)
  {
      population = newpopulation //error: cannot modify property "popultion"
  }
}
  var mycity = City(population : 1000)
  mycity.changePopulation(newpopulation : 2000)

On executing the above code we get an error because we are trying to assign a new value to the property population of the Struct City. By default Structs properties can’t be mutated inside its own methods. This is how Apple Developers have built it, so that the Structs will have a static nature by default.

How do we solve it? What’s the alternative?

Mutating Keyword :

Declaring function as mutating inside Struct allows us to alter properties in Structs.
Line No : 5, of the above code changes to like this,

mutating changePopulation(newpopulation : Int)

Now we can assign the value of the newpopulation to property population to within the scope of the method.

Note :

let mycity = City(1000)
mycity.changePopulation(newpopulation : 2000)   //error: cannot modify property "popultion"

If we use let instead of var for Struct objects, then we can’t mutate the value of any properties, Also this is the reason why we get an error when we try to invoke mutating function using let instance. So it is better to use var whenever you are changing value of a property.

Would love to hear your comments and thoughts…..


问:
Windows initial execution context
Once Windows has loaded an executable in memory and transfert execution to the entry point, do values in registers and stack are meaningful? If so, where can I find more informations about it?</p>

答:
Officially, the registers at the entry point of PE file do not have defined values. You're supposed to use APIs, such as GetCommandLine to retrieve the information you need. However, since the kernel function that eventually transfers control to the entry point did not change much from the old days, some PE packers and malware started to rely on its peculiarities. The two more or less reliable registers are:

EAX points to the entry point of the application (because the kernel function uses call eax to jump to it)

EBX points to the Process Environment Block (PEB).

Title: Windows initial execution context


问:
How to handle SSL Certificate for Edge browser in protractor?
We have requirement to run automation test in Edge browser using protractor. I am able to lunch Edge through protector after gone through some references but now I am stuck in handling the SSL Certificate for Edge. Not getting any proper reference how to do this in Protractor. </p>

<p>It will be really help if any one can share any reference. </p>

答:
The ideal scenario here is to avoid using SSL during testing.

Generally, SSL termination is best handled by your outward facing webserver, rather than within your application. This has numerous advantages:

It makes developing and debugging your application easier

It makes testing easier, as you are seeing

It removes the overhead of SSL handshakes

I appreciate that you may not have control over this, or you might be testing something which requires SSL (you should probably move it into its own suite and find an alternative method of testing it), but that's the ideal.

If you're still stuck, I'd look at going into more detail about your problem - as you don't exactly specify what the problem you are encountering is, just that you're encountering a problem.

Body:
We have requirement to run automation test in Edge browser using protractor. I am able to lunch Edge through protector after gone through some references but now I am stuck in handling the SSL Certificate for Edge. Not getting any proper reference how to do this in Protractor.

It will be really help if any one can share any reference.


问:
Add method to decorator in Python
In this documentation about lru_cache I can see that there's the possibility to call a function on a decorator with the dot notation, for instance I can call:

```<code>lru_cache_decorated_func.cache_info()
</code>```

What I'm trying to achieve is make my own decorator with my custom function to call that works and is called like cache_info().

So how I can add  such a function to a decorator?

答:
A decorator is nothing more (or less) than a callable returning a callable[0] aka

@foo
def bar():
   ...
```

<p>is exactly the same as:</p>

<pre class="lang-py prettyprint-override"><code>def bar():
    ...
bar = foo(bar)
</code>```

There are various options to "smartify" decorators, what lru_cache does is pretty simple:

it wraps the decorated function in a wrapper function

it then sets to attributes on that wrapper function

and it returns the wrapper (swapping the original function for the wrapper)

import functools

def foo(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    wrapper.thing = 'yay'
    return wrapper

@foo
def bar(): ...

print(bar.thing)
```

will print yay.

[0] or even a not-callable, as is the case for @property or @cached_property.

Title: Add method to decorator in Python

Body:
In this documentation about lru_cache I can see that there's the possibility to call a function on a decorator with the dot notation, for instance I can call:

lru_cache_decorated_func.cache_info()

What I'm trying to achieve is make my own decorator with my custom function to call that works and is called like cache_info().

So how I can add  such a function to a decorator?

Body:
A decorator is nothing more (or less) than a callable returning a callable[0] aka

@foo
def bar():
   ...

is exactly the same as:

def bar():
    ...
bar = foo(bar)

There are various options to "smartify" decorators, what lru_cache does is pretty simple:

it wraps the decorated function in a wrapper function

it then sets to attributes on that wrapper function

and it returns the wrapper (swapping the original function for the wrapper)

import functools

def foo(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    wrapper.thing = 'yay'
    return wrapper

@foo
def bar(): ...

print(bar.thing)

will print yay.

[0] or even a not-callable, as is the case for @property or @cached_property.


问:
How can I pass a variable to a directive when extending Laravel Blade?
When creating a custom Laravel Blade directive how can I pass a variable in? At the moment the variable passed to the @svg() directive is not parsed and is treated as a string:

Blade view:

```<code>@svg($svg->url, 'fill-white')
</code>```

AppServiceProvider.php

```<code>    Blade::directive('svg', function ($arguments) {

        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");

            dd($path); // Outputs $svg->url

           // Required output = path/to/filename.svg

        });
</code>```

UPDATED CODE (Based on Andrei Dascalu's answer):

Blade template:

```<code> @php($svg = 'test.svg')
 @svg($svg, 'fill-white')
</code>```

AppServiceProvider:

```<code>       Blade::directive('svg', function ($arguments) {
            eval("\$params = [$arguments];");
           // Produces 'undefined variable $svg' error

            list($path, $class) = $params;
});
</code>```

答:
I believe you are looking for ways to pass multiple parameters, which should go like this:

```<code>eval("\$params = [$arguments];");
list($param1, $param2, $param3) = $params;
</code>```

That way you can call @mydirective($param1, $param2, $param3) and the closure will handle breaking the params apart from the single $arguments strings.

Body:
When creating a custom Laravel Blade directive how can I pass a variable in? At the moment the variable passed to the @svg() directive is not parsed and is treated as a string:

Blade view:

@svg($svg->url, 'fill-white')

AppServiceProvider.php

    Blade::directive('svg', function ($arguments) {

        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");

            dd($path); // Outputs $svg->url

           // Required output = path/to/filename.svg

        });

UPDATED CODE (Based on Andrei Dascalu's answer):

Blade template:

 @php($svg = 'test.svg')
 @svg($svg, 'fill-white')

AppServiceProvider:

       Blade::directive('svg', function ($arguments) {
            eval("\$params = [$arguments];");
           // Produces 'undefined variable $svg' error

            list($path, $class) = $params;
});

Body:
I believe you are looking for ways to pass multiple parameters, which should go like this:

eval("\$params = [$arguments];");
list($param1, $param2, $param3) = $params;

That way you can call @mydirective($param1, $param2, $param3) and the closure will handle breaking the params apart from the single $arguments strings.