问:
Exploring short ways in pandas to GROUPBY & JOIN without creating intermediate dataframes
In my attempt to curtail my code, I observed I quite often need to groupby and then join the grouped dataframe to the parent one.  Are there any ways to write a more elegant and concise code? Please check my example below:

Assume this parent dataframe: (you can copy and paste to play around)

```<code>chem_1=np.array([-5, 9, -1,4,-2,3,4,np.nan,np.nan,np.nan,8,np.nan,9])
chem_2=np.array([6, -1, -4,np.nan,-7,-5,5,np.nan,10,-9,8,6,np.nan])
frame_total=pd.DataFrame(list(zip(chem_1,chem_2)), columns=['chem_1', 'chem_2'])
frame_total['sum_hourly']=frame_total.sum(axis=1)
frame_total.loc[frame_total[['chem_1', 'chem_2']].isnull().all(1),'sum_hourly']=np.nan
frame_total.index=pd.date_range('2018-01-01', periods=13, freq='6H')
print(frame_total)

                     chem_1  chem_2  sum_hourly
2018-01-01 00:00:00    -5.0     6.0         1.0
2018-01-01 06:00:00     9.0    -1.0         8.0
2018-01-01 12:00:00    -1.0    -4.0        -5.0
2018-01-01 18:00:00     4.0     NaN         4.0
2018-01-02 00:00:00    -2.0    -7.0        -9.0
2018-01-02 06:00:00     3.0    -5.0        -2.0
2018-01-02 12:00:00     4.0     5.0         9.0
2018-01-02 18:00:00     NaN     NaN         NaN
2018-01-03 00:00:00     NaN    10.0        10.0
2018-01-03 06:00:00     NaN    -9.0        -9.0
2018-01-03 12:00:00     8.0     8.0        16.0
2018-01-03 18:00:00     NaN     6.0         6.0
2018-01-04 00:00:00     9.0     NaN         9.0
</code>```

EXAMPLE: A simple groupby and join is described below which will populate the column 'sum_24_a' that sums up the hourly sum values per calendar day. However, I recently found that I can shorten this by applying the second part of code, which populates the column 'sum_24_b'

```<code># first part: create a dataframe and then join to get column 'sum_24_a'
frame_sum=frame_total.groupby(frame_total.index.date)['sum_hourly'].sum().to_frame('sum_24_a')
frame_total=frame_total.join(frame_sum)

# second part: directly create column 'sum_24_b' without the need of joining
frame_total['sum_24_b']=frame_total['sum_hourly'].groupby(frame_total.index.date).sum()

print(frame_total)

                     chem_1  chem_2  sum_hourly  sum_24_a  sum_24_b
2018-01-01 00:00:00    -5.0     6.0         1.0       8.0       8.0
2018-01-01 06:00:00     9.0    -1.0         8.0       NaN       NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0       NaN       NaN
2018-01-01 18:00:00     4.0     NaN         4.0       NaN       NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0      -2.0      -2.0
2018-01-02 06:00:00     3.0    -5.0        -2.0       NaN       NaN
2018-01-02 12:00:00     4.0     5.0         9.0       NaN       NaN
2018-01-02 18:00:00     NaN     NaN         NaN       NaN       NaN
2018-01-03 00:00:00     NaN    10.0        10.0      23.0      23.0
2018-01-03 06:00:00     NaN    -9.0        -9.0       NaN       NaN
2018-01-03 12:00:00     8.0     8.0        16.0       NaN       NaN
2018-01-03 18:00:00     NaN     6.0         6.0       NaN       NaN
2018-01-04 00:00:00     9.0     NaN         9.0       9.0       9.0
</code>```

QUESTION: Is there a similar suggestion to perform the following more complex GROUPBY, AGG and JOIN without needing to create the 'frame_day' dataframe and then join it to the original, as shown below?

```<code>frame_day=frame_total.between_time('10:00:00', '16:00:00').\
          groupby(frame_total.between_time('10:00:00', '16:00:00').index.date)['sum_hourly'].\
          agg([('sum_day', lambda x: x.sum()), \
               ('positive_sum_day', lambda x: x[x>0].sum()), \
               ('negative_sum_day', lambda x: x[x<0].sum())])
frame_total=frame_total.join(frame_day)

print(frame_total.head(8))

                     chem_1  chem_2  sum_hourly  sum_24_a  sum_24_b  \
2018-01-01 00:00:00    -5.0     6.0         1.0       8.0       8.0
2018-01-01 06:00:00     9.0    -1.0         8.0       NaN       NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0       NaN       NaN
2018-01-01 18:00:00     4.0     NaN         4.0       NaN       NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0      -2.0      -2.0
2018-01-02 06:00:00     3.0    -5.0        -2.0       NaN       NaN
2018-01-02 12:00:00     4.0     5.0         9.0       NaN       NaN
2018-01-02 18:00:00     NaN     NaN         NaN       NaN       NaN

                     sum_day  positive_sum_day  negative_sum_day
2018-01-01 00:00:00     -5.0               0.0              -5.0
2018-01-01 06:00:00      NaN               NaN               NaN
2018-01-01 12:00:00      NaN               NaN               NaN
2018-01-01 18:00:00      NaN               NaN               NaN
2018-01-02 00:00:00      9.0               9.0               0.0
2018-01-02 06:00:00      NaN               NaN               NaN
2018-01-02 12:00:00      NaN               NaN               NaN
2018-01-02 18:00:00      NaN               NaN               NaN
</code>```

I hope my question and example are clear. Thank you in advance!

Body:
In my attempt to curtail my code, I observed I quite often need to groupby and then join the grouped dataframe to the parent one.  Are there any ways to write a more elegant and concise code? Please check my example below:

Assume this parent dataframe: (you can copy and paste to play around)

chem_1=np.array([-5, 9, -1,4,-2,3,4,np.nan,np.nan,np.nan,8,np.nan,9])
chem_2=np.array([6, -1, -4,np.nan,-7,-5,5,np.nan,10,-9,8,6,np.nan])
frame_total=pd.DataFrame(list(zip(chem_1,chem_2)), columns=['chem_1', 'chem_2'])
frame_total['sum_hourly']=frame_total.sum(axis=1)
frame_total.loc[frame_total[['chem_1', 'chem_2']].isnull().all(1),'sum_hourly']=np.nan
frame_total.index=pd.date_range('2018-01-01', periods=13, freq='6H')
print(frame_total)

                     chem_1  chem_2  sum_hourly
2018-01-01 00:00:00    -5.0     6.0         1.0
2018-01-01 06:00:00     9.0    -1.0         8.0
2018-01-01 12:00:00    -1.0    -4.0        -5.0
2018-01-01 18:00:00     4.0     NaN         4.0
2018-01-02 00:00:00    -2.0    -7.0        -9.0
2018-01-02 06:00:00     3.0    -5.0        -2.0
2018-01-02 12:00:00     4.0     5.0         9.0
2018-01-02 18:00:00     NaN     NaN         NaN
2018-01-03 00:00:00     NaN    10.0        10.0
2018-01-03 06:00:00     NaN    -9.0        -9.0
2018-01-03 12:00:00     8.0     8.0        16.0
2018-01-03 18:00:00     NaN     6.0         6.0
2018-01-04 00:00:00     9.0     NaN         9.0

EXAMPLE: A simple groupby and join is described below which will populate the column 'sum_24_a' that sums up the hourly sum values per calendar day. However, I recently found that I can shorten this by applying the second part of code, which populates the column 'sum_24_b'

# first part: create a dataframe and then join to get column 'sum_24_a'
frame_sum=frame_total.groupby(frame_total.index.date)['sum_hourly'].sum().to_frame('sum_24_a')
frame_total=frame_total.join(frame_sum)

# second part: directly create column 'sum_24_b' without the need of joining
frame_total['sum_24_b']=frame_total['sum_hourly'].groupby(frame_total.index.date).sum()

print(frame_total)

                     chem_1  chem_2  sum_hourly  sum_24_a  sum_24_b
2018-01-01 00:00:00    -5.0     6.0         1.0       8.0       8.0
2018-01-01 06:00:00     9.0    -1.0         8.0       NaN       NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0       NaN       NaN
2018-01-01 18:00:00     4.0     NaN         4.0       NaN       NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0      -2.0      -2.0
2018-01-02 06:00:00     3.0    -5.0        -2.0       NaN       NaN
2018-01-02 12:00:00     4.0     5.0         9.0       NaN       NaN
2018-01-02 18:00:00     NaN     NaN         NaN       NaN       NaN
2018-01-03 00:00:00     NaN    10.0        10.0      23.0      23.0
2018-01-03 06:00:00     NaN    -9.0        -9.0       NaN       NaN
2018-01-03 12:00:00     8.0     8.0        16.0       NaN       NaN
2018-01-03 18:00:00     NaN     6.0         6.0       NaN       NaN
2018-01-04 00:00:00     9.0     NaN         9.0       9.0       9.0

QUESTION: Is there a similar suggestion to perform the following more complex GROUPBY, AGG and JOIN without needing to create the 'frame_day' dataframe and then join it to the original, as shown below?

frame_day=frame_total.between_time('10:00:00', '16:00:00').\
          groupby(frame_total.between_time('10:00:00', '16:00:00').index.date)['sum_hourly'].\
          agg([('sum_day', lambda x: x.sum()), \
               ('positive_sum_day', lambda x: x[x>0].sum()), \
               ('negative_sum_day', lambda x: x[x<0].sum())])
frame_total=frame_total.join(frame_day)

print(frame_total.head(8))

                     chem_1  chem_2  sum_hourly  sum_24_a  sum_24_b  \
2018-01-01 00:00:00    -5.0     6.0         1.0       8.0       8.0
2018-01-01 06:00:00     9.0    -1.0         8.0       NaN       NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0       NaN       NaN
2018-01-01 18:00:00     4.0     NaN         4.0       NaN       NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0      -2.0      -2.0
2018-01-02 06:00:00     3.0    -5.0        -2.0       NaN       NaN
2018-01-02 12:00:00     4.0     5.0         9.0       NaN       NaN
2018-01-02 18:00:00     NaN     NaN         NaN       NaN       NaN

                     sum_day  positive_sum_day  negative_sum_day
2018-01-01 00:00:00     -5.0               0.0              -5.0
2018-01-01 06:00:00      NaN               NaN               NaN
2018-01-01 12:00:00      NaN               NaN               NaN
2018-01-01 18:00:00      NaN               NaN               NaN
2018-01-02 00:00:00      9.0               9.0               0.0
2018-01-02 06:00:00      NaN               NaN               NaN
2018-01-02 12:00:00      NaN               NaN               NaN
2018-01-02 18:00:00      NaN               NaN               NaN

I hope my question and example are clear. Thank you in advance!

Body:
Regarding the first question here's a solution.   You can drop the date column later if you don't need it.

frame_total['date'] = frame_total.index.date
frame_total['sum_24_a'] = frame_total.groupby('date')['sum_hourly'].sum()
print(frame_total)

                     chem_1  chem_2  sum_hourly        date  sum_24_a
2018-01-01 00:00:00    -5.0     6.0         1.0  2018-01-01       8.0
2018-01-01 06:00:00     9.0    -1.0         8.0  2018-01-01       NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0  2018-01-01       NaN
2018-01-01 18:00:00     4.0     NaN         4.0  2018-01-01       NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0  2018-01-02      -2.0
2018-01-02 06:00:00     3.0    -5.0        -2.0  2018-01-02       NaN
2018-01-02 12:00:00     4.0     5.0         9.0  2018-01-02       NaN
2018-01-02 18:00:00     NaN     NaN         NaN  2018-01-02       NaN
2018-01-03 00:00:00     NaN    10.0        10.0  2018-01-03      23.0
2018-01-03 06:00:00     NaN    -9.0        -9.0  2018-01-03       NaN
2018-01-03 12:00:00     8.0     8.0        16.0  2018-01-03       NaN
2018-01-03 18:00:00     NaN     6.0         6.0  2018-01-03       NaN
2018-01-04 00:00:00     9.0     NaN         9.0  2018-01-04       9.0

Regarding the second question, here's a simple way to generate the 'sum_day' column. The others may be built in the same way:

frame_total['sum_day'] = frame_total.loc[
    frame_total.between_time('10:00:00', '16:00:00').index] \
    .groupby('date')['sum_hourly'].agg('sum')
print(frame_total.head(8))

                     chem_1  chem_2  sum_hourly        date  sum_24_a  sum_day
2018-01-01 00:00:00    -5.0     6.0         1.0  2018-01-01       8.0     -5.0
2018-01-01 06:00:00     9.0    -1.0         8.0  2018-01-01       NaN      NaN
2018-01-01 12:00:00    -1.0    -4.0        -5.0  2018-01-01       NaN      NaN
2018-01-01 18:00:00     4.0     NaN         4.0  2018-01-01       NaN      NaN
2018-01-02 00:00:00    -2.0    -7.0        -9.0  2018-01-02      -2.0      9.0
2018-01-02 06:00:00     3.0    -5.0        -2.0  2018-01-02       NaN      NaN
2018-01-02 12:00:00     4.0     5.0         9.0  2018-01-02       NaN      NaN
2018-01-02 18:00:00     NaN     NaN         NaN  2018-01-02       NaN      NaN


来源: stackexchange

问:
passing string around question
I have a member function like

```<code>setResult(const std::string &s)
{
         this->m_result = s;
}
</code>```

After checking, I found this->m_result's address is the same as s. Will m_result disappear (or become garbage) when s goes out of scope if s is a stack object?

答:
Effectively s is no stack object, as it's a reference (the reference itself is a stack object, but the string is not). Actually this->m_result can only have the same address as s, if you passed this->m_result to testResult, but although self-assignment is quite useless, in this case it doesn't do any harm.

EDIT: Another case could be, that this->m_result is not a std::string but a reference to it. Then you got a problem as you got a reference to a destroyed object. Remember, a reference is nothing more than a pointer (just more comfortable to use and with reduced functionalty).

ContentLicense: CC BY-SA 3.0

Title: passing string around question

Body:
I have a member function like

setResult(const std::string &s)
{
         this->m_result = s;
}

After checking, I found this->m_result's address is the same as s. Will m_result disappear (or become garbage) when s goes out of scope if s is a stack object?


问:
How we get the data and show like viewdidload using swiftUI
i'm trying to work with swiftUI but i'm having an issue. i want to fetch the data from firebase and show that data to the list. i used mutating function to modify the variable. now when i called that function than it give me error. how i can solve this please help me. below are the code i'm using.

```<code>struct UserListView : View {

var body: some View{
    VStack{
        List{
            VStack(alignment:.leading){
                HStack{
                    Text("Favroute").frame(alignment: .leading).padding(.leading, 20)
                    Spacer()
                    Text("All").frame(alignment: .trailing)
                }
            ScrollView(.horizontal, content: {
                HStack(spacing: 10) {
                    ForEach(0..<10) { index in
                        StatusView(statusImage: "nature")
                    }
                }
                .padding(.leading, 10)
            })
                .frame(height: 190)
            }

            ForEach(0..<10){_ in
                HStack{
                    Group{
                        NavigationLink(destination: ChatView()){
                            UserImageView(imageName: "profileDummy").padding(.leading, 5)
                            Text("User Name").padding(.leading,10)
                        }
                    }
                }.frame( height: 40)
            }.environment(\.defaultMinListRowHeight, 40)
        }
    }
    .navigationBarTitle("UserList",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}

var userDataList = [UserModel]()
mutating func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}
</code>```

}

below are the error message i'm getting:

```<code>Cannot use mutating member on immutable value: 'self' is immutable
</code>```

答: You should declare your userDataList property like so @State var userDataList = [UserModel](). This way this property will be stored by SwiftUI outside of your struct and can be mutated.

ContentLicense: CC BY-SA 4.0

Body:
i'm trying to work with swiftUI but i'm having an issue. i want to fetch the data from firebase and show that data to the list. i used mutating function to modify the variable. now when i called that function than it give me error. how i can solve this please help me. below are the code i'm using.

struct UserListView : View {

var body: some View{
    VStack{
        List{
            VStack(alignment:.leading){
                HStack{
                    Text("Favroute").frame(alignment: .leading).padding(.leading, 20)
                    Spacer()
                    Text("All").frame(alignment: .trailing)
                }
            ScrollView(.horizontal, content: {
                HStack(spacing: 10) {
                    ForEach(0..<10) { index in
                        StatusView(statusImage: "nature")
                    }
                }
                .padding(.leading, 10)
            })
                .frame(height: 190)
            }

            ForEach(0..<10){_ in
                HStack{
                    Group{
                        NavigationLink(destination: ChatView()){
                            UserImageView(imageName: "profileDummy").padding(.leading, 5)
                            Text("User Name").padding(.leading,10)
                        }
                    }
                }.frame( height: 40)
            }.environment(\.defaultMinListRowHeight, 40)
        }
    }
    .navigationBarTitle("UserList",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}

var userDataList = [UserModel]()
mutating func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}

}

below are the error message i'm getting:

Cannot use mutating member on immutable value: 'self' is immutable


问:
Processing Data by Datatype in Pandas
I have a DataFrame containing int and str data which I have to process through.

I would like to separate the text and the numerical values in each cell into separate columns, so that I can compute on the numerical data.

My columns are similar to this:

I have read about doing something like this through the apply function and applymap function, but I can't design such a function as I am new to pandas. It should basically do -

```<code>def separator():
       if cell has str:
           Add str part to another column(Check column), leave int inplace.
       else:
           Add 'NA' to Check column
</code>```

答:
You can do this using extract with a followed to_numeric:

```<code>import pandas as pd

df = pd.DataFrame({'a_mrk4': ['042FP', '077', '079', '1234A-BC D..EF']})

df[['a_mrk4', 'Check']] = df['a_mrk4'].str.extract(r'(\d+)(.*)')
df['a_mrk4'] = pd.to_numeric(df['a_mrk4'])
print(df)
</code>```

Output:

```<code>   a_mrk4       Check
0      42          FP
1      77
2      79
3    1234  A-BC D..EF
</code>```

Title: Processing Data by Datatype in Pandas

Body:
I have a DataFrame containing int and str data which I have to process through.

I would like to separate the text and the numerical values in each cell into separate columns, so that I can compute on the numerical data.

My columns are similar to this:

I have read about doing something like this through the apply function and applymap function, but I can't design such a function as I am new to pandas. It should basically do -

def separator():
       if cell has str:
           Add str part to another column(Check column), leave int inplace.
       else:
           Add 'NA' to Check column

Body:
You can do this using extract with a followed to_numeric:

import pandas as pd

df = pd.DataFrame({'a_mrk4': ['042FP', '077', '079', '1234A-BC D..EF']})

df[['a_mrk4', 'Check']] = df['a_mrk4'].str.extract(r'(\d+)(.*)')
df['a_mrk4'] = pd.to_numeric(df['a_mrk4'])
print(df)

Output:

   a_mrk4       Check
0      42          FP
1      77
2      79
3    1234  A-BC D..EF


问:
Components alignment in android studio's layout preview does not match with what the device shows
Preview of Android Studio's Layout

Preview of Device's Layout

As you can see in the pictures above, the alignment of the components is properly arranged but when it is run it appears that the bottom components (TextView and a Switch) are cut. Is there something I must do so that my components' alignment in the android studio's layout shows exactly what I will see when I use the application on my device?

My device is Samsung SM-G610Y. Resolution: 1080 by 1920; Diagonal: 5.5 inches; Android 6.1 (Marshmallow).
These are also the specifications I "plugged-in" when creating the Android Virtual Device.

This is the XML file of the layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible">

            <Button
                android:id="@+id/editAlarm1"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime1"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm2"
                app:layout_constraintEnd_toStartOf="@+id/alarmText1"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime2"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm3"
                app:layout_constraintEnd_toStartOf="@+id/alarmText2"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm3"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime3"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm4"
                app:layout_constraintEnd_toStartOf="@+id/alarmText3"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm4"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="65dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime4"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@+id/alarmText4"
                tools:visibility="visible" />

            <Switch
                android:id="@+id/alarmSwitch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText1"
                app:layout_constraintTop_toTopOf="@+id/alarmText1"
                tools:visibility="visible" />

            <Switch
                android:id="@+id/alarmSwitch2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText2"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText2"
                app:layout_constraintTop_toTopOf="@+id/alarmText2" />

            <Switch
                android:id="@+id/alarmSwitch3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText3"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText3"
                app:layout_constraintTop_toTopOf="@+id/alarmText3" />

            <Switch
                android:id="@+id/alarmSwitch4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText4"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText4"
                app:layout_constraintTop_toTopOf="@+id/alarmText4" />

            <TextView
                android:id="@+id/alarmText1"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginTop="125dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText2"
                app:layout_constraintStart_toEndOf="@+id/alarmText4"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/alarmText2"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText3"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/alarmText3"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText4"
                app:layout_constraintStart_toEndOf="@+id/alarmText2"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/alarmText4"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="50dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toEndOf="@+id/alarmText3"
                app:layout_constraintStart_toStartOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>

    <Button
        android:id="@+id/editButton"
        android:layout_width="56dp"
        android:layout_height="35dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:text="EDIT"
        android:textAllCaps="false"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnGo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to Quiz Activity"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
The reason for that is screen density.
Even if you have 2 devices with the same screen resolution of 1080x1920px, and same screen size of 5.5" they will still show the layout differently if the screen density is different.

To understand better the difference between screen size, resolution and density, you can read this answer https://stackoverflow.com/a/22397095/3046181

Edit: Following your comment, if you want to show the full screen and no action bar you need to do the following steps:

Add to your styles.xml the NoActionBar parent:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>
</code>```

Then make sure that your application tag in manifest sets this style:

```<code><application android:theme="@style/AppTheme"></application>
</code>```

Then also add to your code in onCreate of the activity before you inflate the layout of your activity:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
</code>```

Body:
Preview of Android Studio's Layout

Preview of Device's Layout

As you can see in the pictures above, the alignment of the components is properly arranged but when it is run it appears that the bottom components (TextView and a Switch) are cut. Is there something I must do so that my components' alignment in the android studio's layout shows exactly what I will see when I use the application on my device?

My device is Samsung SM-G610Y. Resolution: 1080 by 1920; Diagonal: 5.5 inches; Android 6.1 (Marshmallow).
These are also the specifications I "plugged-in" when creating the Android Virtual Device.

This is the XML file of the layout.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible">

            <Button
                android:id="@+id/editAlarm1"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime1"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm2"
                app:layout_constraintEnd_toStartOf="@+id/alarmText1"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm2"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime2"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm3"
                app:layout_constraintEnd_toStartOf="@+id/alarmText2"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm3"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="120dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime3"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/editAlarm4"
                app:layout_constraintEnd_toStartOf="@+id/alarmText3"
                tools:visibility="visible" />

            <Button
                android:id="@+id/editAlarm4"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="65dp"
                android:background="@android:drawable/ic_menu_edit"
                android:onClick="setTime4"
                android:textSize="0sp"
                android:visibility="invisible"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@+id/alarmText4"
                tools:visibility="visible" />

            <Switch
                android:id="@+id/alarmSwitch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText1"
                app:layout_constraintTop_toTopOf="@+id/alarmText1"
                tools:visibility="visible" />

            <Switch
                android:id="@+id/alarmSwitch2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText2"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText2"
                app:layout_constraintTop_toTopOf="@+id/alarmText2" />

            <Switch
                android:id="@+id/alarmSwitch3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText3"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText3"
                app:layout_constraintTop_toTopOf="@+id/alarmText3" />

            <Switch
                android:id="@+id/alarmSwitch4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:height="40sp"
                android:gravity="center_horizontal|center_vertical"
                android:hapticFeedbackEnabled="false"
                android:scrollbarSize="4dp"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="@+id/alarmText4"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.75"
                app:layout_constraintStart_toEndOf="@+id/alarmText4"
                app:layout_constraintTop_toTopOf="@+id/alarmText4" />

            <TextView
                android:id="@+id/alarmText1"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginTop="125dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText2"
                app:layout_constraintStart_toEndOf="@+id/alarmText4"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/alarmText2"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText3"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/alarmText3"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="90dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toTopOf="@+id/alarmText4"
                app:layout_constraintStart_toEndOf="@+id/alarmText2"
                app:layout_constraintStart_toStartOf="parent" />

            <TextView
                android:id="@+id/alarmText4"
                android:layout_width="159dp"
                android:layout_height="49dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:layout_marginBottom="50dp"
                android:text="@string/default_alarm_time"
                android:textSize="35sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toEndOf="@+id/alarmText3"
                app:layout_constraintStart_toStartOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>

    <Button
        android:id="@+id/editButton"
        android:layout_width="56dp"
        android:layout_height="35dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:text="EDIT"
        android:textAllCaps="false"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnGo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to Quiz Activity"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
The reason for that is screen density.
Even if you have 2 devices with the same screen resolution of 1080x1920px, and same screen size of 5.5" they will still show the layout differently if the screen density is different.

To understand better the difference between screen size, resolution and density, you can read this answer https://stackoverflow.com/a/22397095/3046181

Edit: Following your comment, if you want to show the full screen and no action bar you need to do the following steps:

Add to your styles.xml the NoActionBar parent:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>

Then make sure that your application tag in manifest sets this style:

<application android:theme="@style/AppTheme"></application>

Then also add to your code in onCreate of the activity before you inflate the layout of your activity:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);


问:
How do I package and run a simple command-line application with dependencies using maven?
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

```<code>java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App
</code>```

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

答:
You can make a jar executable by adding the Main-Class attribute to its manifest file. In Maven this is done by the archiver plugin. To add the Main-Class attribute, add this to your pom.xml:

```<code> <build>
   <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <mainClass>com.mycompany.app.App</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
 </build>
</code>```

You can now run your jar with the command: java -jar myjar.jar or by double clicking on it (not available in all platforms).

Body:
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

Body:
You can make a jar executable by adding the Main-Class attribute to its manifest file. In Maven this is done by the archiver plugin. To add the Main-Class attribute, add this to your pom.xml:

 <build>
   <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <mainClass>com.mycompany.app.App</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
 </build>

You can now run your jar with the command: java -jar myjar.jar or by double clicking on it (not available in all platforms).


问:
Set MySQL timestamp to random time within past 24 hours
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

```<code>UPDATE table SET timestamp =
</code>```

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

答:
You can use Unixtimestqamps for that</p>

```<code>UPDATE table1
    SET timestamp = (SELECT TIMESTAMPADD(SECOND,
          FLOOR(RAND() * TIMESTAMPDIFF(SECOND, NOW() - INTERVAL 1 DAY, NOW()))
          , NOW() - INTERVAL 1 DAY));
</code>```

Body:
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

UPDATE table SET timestamp =

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

Body:
You can use Unixtimestqamps for that

UPDATE table1
    SET timestamp = (SELECT TIMESTAMPADD(SECOND,
          FLOOR(RAND() * TIMESTAMPDIFF(SECOND, NOW() - INTERVAL 1 DAY, NOW()))
          , NOW() - INTERVAL 1 DAY));


问:
C++ static initialization of stateless class
Suppose I have a class T where

T has no virtual functions.

T instances have no state.

T has static member instances of itself.

T itself has no other state.

Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should not matter because T objects are stateless.

I'm interested in doing this for enum-like classes like so:

```<code>// Switch.h

class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};
</code>```

```<code>// Switch.cpp

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}
</code>```

答: To answer the first part of your question, if T has a constructor which has side effects then you can in fact get burned by static initialization fiasco.

Body:
Suppose I have a class T where

T has no virtual functions.

T instances have no state.

T has static member instances of itself.

T itself has no other state.

Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should not matter because T objects are stateless.

I'm interested in doing this for enum-like classes like so:

// Switch.h

class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};

// Switch.cpp

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}


问:
Change GPU quota on Google Cloud Platform
I am trying to change the quota for the number of GPUs I can use on a project on the Google Cloud Platform. Thing is I've made requests before on a different account and they all went through.

This is a brand new account about 5 days old and even though I've upgraded my billing the requests are still denied. I reached out for feedback and the response was

Unfortunately, we are unable to grant your quota increase due to insufficient service usage history

I've reached out to their sales team but they haven't gotten back to me yet and I've tried putting in that I just created the account and upgraded billing in the justification for the request as mentioned here.

Does anyone know how to get requests to edit quotas on brand new accounts approved?

答:
After some chatting with the Google Cloud Platform Billing Support, the basic answer is no, there's no way to increase quotas on a new account.

The last bit of correspondence and essentially the official response:

I was able to check with the downstream team the information |Support officer name here|
provided you and before your projects can get their GPU quota
increased it needs to accumulate more billing history. In my
experience I would recommend you to try again and request the quota
increase.

The issue is that new accounts don't have enough billing history or tenure to request quotas and one billing cycle has to pass in order for that information to be made available. I also asked if this is a policy that would change in the future to which the response was:

Google has a very sensitive policy specifically regarding the quotas
for GPU's, meaning this limitation on the product will continue to
work this way since the only way to generate tenure on an account is
by generating billing history.


问:
Kaitai (KSY) - optional attribute
I'm trying to describe SSH protocol in Kaitai language (.ksy file).
At the beginning, there is a protocol version exchange in the following format:

```<code>SSH-protoversion-softwareversion SP comments CR LF
</code>```

where SP comments is optional. AFAIK, there is not way of describing attribute as fully optional, only via if condition. Does anybody know how to describe this relation in Kaitai, so that parser accepts also this format: SSH-protoversion-softwareversion CR LF?

Thanks

答:
Kaitai Struct is not designed to be what you would call a grammar in its traditional meaning (i.e. something mapping to a regular language, context-free grammar, BNF, or something similar). Traditional grammars have notion of "this element being optional" or "this element can be repeated multiple times", but KS works the other way around: it's not even attempting to solve the ambiguility problem, but rather builds on a fact that all binary formats are designed to be non-ambiguous.

So, whenever you're encountering something like "optional element" or "repeated element" without any further context, please take a pause and consider if Kaitai Struct is a right tool for the task, and is it really a binary format you're trying to parse. For example, parsing something like JSON or XML or YAML might be theoretically possible with KS, but the result will be not of much use.

That said, in this particular case, it's perfectly possible to use Kaitai Struct, you'll just need to think on how a real-life binary parser will handle this. From my understanding, a real-life parser will read the whole line until the CR byte, and then will do a second pass at trying to interpret the contents of that line. You can model that in KS using something like that:

```<code>seq:
  - id: line
    terminator: 0xd # CR
    type: version_line
    # ^^^ this creates a substream with all bytes up to CR byte
  - id: reserved_lf
    contents: [0xa]
types:
  version_line:
    seq:
      - id: magic
        contents: 'SSH-'
      - id: proto_version
        type: str
        terminator: 0x2d # '-'
      - id: software_version
        type: str
        terminator: 0x20 # ' '
        eos-error: false
        # ^^^ if we don't find that space and will just hit end of stream, that's fine
      - id: comments
        type: str
        size-eos: true
        # ^^^ if we still have some data in the stream, that's all comment
</code>```

If you want to get null instead of empty string for comments when they're not included, just add extra if: not _io.eof for the comments attribute.

Title: Kaitai (KSY) - optional attribute

Body:
I'm trying to describe SSH protocol in Kaitai language (.ksy file).
At the beginning, there is a protocol version exchange in the following format:

SSH-protoversion-softwareversion SP comments CR LF

where SP comments is optional. AFAIK, there is not way of describing attribute as fully optional, only via if condition. Does anybody know how to describe this relation in Kaitai, so that parser accepts also this format: SSH-protoversion-softwareversion CR LF?

Thanks

Body:
Kaitai Struct is not designed to be what you would call a grammar in its traditional meaning (i.e. something mapping to a regular language, context-free grammar, BNF, or something similar). Traditional grammars have notion of "this element being optional" or "this element can be repeated multiple times", but KS works the other way around: it's not even attempting to solve the ambiguility problem, but rather builds on a fact that all binary formats are designed to be non-ambiguous.

So, whenever you're encountering something like "optional element" or "repeated element" without any further context, please take a pause and consider if Kaitai Struct is a right tool for the task, and is it really a binary format you're trying to parse. For example, parsing something like JSON or XML or YAML might be theoretically possible with KS, but the result will be not of much use.

That said, in this particular case, it's perfectly possible to use Kaitai Struct, you'll just need to think on how a real-life binary parser will handle this. From my understanding, a real-life parser will read the whole line until the CR byte, and then will do a second pass at trying to interpret the contents of that line. You can model that in KS using something like that:

seq:
  - id: line
    terminator: 0xd # CR
    type: version_line
    # ^^^ this creates a substream with all bytes up to CR byte
  - id: reserved_lf
    contents: [0xa]
types:
  version_line:
    seq:
      - id: magic
        contents: 'SSH-'
      - id: proto_version
        type: str
        terminator: 0x2d # '-'
      - id: software_version
        type: str
        terminator: 0x20 # ' '
        eos-error: false
        # ^^^ if we don't find that space and will just hit end of stream, that's fine
      - id: comments
        type: str
        size-eos: true
        # ^^^ if we still have some data in the stream, that's all comment

If you want to get null instead of empty string for comments when they're not included, just add extra if: not _io.eof for the comments attribute.


问:
Will react re-render only children in which some part of the state has changed or are all children that use the state are re-rendered?
Consider the following scenario in a component.

```<code>export default class Dummy extends React.Component{
       state = {
          A: some data
          B: other data
          C: extra data
       }

       somefunction = () => {
           this.setState({A: changed Data});
       }

       render(){
            return(
                 <ChildA data={this.state.A} callBackFunction={this.somefunction}/>
                 <ChildB data={this.state.B}/>
                 <ChildC data={this.state.C}/>
            );
       }
}
</code>```

That is, if State 'A' is changed, will ChildA only be re-rendered (because it is only associated with 'A') or all the children be re-rendered (because they are associated with state in general)?

答:
Theoretically this some function will invoke render method which result in rendering of all child components. </p>

<p>Try should component updates, useMemo, React.memo etc to control the defending of individual components. </p>

Body:
Consider the following scenario in a component.

export default class Dummy extends React.Component{
       state = {
          A: some data
          B: other data
          C: extra data
       }

       somefunction = () => {
           this.setState({A: changed Data});
       }

       render(){
            return(
                 <ChildA data={this.state.A} callBackFunction={this.somefunction}/>
                 <ChildB data={this.state.B}/>
                 <ChildC data={this.state.C}/>
            );
       }
}

That is, if State 'A' is changed, will ChildA only be re-rendered (because it is only associated with 'A') or all the children be re-rendered (because they are associated with state in general)?

Body:
Theoretically this some function will invoke render method which result in rendering of all child components.

Try should component updates, useMemo, React.memo etc to control the defending of individual components.


答:
you can use regular expressions, let's say that you have a column (target_col) and the data follow the pattern digits+text then you can use the following column </p>

```<code>df.target_col.str.extractall(r'(/d)(/w)')
</code>```

<p>you can tweak the re to match your specific needs </p>

Title: Processing Data by Datatype in Pandas

Body:
you can use regular expressions, let's say that you have a column (target_col) and the data follow the pattern digits+text then you can use the following column

df.target_col.str.extractall(r'(/d)(/w)')

you can tweak the re to match your specific needs


问:
Geo distance Search MYSQL
I'm doing a geo search with mysql using the spatial extension. FOr that i did a stored procedure (thats work really well when i tri on command line in mysql like that

mysql> CALL
  test2(GeomFromText('POINT(-0.93961472
  43.52843475)'),0.6 );

```<code>DROP PROCEDURE `test2`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `test2`(IN center2 point,IN dist int)
BEGIN
SET @center = center2;
SET @radius = dist;

SET @bbox = CONCAT('POLYGON((',
 X(@center) - @radius, ' ', Y(@center) - @radius, ',',
 X(@center) + @radius, ' ', Y(@center) - @radius, ',',
 X(@center) + @radius, ' ', Y(@center) + @radius, ',',
 X(@center) - @radius, ' ', Y(@center) + @radius, ',',
 X(@center) - @radius, ' ', Y(@center) - @radius, '))'
);

SELECT professionnels.*, AsText(coord)
FROM professionnels
WHERE Intersects( coord, GeomFromText(@bbox) )
AND SQRT(POW( ABS( X(coord) - X(@center)), 2) + POW( ABS(Y(coord) - Y(@center)), 2 )) < @radius limit 20;
end
</code>```

But the problem is that i need to call that from php. and when i do it, an error is return said that

PROCEDURE test2 can't return a result
  set in the given context

So.. How can i use a turn around to return a set of data ?

Thanks

答:
You can change the last part into

```<code>/*delete all rows from temp_table*/
DELETE FROM temp_table WHERE temp_table.somefield is not null;

INSERT INTO temp_table
  SELECT professionnels.*, AsText(coord)
  FROM professionnels
  WHERE Intersects( coord, GeomFromText(@bbox) )
  AND SQRT(POW( ABS( X(coord) - X(@center)), 2)
      + POW( ABS(Y(coord) - Y(@center)), 2 )) < @radius limit 20;
</code>```

Then you can select from the temp_table and find resultset there.

Title: Geo distance Search MYSQL

Body:
I'm doing a geo search with mysql using the spatial extension. FOr that i did a stored procedure (thats work really well when i tri on command line in mysql like that

mysql> CALL
  test2(GeomFromText('POINT(-0.93961472
  43.52843475)'),0.6 );

DROP PROCEDURE `test2`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `test2`(IN center2 point,IN dist int)
BEGIN
SET @center = center2;
SET @radius = dist;

SET @bbox = CONCAT('POLYGON((',
 X(@center) - @radius, ' ', Y(@center) - @radius, ',',
 X(@center) + @radius, ' ', Y(@center) - @radius, ',',
 X(@center) + @radius, ' ', Y(@center) + @radius, ',',
 X(@center) - @radius, ' ', Y(@center) + @radius, ',',
 X(@center) - @radius, ' ', Y(@center) - @radius, '))'
);

SELECT professionnels.*, AsText(coord)
FROM professionnels
WHERE Intersects( coord, GeomFromText(@bbox) )
AND SQRT(POW( ABS( X(coord) - X(@center)), 2) + POW( ABS(Y(coord) - Y(@center)), 2 )) < @radius limit 20;
end

But the problem is that i need to call that from php. and when i do it, an error is return said that

PROCEDURE test2 can't return a result
  set in the given context

So.. How can i use a turn around to return a set of data ?

Thanks

Body:
You can change the last part into

/*delete all rows from temp_table*/
DELETE FROM temp_table WHERE temp_table.somefield is not null;

INSERT INTO temp_table
  SELECT professionnels.*, AsText(coord)
  FROM professionnels
  WHERE Intersects( coord, GeomFromText(@bbox) )
  AND SQRT(POW( ABS( X(coord) - X(@center)), 2)
      + POW( ABS(Y(coord) - Y(@center)), 2 )) < @radius limit 20;

Then you can select from the temp_table and find resultset there.


问:
Why i have Cannot read property 'addEventListener' of null error?
HTML:

```<code> <body>
<script src="dynamic.js"></script>
<nav>
  <label id="logo">My Life</label>
  <ul id="test">
    <li>
      <a href="#" id="change">Home</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">News</a>
    </li>
    <li>
      <a href="#">Feedback</a>
    </li>
    <li>
      <a href="#" class="active">Log in</a>
    </li>
  </ul>
</nav>
</code>```

JavaScript:

```<code>const change = document.getElementById("change");
change.addEventListener("mouseover", () => changeFont());
change.addEventListener("mouseout", () => normalFont());

function changeFont() {
  change.style.fontSize = "25px";
}

function normalFont() {
  change.style.fontSize = "15px";
}
</code>```

I have simple navigation bar and when i decide to make it more interesting with hover effect I decide to be with JS NOT CSS and when i run the code in chrome i have a "Cannot read property 'addEventListener' of null" error and I can't figure out why?

I need some help ...

答: Because

Body:
HTML:

  My Life

      Home

      Contact

      News

      Feedback

      Log in

JavaScript:

const change = document.getElementById("change");
change.addEventListener("mouseover", () => changeFont());
change.addEventListener("mouseout", () => normalFont());

function changeFont() {
  change.style.fontSize = "25px";
}

function normalFont() {
  change.style.fontSize = "15px";
}

I have simple navigation bar and when i decide to make it more interesting with hover effect I decide to be with JS NOT CSS and when i run the code in chrome i have a "Cannot read property 'addEventListener' of null" error and I can't figure out why?

I need some help ...

Body: Because <script> in the beggining of the file. So when it executes element change is not loaded and so variable is null. Put your script in the end of the document or set the attribute defer. Scripts with this attribute wait when the DOM will be loaded and after that execute.


问:
Dynamic cell height programmatically
Is it possible to make a dynamic cell height programmatically and only using a frames?
Without constraints, autolayout and external libraries!

In this custom tableView cell, i set frame for label with calculating height for text label:

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    makeLayout()
}

func makeLayout() {
    let sizeLabel = descriptionLabel.sizeThatFits(bounds.size)
    descriptionLabel.frame = CGRect(x: 0, y: 0, width: bounds.width, height: sizeLabel.height)
}
</code>```

I have view controller with tableView, where i implement his delegate with return automaticDimension, but it doesn't work

答:
Yes,
You will have to return the height programmatically by implementing the
UITableViewDelegate function</p>

Title: Dynamic cell height programmatically

Body:
Is it possible to make a dynamic cell height programmatically and only using a frames?
Without constraints, autolayout and external libraries!

In this custom tableView cell, i set frame for label with calculating height for text label:

override func layoutSubviews() {
    super.layoutSubviews()
    makeLayout()
}

func makeLayout() {
    let sizeLabel = descriptionLabel.sizeThatFits(bounds.size)
    descriptionLabel.frame = CGRect(x: 0, y: 0, width: bounds.width, height: sizeLabel.height)
}

I have view controller with tableView, where i implement his delegate with return automaticDimension, but it doesn't work


问:
why dont set this value?
I want set my gorterilecekkart variable in code, but it will not change. It always sees the first value instead. How can I solve this problem? Please help me. I don't know English very well sorry. But in my code I have added comments.

```<code> class Sahnem : AppCompatActivity() {

     var gorterilecekkart=5

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_sahnem)

            val parsUser = ParseUser.getCurrentUser().email
            val queryTercih = ParseQuery.getQuery<ParseObject>("Tercih")
            queryTercih.whereEqualTo("user", parsUser.toString())

            queryTercih.findInBackground { objects, e ->

                if (objects.isEmpty()){

                }else{

                    var bas:String=objects[0].get("basla").toString()
                    var bit:String=objects[0].get("bitir").toString()

                    txvBasla.setText(bas)
                    txvBitir.setText(bit)

                    bitir=bit.toInt()
                    baslat=bas.toInt()

                    gorterilecekkart=bitir-baslat // i see log 3
                }

                println("116 "+bitir)

                gorterilecekkart=bitir-baslat

                println("119 "+gorterilecekkart)  //  i see  log 3

            }

            println("124 "+gorterilecekkart) // why i dont see log 3, i see 5
</code>```

答:
It looks like ParseQuery#findInBackground(...) runs the callback lambda in a background thread. Documentation here.

This means that:

```<code>println("124 "+gorterilecekkart) // why i dont see log 3, i see 5
</code>```

Actually gets executed first, before the lambda is done executing.

In order to fix this, you need to use ParseQuery#find(...) instead, or somehow find a way to wait until the background thread is done executing your lambda before checking the value of gorterilecekkart.

Title: why dont set this value?

Body:
I want set my gorterilecekkart variable in code, but it will not change. It always sees the first value instead. How can I solve this problem? Please help me. I don't know English very well sorry. But in my code I have added comments.

 class Sahnem : AppCompatActivity() {

     var gorterilecekkart=5

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_sahnem)

            val parsUser = ParseUser.getCurrentUser().email
            val queryTercih = ParseQuery.getQuery<ParseObject>("Tercih")
            queryTercih.whereEqualTo("user", parsUser.toString())

            queryTercih.findInBackground { objects, e ->

                if (objects.isEmpty()){

                }else{

                    var bas:String=objects[0].get("basla").toString()
                    var bit:String=objects[0].get("bitir").toString()

                    txvBasla.setText(bas)
                    txvBitir.setText(bit)

                    bitir=bit.toInt()
                    baslat=bas.toInt()

                    gorterilecekkart=bitir-baslat // i see log 3
                }

                println("116 "+bitir)

                gorterilecekkart=bitir-baslat

                println("119 "+gorterilecekkart)  //  i see  log 3

            }

            println("124 "+gorterilecekkart) // why i dont see log 3, i see 5

Body:
It looks like ParseQuery#findInBackground(...) runs the callback lambda in a background thread. Documentation here.

This means that:

println("124 "+gorterilecekkart) // why i dont see log 3, i see 5

Actually gets executed first, before the lambda is done executing.

In order to fix this, you need to use ParseQuery#find(...) instead, or somehow find a way to wait until the background thread is done executing your lambda before checking the value of gorterilecekkart.


问:
"main" function in Lua?
In python, one would usually define a main function, in order to allow the script to be used as module (if needed):

```<code>def main():
    print("Hello world")
    return 0

if __name__ == "__main__":
    sys.exit(main())
</code>```

In Lua, the idiom if __name__ == "__main__" isn't possible as such (that means, I don't think it is).

That's what I'm usually doing in order to have a similar behaviour in Lua:

```<code>os.exit((function(args)
    print("Hello world")
    return 0
end)(arg))
</code>```

... But this approach seems rather "heavy on parentheses" :-)

Is there a more common approach (besides defining a global main function, which seems redundant)?

答:
```<code>if arg ~= nil and arg[0] == string.sub(debug.getinfo(1,'S').source,2) then
  print "Main file"
else
  print "Library"
end
</code>```

An explanation:

Lua calls a script from the interpreter with the arg table, with arg[0] being the name of the script.

The debug.getinfo function returns a table of information describing the function at the level of the stack given by its numbered argument (1 refers to the function calling getinfo; 0 refers to getinfo itself). Its second parameter is optional: it specifies which subset of the getinfo fields to retrieve. The 'S' defines Source names.

The source field of the table returned by getinfo for files contains the name of the file the function was defined in, prefixed with an @. By passing the value of that field to string.sub(...,2), we strip that @. (The short_src field contains the name without the @, but that's because it's defined as a "print-friendly" name, and is less safe than stripping source.)

Note that this code uses a debug function, so in 5.2 you'll have to require debug to be able to use it.

ContentLicense: CC BY-SA 2.5

Title: "main" function in Lua?

Body:
In python, one would usually define a main function, in order to allow the script to be used as module (if needed):

def main():
    print("Hello world")
    return 0

if __name__ == "__main__":
    sys.exit(main())

In Lua, the idiom if __name__ == "__main__" isn't possible as such (that means, I don't think it is).

That's what I'm usually doing in order to have a similar behaviour in Lua:

os.exit((function(args)
    print("Hello world")
    return 0
end)(arg))

... But this approach seems rather "heavy on parentheses" :-)

Is there a more common approach (besides defining a global main function, which seems redundant)?

Body:
if arg ~= nil and arg[0] == string.sub(debug.getinfo(1,'S').source,2) then
  print "Main file"
else
  print "Library"
end

An explanation:

Lua calls a script from the interpreter with the arg table, with arg[0] being the name of the script.

The debug.getinfo function returns a table of information describing the function at the level of the stack given by its numbered argument (1 refers to the function calling getinfo; 0 refers to getinfo itself). Its second parameter is optional: it specifies which subset of the getinfo fields to retrieve. The 'S' defines Source names.

The source field of the table returned by getinfo for files contains the name of the file the function was defined in, prefixed with an @. By passing the value of that field to string.sub(...,2), we strip that @. (The short_src field contains the name without the @, but that's because it's defined as a "print-friendly" name, and is less safe than stripping source.)

Note that this code uses a debug function, so in 5.2 you'll have to require debug to be able to use it.


问:
finding whats wrong with my code,solving a easy competitive problem
QN;Here is the question.i dont know where my algorithm is wrong.help me find pls

Given an array A of N length. We need to calculate the next greater element for each element in given array. If next greater element is not available in given array then we need to fill ‘_’ at that index place.

Input:
The first line contains an integer T, the number of test cases. For each test case, the first line contains an integer n, the size of the array. Next line contains n space separated integers denoting the elements of the array.

Output:
For each test case, the output is an array that displays next greater element to element at that index.

```<code>Constraints:
1 <= T <= 100
1 <= N <= 100
-106 <= Ai <= 106

Example:
Input
2
9
6 3 9 8 10 2 1 15 7
4
13 6 7 12

Output:
7 6 10 9 15 3 2 _ 8
_ 7 12 13
</code>```

Explanation:
Testcase 1: Here every element of the array has next greater element but at index 7, 15 is the greatest element of given array and no other element is greater from 15 so at the index of 15 we fill with ''.
Testcase 2: Here, at index 0, 13 is the greatest value in given array and no other array element is greater from 13 so at index 0 we fill ''.

My solution:

```<code>//NOT SOLVED YET
#include<iostream>
using namespace std;
int main()
{
    int a[10]={6 ,3 ,9, 8 ,10, 2 ,1, 15, 7};
    int b[10],flag=0,big=-1,i,j;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
            if(i==j)continue;
            if((a[j]>a[i]) && (flag==0))
            {
                big=a[j];
                flag=1;
            }
            else if(a[j]<big && big>a[i] && flag==1)
                big=a[j];

        }
        if(big==-1)cout<<'_';
        else cout<<big<<' ';
        big=-1;
        flag=0;
    }

}
</code>```

the output i get is:

```<code> 2 2 2 2 7 1 0 _ 2 1
</code>```

答:
The condition should be:

```<code>    else if(a[j] < big && <b>a[j]</b> > a[i] && flag == 1)</code>```

Indeed, if you use big > a[i], then that means you just check if the thus far next greater element was larger than a[i], but this thus makes it possible to select a value later in the process that is smaller than big, but smaller than a[i] as well. Here we thus want to check if a[j] is between a[i] and big.

That being said, the above approach is not very efficient. Indeed, for each element, you calculate the next element in linear time, making this a quadratic time algorithm. You might want to look at solutions where the list is sorted first. You can for example use min-heap here to move over the list in two passes.

Body:
QN;Here is the question.i dont know where my algorithm is wrong.help me find pls

Given an array A of N length. We need to calculate the next greater element for each element in given array. If next greater element is not available in given array then we need to fill ‘_’ at that index place.

Input:
The first line contains an integer T, the number of test cases. For each test case, the first line contains an integer n, the size of the array. Next line contains n space separated integers denoting the elements of the array.

Output:
For each test case, the output is an array that displays next greater element to element at that index.

Constraints:
1 <= T <= 100
1 <= N <= 100
-106 <= Ai <= 106

Example:
Input
2
9
6 3 9 8 10 2 1 15 7
4
13 6 7 12

Output:
7 6 10 9 15 3 2 _ 8
_ 7 12 13

Explanation:
Testcase 1: Here every element of the array has next greater element but at index 7, 15 is the greatest element of given array and no other element is greater from 15 so at the index of 15 we fill with ''.
Testcase 2: Here, at index 0, 13 is the greatest value in given array and no other array element is greater from 13 so at index 0 we fill ''.

My solution:

//NOT SOLVED YET
#include<iostream>
using namespace std;
int main()
{
    int a[10]={6 ,3 ,9, 8 ,10, 2 ,1, 15, 7};
    int b[10],flag=0,big=-1,i,j;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
            if(i==j)continue;
            if((a[j]>a[i]) && (flag==0))
            {
                big=a[j];
                flag=1;
            }
            else if(a[j]<big && big>a[i] && flag==1)
                big=a[j];

        }
        if(big==-1)cout<<'_';
        else cout<<big<<' ';
        big=-1;
        flag=0;
    }

}

the output i get is:

 2 2 2 2 7 1 0 _ 2 1

Body:
The condition should be:

    else if(a[j] < big && a[j] > a[i] && flag == 1)

Indeed, if you use big > a[i], then that means you just check if the thus far next greater element was larger than a[i], but this thus makes it possible to select a value later in the process that is smaller than big, but smaller than a[i] as well. Here we thus want to check if a[j] is between a[i] and big.

That being said, the above approach is not very efficient. Indeed, for each element, you calculate the next element in linear time, making this a quadratic time algorithm. You might want to look at solutions where the list is sorted first. You can for example use min-heap here to move over the list in two passes.


问:
Java: difference between < and <= for long integer for 9223372036854775807L
When I run the following code in JVM, I am unable to understand why it behaves like this.
As per my understanding, < x operator should go till x-1.

```<code>  public class LongQuestion {

  public static void main(String[] args) {

        if(9223372036854775807L < Math.pow(2,63)) {
            System.out.println("True");                            // DOES NOT GET PRINTED
        }

         if(9223372036854775807L <= Math.pow(2,63) - 1 ) {
            System.out.println("Also True");                       // THIS GETS PRINTED
        }

    }

}
</code>```

I want to understand why Java behaves like this.

答:
Math.pow is declared as

```<code>public static double pow(double a, double b)
</code>```

So we are dealing with doubles. Math.pow(2,63) is "2.0d ^ 63.0d" (power, not eor). As double is 64 bits in total, changing the value 60 odd bits below the most significant bit will not change the value. So Math.pow(2,63) == Math.pow(2,63) - 1, which is also (double)9223372036854775807L.

Making the implicits casts implicit in the first if.

```<code>    if((double)9223372036854775807L < Math.pow(2.0d,63.0d)) {
        System.out.println("True");                            // DOES NOT GET PRINTED
    }
</code>```

Both left and right side of < are 9.223372036854776E18, so false.

Body:
When I run the following code in JVM, I am unable to understand why it behaves like this.
As per my understanding, < x operator should go till x-1.

  public class LongQuestion {

  public static void main(String[] args) {

        if(9223372036854775807L < Math.pow(2,63)) {
            System.out.println("True");                            // DOES NOT GET PRINTED
        }

         if(9223372036854775807L <= Math.pow(2,63) - 1 ) {
            System.out.println("Also True");                       // THIS GETS PRINTED
        }

    }

}

I want to understand why Java behaves like this.

Body:
Math.pow is declared as

public static double pow(double a, double b)

So we are dealing with doubles. Math.pow(2,63) is "2.0d ^ 63.0d" (power, not eor). As double is 64 bits in total, changing the value 60 odd bits below the most significant bit will not change the value. So Math.pow(2,63) == Math.pow(2,63) - 1, which is also (double)9223372036854775807L.

Making the implicits casts implicit in the first if.

    if((double)9223372036854775807L < Math.pow(2.0d,63.0d)) {
        System.out.println("True");                            // DOES NOT GET PRINTED
    }

Both left and right side of < are 9.223372036854776E18, so false.


问:
Why I have this warning in a Spring Boot pom.xml file? "Overriding managed version 1.5.9 for mariadb-java-client"
I am not using Spring from a lot of time and I have the following doubt.

I have this pom.xml file related to a Spring Boot project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springboot</groupId>
    <artifactId>excel-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Excel API with Spring Boot</name>
    <description>Spring Boot - working with Excel API</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-data</artifactId>
        </dependency>

        <!-- Start of excel dependencies -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
        <!-- End of excel dependencies -->

        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.6</version>
        </dependency>

        <!-- Start DB connectivity dependencies -->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
          <groupId>org.mariadb.jdbc</groupId>
          <artifactId>mariadb-java-client</artifactId>
          <version>1.5.7</version>
        </dependency>
        <!-- End DB connectivity dependencies -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I have added the last dependencies section related to the connectivity to a Maria DB database, these linese:

```<code><!-- Start DB connectivity dependencies -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>
<!-- End DB connectivity dependencies -->
</code>```

On the last dependency (the Maria DB client) it give me the following warning message:

Overriding managed version 1.5.9 for mariadb-java-client

What exactly means this message? It seems to me that in some way I should already have a more updated version of this client (provided by Spring). But where? I never imported this dependency before so why have I it?

Or am I missing something?

答:
It is because your project will somehow extending the POM spring-boot-dependencies through extending the parent POM spring-boot-starter-parent. And inside spring-boot-dependencies , it defines the version of many dependencies in <dependencyManagement>  which the version of mariadb-java-client is 1.5.9.

The purpose of dependency management is used to centralise all dependencies' related information. In this case, it defines a default version for a set of libraries such that if a children POM want to include these libraries , it does not need to specify the version for them inside their pom.xml as it is already defined in the parent 's <dependencyManagement>.

So, in the children project 's pom.xml , we can simply define

<dependency>
  <groupId>org.foo.bar</groupId>
  <artifactId>foo-bar</artifactId>
</dependency>
```

<p>rather than </p>

<pre class="lang-xml prettyprint-override"><code><dependency>
  <groupId>org.foo.bar</groupId>
  <artifactId>foo-bar</artifactId>
  <version>1.3.56</version>
</dependency>
</code>```

It allows all projects that extending this parent pom will have consistent dependencies version.

So , if you specify the version of a dependency inside the children pom that is different from what define in the <dependencyManagement> , it will give you the following warning :

```<code>Overriding managed version X.Y.Z for foo-bar
</code>```

Body:
I am not using Spring from a lot of time and I have the following doubt.

I have this pom.xml file related to a Spring Boot project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springboot</groupId>
    <artifactId>excel-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Excel API with Spring Boot</name>
    <description>Spring Boot - working with Excel API</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-data</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>

        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.6</version>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
          <groupId>org.mariadb.jdbc</groupId>
          <artifactId>mariadb-java-client</artifactId>
          <version>1.5.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have added the last dependencies section related to the connectivity to a Maria DB database, these linese:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>org.mariadb.jdbc</groupId>
  <artifactId>mariadb-java-client</artifactId>
  <version>1.5.7</version>
</dependency>

On the last dependency (the Maria DB client) it give me the following warning message:

Overriding managed version 1.5.9 for mariadb-java-client

What exactly means this message? It seems to me that in some way I should already have a more updated version of this client (provided by Spring). But where? I never imported this dependency before so why have I it?

Or am I missing something?

Body:
It is because your project will somehow extending the POM spring-boot-dependencies through extending the parent POM spring-boot-starter-parent. And inside spring-boot-dependencies , it defines the version of many dependencies in <dependencyManagement>  which the version of mariadb-java-client is 1.5.9.

The purpose of dependency management is used to centralise all dependencies' related information. In this case, it defines a default version for a set of libraries such that if a children POM want to include these libraries , it does not need to specify the version for them inside their pom.xml as it is already defined in the parent 's <dependencyManagement>.

So, in the children project 's pom.xml , we can simply define

<dependency>
  <groupId>org.foo.bar</groupId>
  <artifactId>foo-bar</artifactId>
</dependency>

rather than

<dependency>
  <groupId>org.foo.bar</groupId>
  <artifactId>foo-bar</artifactId>
  <version>1.3.56</version>
</dependency>

It allows all projects that extending this parent pom will have consistent dependencies version.

So , if you specify the version of a dependency inside the children pom that is different from what define in the <dependencyManagement> , it will give you the following warning :

Overriding managed version X.Y.Z for foo-bar


问:
How to use other html file if consumer is on mobile?
So I have a problem idk how to let my consumer see my mobile html i used:
But for some reason it doesnt want to work do you have nay suggestions?</p>

```<code>    if (screen.width <= 500) {
    document.location = "webapp.html";
    }
    </script> ```

</code>```

答:
Just make your site responsive using css3 flexbox or
css frameworks like bootstrap, etc.</p>

Body:
So I have a problem idk how to let my consumer see my mobile html i used:
But for some reason it doesnt want to work do you have nay suggestions?

    if (screen.width <= 500) {
    document.location = "webapp.html";
    }
    </script> ```