问:
I don't understand why these two elements are not aligning side by side?
I want to get these two elements to align perfectly vertical side by side using a position value of relative. I'm having trouble as to understanding why these two elements don't want to align.

Can someone explain what I'm doing wrong? and if possible find a solution?

https://jsfiddle.net/kerberonix/qcq68gfg/

HTML

```<code><html>
  <body>
    <footer>
      <div class="test">
        <p>Footer Text</p>
      </div>
      <ul class="social-links">
        <li>Link 1</li>
        <li>Link 2</li>
      </ul>
    </footer>
  </body>
</code>```

CSS

```<code>footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
    display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

.social-links li {
    display: inline-block;
    margin-right: 35px;
    text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}
</code>```

答:
Now its Okay I think you get What you need just replace the code in ssocial links

```<code>footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

/*--------------------------------------------------------------------------------------------
SOCIAL LINKS
--------------------------------------------------------------------------------------------*/

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
  text-align: right;
}

.social-links li {
  top 150px;
  height:20px;
  width: 250px;
  position: relative;
  left: calc(50% – 125px);

}

.social-links li:last-child {
  margin: 0;
}
</code>```

Body:
I want to get these two elements to align perfectly vertical side by side using a position value of relative. I'm having trouble as to understanding why these two elements don't want to align.

Can someone explain what I'm doing wrong? and if possible find a solution?

https://jsfiddle.net/kerberonix/qcq68gfg/

HTML

Footer Text

Link 1

Link 2

CSS

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
    display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

.social-links li {
    display: inline-block;
    margin-right: 35px;
    text-decoration: none;
}

.social-links li:last-child {
  margin: 0;
}

Body:
Now its Okay I think you get What you need just replace the code in ssocial links

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    padding: 0 20px;
    background-color: #262626;
}

.test {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
}

footer p {
    font-size: 100%;
    color: #888;
}

/*--------------------------------------------------------------------------------------------
SOCIAL LINKS
--------------------------------------------------------------------------------------------*/

.social-links {
    position: relative;
  display: inline-block;
    top: 50%;
    width: 50%;
    transform: translateY(-50%);
  text-align: right;
}

.social-links li {
  top 150px;
  height:20px;
  width: 250px;
  position: relative;
  left: calc(50% – 125px);

}

.social-links li:last-child {
  margin: 0;
}


来源: stackexchange

问:
set DatePicker field in javafx to empty field?
How to set the datepicker to an empty field?

I have button the user will confirm with the button I want the datepicker to delete whatever the user chose. For example, for the textfield i used the following statement:

```<code>TextField userName = new TextField();
</code>```

Then I clean it using the following statement:

```<code>userName.setText("");
</code>```

but I can't do the same thing for the datepicker object since it has not setText function.

And the same thing for the ComboBox object. I dont want it to choose the first one. I want it to reshow the PromptText message. For example,

```<code>ComboBox items = new ComboBox();
items.setPromptText("Choose From Below");
</code>```

Once the user choose from it, and press the button how to redisplay the prompt message again.

答:
ComboBoxBase defines a valueProperty that is inherited by both DatePicker and ComboBox and represents the currently selected item. So you can call

```<code>datePicker.setValue(null);
</code>```

or

```<code>// items is the combo box you defined:
items.setValue(null);
</code>```

to clear the value from either one.

ContentLicense: CC BY-SA 3.0

Body:
How to set the datepicker to an empty field?

I have button the user will confirm with the button I want the datepicker to delete whatever the user chose. For example, for the textfield i used the following statement:

TextField userName = new TextField();

Then I clean it using the following statement:

userName.setText("");

but I can't do the same thing for the datepicker object since it has not setText function.

And the same thing for the ComboBox object. I dont want it to choose the first one. I want it to reshow the PromptText message. For example,

ComboBox items = new ComboBox();
items.setPromptText("Choose From Below");

Once the user choose from it, and press the button how to redisplay the prompt message again.

Body:
ComboBoxBase defines a valueProperty that is inherited by both DatePicker and ComboBox and represents the currently selected item. So you can call

datePicker.setValue(null);

or

// items is the combo box you defined:
items.setValue(null);

to clear the value from either one.


问:
Views not showing when added on button click?
Ok, I have been on this for 6 hours now and for some reason, I just don't get it.

I am trying to make an app to calculate something using a certain formula.

Now consider it as a grade point average calculating thing. I have a button which should allow the user to add two more spinners to the layout and thereby proceeding further. Now I made a method for this purpose. When I call this method for the first time the spinners are added. But it doesn't work the second time.
It also doesn't work if I put it in the button onClick() method. I have gone through multiple examples posted online and also on stackoverflow, maybe I am making some stupid mistake. Just guide me through this, please.

Here is the code:-

SGPA.class

```<code>public class SGPA extends AppCompatActivity {
    View v;
    Context c;
    LinearLayout subjectData;
    ArrayList<Integer> creditIds;
    ArrayList<Integer> gradeIds;
    ArrayList<String> credits;
    ArrayList<String> grades;
    ArrayList<Integer> gradePoints;
    //int id = View.generateViewId();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sgpa);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        credits=new ArrayList<>();
        grades=new ArrayList<>();
        gradePoints=new ArrayList<>();
        //TODO if 2015 or 2013 regulations
        //assuming 2015
        fill2015();
        LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.activity_sgpa, null);
        subjectData=(LinearLayout)v.findViewById(R.id.subjectdata);
        c = this;
        creditIds=new ArrayList<>();
        gradeIds=new ArrayList<>();
        Button button2=(Button)findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addViewForAnotherSubject();
                setContentView(v);
            }
        });
        setContentView(v);
    }
    void addViewForAnotherSubject()
    {
        LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
        LinearLayout l=new LinearLayout(c);
        l.setOrientation(LinearLayout.HORIZONTAL);
        l.setLayoutParams(lp);
        l.setGravity(Gravity.CENTER_HORIZONTAL);
        Spinner creditspinner=new Spinner(c);
        Spinner gradespinner=new Spinner(c);
        ArrayAdapter<String> creditSpinnerArrayAdapter = new ArrayAdapter<>
(this,
                android.R.layout.simple_spinner_dropdown_item, credits);
        creditspinner.setAdapter(creditSpinnerArrayAdapter);
        ArrayAdapter<String> gradeSpinnerArrayAdapter = new ArrayAdapter<>
(this,
                android.R.layout.simple_spinner_dropdown_item, grades);
        gradespinner.setAdapter(gradeSpinnerArrayAdapter);
        l.addView(creditspinner);
        l.addView(gradespinner);
        subjectData.addView(l);
    }
    void fill2015()
    {
        grades.add("O");        grades.add("A+");
        grades.add("A");        grades.add("B+");
        grades.add("B");        grades.add("C");
        grades.add("P");        grades.add("F");
        grades.add("Ab");        grades.add("I");
        gradePoints.add(10);        gradePoints.add(9);
        gradePoints.add(8);        gradePoints.add(7);
        gradePoints.add(6);        gradePoints.add(5);
        gradePoints.add(4);        gradePoints.add(0);
        gradePoints.add(0);        gradePoints.add(0);
        for(int i=1;i<=10;i++)
            credits.add(""+i);
    }
    void fill2013()
    {

    }
}
</code>```

activity_sgpa.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="innominatebit.srmite.SGPA">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_sgpa" />

</android.support.design.widget.CoordinatorLayout>
</code>```

content_sgpa.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="6dp"
    android:paddingEnd="6dp"
    android:paddingLeft="6dp"
    android:paddingRight="6dp"
    android:paddingStart="6dp"
    android:paddingTop="6dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="innominatebit.srmite.SGPA"
    tools:showIn="@layout/activity_sgpa">

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

        <LinearLayout
            android:id="@+id/subjectdata"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button2"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center_horizontal"
            android:orientation="vertical">

        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />

</RelativeLayout>
</code>```

All help is appreciated. Thanks in advance!

答:
Ok, I got it. i made another test application for debugging purposes until I got it. Seems I did not need a layout inflator at all.
Here's the code:

```<code>public class MainActivity extends AppCompatActivity {
    ArrayList<Integer> creditIds;
    ArrayList<Integer> gradeIds;
    ArrayList<String> credits;
    ArrayList<String> grades;
    ArrayList<Integer> gradePoints;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        credits=new ArrayList<>();
        grades=new ArrayList<>();
        gradePoints=new ArrayList<>();
        fill2015();
        creditIds=new ArrayList<>();
        gradeIds=new ArrayList<>();
        final LinearLayout myData=(LinearLayout)findViewById(R.id.myData);
        addforanothersubject(myData);
        Button b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            addforanothersubject(myData);
            }
        });
    }
    void addforanothersubject(LinearLayout myData)
    {
        Context c=MainActivity.this;
        LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
        LinearLayout l=new LinearLayout(c);
        l.setOrientation(LinearLayout.HORIZONTAL);
        l.setLayoutParams(lp);
        l.setGravity(Gravity.CENTER_HORIZONTAL);
        Spinner creditspinner=new Spinner(c);
        Spinner gradespinner=new Spinner(c);
        ArrayAdapter<String> creditSpinnerArrayAdapter = new ArrayAdapter<>
(c,
                android.R.layout.simple_spinner_item, credits);
        creditspinner.setAdapter(creditSpinnerArrayAdapter);
        ArrayAdapter<String> gradeSpinnerArrayAdapter = new ArrayAdapter<>
(c,
                android.R.layout.simple_spinner_item, grades);
        gradespinner.setAdapter(gradeSpinnerArrayAdapter);
        l.addView(creditspinner);
        l.addView(gradespinner);
        myData.addView(l);
    }
    void fill2015()
    {
        grades.add("O");        grades.add("A+");
        grades.add("A");        grades.add("B+");
        grades.add("B");        grades.add("C");
        grades.add("P");        grades.add("F");
        grades.add("Ab");        grades.add("I");
        gradePoints.add(10);        gradePoints.add(9);
        gradePoints.add(8);        gradePoints.add(7);
        gradePoints.add(6);        gradePoints.add(5);
        gradePoints.add(4);        gradePoints.add(0);
        gradePoints.add(0);        gradePoints.add(0);
        for(int i=1;i<=10;i++)
            credits.add(""+i);
    }
}
</code>```

And the xml is:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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="aaa.test.MainActivity">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/myData"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>
            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:text="Add" />

        </LinearLayout>
    </ScrollView>

</RelativeLayout>
</code>```

Hope it helps someone.

Body:
Ok, I have been on this for 6 hours now and for some reason, I just don't get it.

I am trying to make an app to calculate something using a certain formula.

Now consider it as a grade point average calculating thing. I have a button which should allow the user to add two more spinners to the layout and thereby proceeding further. Now I made a method for this purpose. When I call this method for the first time the spinners are added. But it doesn't work the second time.
It also doesn't work if I put it in the button onClick() method. I have gone through multiple examples posted online and also on stackoverflow, maybe I am making some stupid mistake. Just guide me through this, please.

Here is the code:-

SGPA.class

public class SGPA extends AppCompatActivity {
    View v;
    Context c;
    LinearLayout subjectData;
    ArrayList<Integer> creditIds;
    ArrayList<Integer> gradeIds;
    ArrayList<String> credits;
    ArrayList<String> grades;
    ArrayList<Integer> gradePoints;
    //int id = View.generateViewId();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sgpa);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        credits=new ArrayList<>();
        grades=new ArrayList<>();
        gradePoints=new ArrayList<>();
        //TODO if 2015 or 2013 regulations
        //assuming 2015
        fill2015();
        LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.activity_sgpa, null);
        subjectData=(LinearLayout)v.findViewById(R.id.subjectdata);
        c = this;
        creditIds=new ArrayList<>();
        gradeIds=new ArrayList<>();
        Button button2=(Button)findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addViewForAnotherSubject();
                setContentView(v);
            }
        });
        setContentView(v);
    }
    void addViewForAnotherSubject()
    {
        LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
        LinearLayout l=new LinearLayout(c);
        l.setOrientation(LinearLayout.HORIZONTAL);
        l.setLayoutParams(lp);
        l.setGravity(Gravity.CENTER_HORIZONTAL);
        Spinner creditspinner=new Spinner(c);
        Spinner gradespinner=new Spinner(c);
        ArrayAdapter<String> creditSpinnerArrayAdapter = new ArrayAdapter<>
(this,
                android.R.layout.simple_spinner_dropdown_item, credits);
        creditspinner.setAdapter(creditSpinnerArrayAdapter);
        ArrayAdapter<String> gradeSpinnerArrayAdapter = new ArrayAdapter<>
(this,
                android.R.layout.simple_spinner_dropdown_item, grades);
        gradespinner.setAdapter(gradeSpinnerArrayAdapter);
        l.addView(creditspinner);
        l.addView(gradespinner);
        subjectData.addView(l);
    }
    void fill2015()
    {
        grades.add("O");        grades.add("A+");
        grades.add("A");        grades.add("B+");
        grades.add("B");        grades.add("C");
        grades.add("P");        grades.add("F");
        grades.add("Ab");        grades.add("I");
        gradePoints.add(10);        gradePoints.add(9);
        gradePoints.add(8);        gradePoints.add(7);
        gradePoints.add(6);        gradePoints.add(5);
        gradePoints.add(4);        gradePoints.add(0);
        gradePoints.add(0);        gradePoints.add(0);
        for(int i=1;i<=10;i++)
            credits.add(""+i);
    }
    void fill2013()
    {

    }
}

activity_sgpa.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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="innominatebit.srmite.SGPA">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_sgpa" />

</android.support.design.widget.CoordinatorLayout>

content_sgpa.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="6dp"
    android:paddingEnd="6dp"
    android:paddingLeft="6dp"
    android:paddingRight="6dp"
    android:paddingStart="6dp"
    android:paddingTop="6dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="innominatebit.srmite.SGPA"
    tools:showIn="@layout/activity_sgpa">

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

        <LinearLayout
            android:id="@+id/subjectdata"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button2"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center_horizontal"
            android:orientation="vertical">

        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />

</RelativeLayout>

All help is appreciated. Thanks in advance!

Body:
Ok, I got it. i made another test application for debugging purposes until I got it. Seems I did not need a layout inflator at all.
Here's the code:

public class MainActivity extends AppCompatActivity {
    ArrayList<Integer> creditIds;
    ArrayList<Integer> gradeIds;
    ArrayList<String> credits;
    ArrayList<String> grades;
    ArrayList<Integer> gradePoints;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        credits=new ArrayList<>();
        grades=new ArrayList<>();
        gradePoints=new ArrayList<>();
        fill2015();
        creditIds=new ArrayList<>();
        gradeIds=new ArrayList<>();
        final LinearLayout myData=(LinearLayout)findViewById(R.id.myData);
        addforanothersubject(myData);
        Button b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            addforanothersubject(myData);
            }
        });
    }
    void addforanothersubject(LinearLayout myData)
    {
        Context c=MainActivity.this;
        LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
        LinearLayout l=new LinearLayout(c);
        l.setOrientation(LinearLayout.HORIZONTAL);
        l.setLayoutParams(lp);
        l.setGravity(Gravity.CENTER_HORIZONTAL);
        Spinner creditspinner=new Spinner(c);
        Spinner gradespinner=new Spinner(c);
        ArrayAdapter<String> creditSpinnerArrayAdapter = new ArrayAdapter<>
(c,
                android.R.layout.simple_spinner_item, credits);
        creditspinner.setAdapter(creditSpinnerArrayAdapter);
        ArrayAdapter<String> gradeSpinnerArrayAdapter = new ArrayAdapter<>
(c,
                android.R.layout.simple_spinner_item, grades);
        gradespinner.setAdapter(gradeSpinnerArrayAdapter);
        l.addView(creditspinner);
        l.addView(gradespinner);
        myData.addView(l);
    }
    void fill2015()
    {
        grades.add("O");        grades.add("A+");
        grades.add("A");        grades.add("B+");
        grades.add("B");        grades.add("C");
        grades.add("P");        grades.add("F");
        grades.add("Ab");        grades.add("I");
        gradePoints.add(10);        gradePoints.add(9);
        gradePoints.add(8);        gradePoints.add(7);
        gradePoints.add(6);        gradePoints.add(5);
        gradePoints.add(4);        gradePoints.add(0);
        gradePoints.add(0);        gradePoints.add(0);
        for(int i=1;i<=10;i++)
            credits.add(""+i);
    }
}

And the xml is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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="aaa.test.MainActivity">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/myData"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >
            </LinearLayout>
            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:text="Add" />

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Hope it helps someone.


问:
Spring solr dynamic fields anotation
I'm trying to do a query like that retrieves one specific field from the document, i don't a get runtime error when executing the query but i don't get the 3 fields i'm supposed to retrieve from the query, just date and origin, but no the variable, the one that is supposed to return all of them are nulls.
How i can select the fields i only want to retrieve in a query?

currently my query looks like this:

```<code>  @Query(value = "id:?0", fields = {"?1","date","origin"})
   List<Data> getRecord(String id,String field);
</code>```

答:
Introduction

Reading your comments I see there is a bit of confusion about what's SolrJ and
Spring Data for Apache Solr.

SolrJ is the Solr client (personally I would also add the standard and official client).

SolrJ is an API that makes it easy for Java applications to talk to
  Solr. SolrJ hides a lot of the details of connecting to Solr and
  allows your application to interact with Solr with simple high-level
  methods.

Spring Data for Apache Solr is part of the larger framework Spring Data and provides configuration and access to Apache Solr Search Server from Spring applications ( to talk with Solr internally it uses SolrJ).

So far, Solr Spring Data ver. 1.2.0.RELEASE depends on SolrJ 4.7.2 which could be incompatibile with Solr 6.2.0 (for sure if you're using SolrCloud).

Given this appropriate introduction I would suggest to keep Solr instance and SolrJ client on the same version (or at least on the same major version).

So for Solr v.6.2.1 you should use SolrJ 6.2.1, but unfortunately latest Solr Spring Data version is 2.1.3.RELEASE (which internally depends on SolrJ 5.5.0).

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-solr</artifactId>
        <version>2.1.3.RELEASE</version>
    </dependency>
</dependencies>
</code>```

Your question

Regarding the fact that you don't receive the list of fields you're looking for, simply Solr Data does not support placeholders for the field list.

Instead of struggling with Solr Spring Data, I would suggest to extend your Repository class creating a new RepositoryImpl where add a custom search using the simple and plain SolrJ client.

```<code>@Component
public class ProductsRepositoryImpl implements ProductsRepositoryCustom {

  @Autowired
  private SolrServer   solrServer;

  public ProductsRepositoryImpl() {};

  public ProductsRepositoryImpl(SolrServer solrServer) {
    this.solrServer = solrServer;
  }

  public List<Map<String, Object>> findFields(String id, List<String> fields)
  {
    SolrQuery solrQuery = new SolrQuery("id:" + id);
    solrQuery.setFields(fields.toArray(new String[0]));
    try {
      QueryResponse response = this.solrServer.query(solrQuery);
      return response.getResults()
              .stream()
              .map(d ->
                {
                  return d.entrySet()
                          .stream()
                          .filter(e -> fields.contains(e.getKey()))
                          .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
                }).collect(Collectors.toList());
    } catch (SolrServerException e) {
      // TODO Auto-generated catch block
    }
    return Collections.emptyList();
  }

}
</code>```

Title: Spring solr dynamic fields anotation

Body:
I'm trying to do a query like that retrieves one specific field from the document, i don't a get runtime error when executing the query but i don't get the 3 fields i'm supposed to retrieve from the query, just date and origin, but no the variable, the one that is supposed to return all of them are nulls.
How i can select the fields i only want to retrieve in a query?

currently my query looks like this:

  @Query(value = "id:?0", fields = {"?1","date","origin"})
   List<Data> getRecord(String id,String field);

Body:
Introduction

Reading your comments I see there is a bit of confusion about what's SolrJ and
Spring Data for Apache Solr.

SolrJ is the Solr client (personally I would also add the standard and official client).

SolrJ is an API that makes it easy for Java applications to talk to
  Solr. SolrJ hides a lot of the details of connecting to Solr and
  allows your application to interact with Solr with simple high-level
  methods.

Spring Data for Apache Solr is part of the larger framework Spring Data and provides configuration and access to Apache Solr Search Server from Spring applications ( to talk with Solr internally it uses SolrJ).

So far, Solr Spring Data ver. 1.2.0.RELEASE depends on SolrJ 4.7.2 which could be incompatibile with Solr 6.2.0 (for sure if you're using SolrCloud).

Given this appropriate introduction I would suggest to keep Solr instance and SolrJ client on the same version (or at least on the same major version).

So for Solr v.6.2.1 you should use SolrJ 6.2.1, but unfortunately latest Solr Spring Data version is 2.1.3.RELEASE (which internally depends on SolrJ 5.5.0).

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-solr</artifactId>
        <version>2.1.3.RELEASE</version>
    </dependency>
</dependencies>

Your question

Regarding the fact that you don't receive the list of fields you're looking for, simply Solr Data does not support placeholders for the field list.

Instead of struggling with Solr Spring Data, I would suggest to extend your Repository class creating a new RepositoryImpl where add a custom search using the simple and plain SolrJ client.

@Component
public class ProductsRepositoryImpl implements ProductsRepositoryCustom {

  @Autowired
  private SolrServer   solrServer;

  public ProductsRepositoryImpl() {};

  public ProductsRepositoryImpl(SolrServer solrServer) {
    this.solrServer = solrServer;
  }

  public List<Map<String, Object>> findFields(String id, List<String> fields)
  {
    SolrQuery solrQuery = new SolrQuery("id:" + id);
    solrQuery.setFields(fields.toArray(new String[0]));
    try {
      QueryResponse response = this.solrServer.query(solrQuery);
      return response.getResults()
              .stream()
              .map(d ->
                {
                  return d.entrySet()
                          .stream()
                          .filter(e -> fields.contains(e.getKey()))
                          .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
                }).collect(Collectors.toList());
    } catch (SolrServerException e) {
      // TODO Auto-generated catch block
    }
    return Collections.emptyList();
  }

}


问:
Displaying dates in x axis of Bokeh Area plot
Passing my dataframe like this can display plot but not when I specify x to correspond to my Date column. Can you suggest what might be the problem here? I tried converting my Date column into string, datetime and other formats with no success.

```<code>import pandas as pd
from bokeh.charts import output_file, Area, defaults
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([{'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
 {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
 {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
 {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
 {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
 {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
 {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}])

xf["Date"] =xf.REDUCED_DATE.astype(str)
area1 = Area(xf,y=["Cat1","Cat2"], title="Area chart", legend="top_left",
             xlabel="Date",ylabel="Amount",stack=True)

show(area1, notebook_handle=True)
</code>```

Passing Date as x column does not display any data at all:

```<code>xf["Date"] =xf.REDUCED_DATE.astype(str)
area1 = Area(xf, x="REDUCED_DATE", y=["Cat1","Cat2"], title="Area chart",
             legend="top_left",xlabel="Date",ylabel="Amount",stack=True)

show(area1, notebook_handle=True)
</code>```

答:
Apparently there is a bug in bokeh.charts.Area and if confirmed it should be reported in the  bokeh repository. I am using bokeh version 0.12.4 and there is a curiosity about the string values to be used as xaxis tick labels (REDUCED_DATE in the present example). If the third value is '2' and the fourth value starts with '3'(or 4,5,...9) then Area chart shows ok, otherwise no Area chart is shown (as in the question):

```<code>import pandas as pd
from bokeh.charts import output_file, Area
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '3'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

area1 = Area(xf, x="REDUCED_DATE", y=["Cat1","Cat2"], title="Area chart",
             legend="top_left",xlabel="Date",ylabel="Amount",stack=True)
show(area1, notebook_handle=True)
</code>```

The output:

A workaround that worked for me is using bokeh.plotting.figure to create a figure with x_range defined by bokeh.models.FactorRange and adding patches glyphs:

```<code>import pandas as pd
import bokeh.plotting
from bokeh.charts import output_file
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

# getting the coordinates of the patches:
nvals = xf.shape[0]
accum = pd.np.zeros(nvals)
vals = []
for cat in ['Cat1','Cat2']:
    prev_accum = accum.copy()
    accum += xf[cat].get_values()
    vals += [pd.np.concatenate((prev_accum,accum[::-1]))]

p = bokeh.plotting.figure(
        x_range=bokeh.models.FactorRange(factors=list(xf["REDUCED_DATE"]),offset=-1))
p.patches(xs=[range(nvals)+range(nvals-1,-1,-1)], ys=[vals[0]],
                color=['#f22c40'],alpha=0.8 ,legend='Cat1')
p.patches(xs=[range(nvals)+range(nvals-1,-1,-1)], ys=[vals[1]],
                color=['#5ab738'],alpha=0.8 ,legend='Cat2')
p.xaxis.major_label_orientation = 3.4142/4
p.legend[0].location = 'top_left'
p.xaxis.axis_label = "Date"
p.yaxis.axis_label = "Amount"
show(p)
</code>```

The output here is the correct one:

UPDATE bokeh version 0.12.16

offset no longer supported in FactorRange in the latest versions of bokeh. In the following code (tested in version 0.12.16) I am using datetime as the x axis values. Also inspired in the following codes: brewer.py and github issue #6376:

```<code>import pandas as pd
import bokeh.plotting
from bokeh.io import show, output_notebook

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

def stacked(df,N=2):
    df_top = df.iloc[:,0:N].cumsum(axis=1) # accumulates first N columns
    df_bottom = df_top.shift(axis=1).fillna({'Cat1': 0})[::-1]
    df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
    return df_stack

dates  = [pd.datetime.strptime(x,'%Y-%m') for x in xf['REDUCED_DATE']]
x2 = np.hstack((dates[::-1], dates))
areas = stacked(xf)

source = bokeh.models.ColumnDataSource(dict(
    xs=[x2] * areas.shape[1],
    ys=[areas[c].values for c in areas],
    color=['#f22c40','#5ab738'],
    label=['Cat1','Cat2']
))

p = bokeh.plotting.figure( x_axis_type='datetime')
p.patches( xs='xs', ys='ys', color='color', legend='label', source=source,alpha=0.8)
p.xaxis.formatter = bokeh.models.formatters.DatetimeTickFormatter(months=["%Y-%m"])
p.xaxis.major_label_orientation = 3.4142/4
p.legend.location = 'top_left'
p.xaxis.axis_label = "Date"
p.yaxis.axis_label = "Amount"

output_notebook()
show(p)
</code>```

Body:
Passing my dataframe like this can display plot but not when I specify x to correspond to my Date column. Can you suggest what might be the problem here? I tried converting my Date column into string, datetime and other formats with no success.

import pandas as pd
from bokeh.charts import output_file, Area, defaults
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([{'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
 {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
 {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
 {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
 {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
 {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
 {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}])

xf["Date"] =xf.REDUCED_DATE.astype(str)
area1 = Area(xf,y=["Cat1","Cat2"], title="Area chart", legend="top_left",
             xlabel="Date",ylabel="Amount",stack=True)

show(area1, notebook_handle=True)

Passing Date as x column does not display any data at all:

xf["Date"] =xf.REDUCED_DATE.astype(str)
area1 = Area(xf, x="REDUCED_DATE", y=["Cat1","Cat2"], title="Area chart",
             legend="top_left",xlabel="Date",ylabel="Amount",stack=True)

show(area1, notebook_handle=True)

Body:
Apparently there is a bug in bokeh.charts.Area and if confirmed it should be reported in the  bokeh repository. I am using bokeh version 0.12.4 and there is a curiosity about the string values to be used as xaxis tick labels (REDUCED_DATE in the present example). If the third value is '2' and the fourth value starts with '3'(or 4,5,...9) then Area chart shows ok, otherwise no Area chart is shown (as in the question):

import pandas as pd
from bokeh.charts import output_file, Area
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '3'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

area1 = Area(xf, x="REDUCED_DATE", y=["Cat1","Cat2"], title="Area chart",
             legend="top_left",xlabel="Date",ylabel="Amount",stack=True)
show(area1, notebook_handle=True)

The output:

A workaround that worked for me is using bokeh.plotting.figure to create a figure with x_range defined by bokeh.models.FactorRange and adding patches glyphs:

import pandas as pd
import bokeh.plotting
from bokeh.charts import output_file
from bokeh.io import show, output_notebook
output_notebook()

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

# getting the coordinates of the patches:
nvals = xf.shape[0]
accum = pd.np.zeros(nvals)
vals = []
for cat in ['Cat1','Cat2']:
    prev_accum = accum.copy()
    accum += xf[cat].get_values()
    vals += [pd.np.concatenate((prev_accum,accum[::-1]))]

p = bokeh.plotting.figure(
        x_range=bokeh.models.FactorRange(factors=list(xf["REDUCED_DATE"]),offset=-1))
p.patches(xs=[range(nvals)+range(nvals-1,-1,-1)], ys=[vals[0]],
                color=['#f22c40'],alpha=0.8 ,legend='Cat1')
p.patches(xs=[range(nvals)+range(nvals-1,-1,-1)], ys=[vals[1]],
                color=['#5ab738'],alpha=0.8 ,legend='Cat2')
p.xaxis.major_label_orientation = 3.4142/4
p.legend[0].location = 'top_left'
p.xaxis.axis_label = "Date"
p.yaxis.axis_label = "Amount"
show(p)

The output here is the correct one:

UPDATE bokeh version 0.12.16

offset no longer supported in FactorRange in the latest versions of bokeh. In the following code (tested in version 0.12.16) I am using datetime as the x axis values. Also inspired in the following codes: brewer.py and github issue #6376:

import pandas as pd
import bokeh.plotting
from bokeh.io import show, output_notebook

xf = pd.DataFrame([
     {'Cat1': 112.04, 'Cat2': 0.0, 'REDUCED_DATE': '2011-12'},
     {'Cat1': 359.57449999999994, 'Cat2': 579.35, 'REDUCED_DATE': '2012-01'},
     {'Cat1': 376.99000000000007, 'Cat2': 552.64, 'REDUCED_DATE': '2012-02'},
     {'Cat1': 416.86000000000007, 'Cat2': 543.35, 'REDUCED_DATE': '2012-03'},
     {'Cat1': 320.5847000000001, 'Cat2': 543.35, 'REDUCED_DATE': '2012-04'},
     {'Cat1': 521.0349999999999, 'Cat2': 553.33, 'REDUCED_DATE': '2012-05'},
     {'Cat1': 330.84, 'Cat2': 667.94, 'REDUCED_DATE': '2012-06'}
])

def stacked(df,N=2):
    df_top = df.iloc[:,0:N].cumsum(axis=1) # accumulates first N columns
    df_bottom = df_top.shift(axis=1).fillna({'Cat1': 0})[::-1]
    df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
    return df_stack

dates  = [pd.datetime.strptime(x,'%Y-%m') for x in xf['REDUCED_DATE']]
x2 = np.hstack((dates[::-1], dates))
areas = stacked(xf)

source = bokeh.models.ColumnDataSource(dict(
    xs=[x2] * areas.shape[1],
    ys=[areas[c].values for c in areas],
    color=['#f22c40','#5ab738'],
    label=['Cat1','Cat2']
))

p = bokeh.plotting.figure( x_axis_type='datetime')
p.patches( xs='xs', ys='ys', color='color', legend='label', source=source,alpha=0.8)
p.xaxis.formatter = bokeh.models.formatters.DatetimeTickFormatter(months=["%Y-%m"])
p.xaxis.major_label_orientation = 3.4142/4
p.legend.location = 'top_left'
p.xaxis.axis_label = "Date"
p.yaxis.axis_label = "Amount"

output_notebook()
show(p)

ContentLicense: CC BY-SA 4.0


问:
How to get html tags?
Say I have a text file like this:

```<code><html><head>Headline<html><head>more words
</script>even more words</script>
<html><head>Headline<html><head>more words
</script>even more words</script>
</code>```

How would I get just the tags into a list like this:

```<code><html>
<head>
<html>
<head>
</script>
</script>
<html>
<head>
<html>
<head>
</script>
</script>
</code>```

答:
I think this is what you want:

```<code>html_string = ''.join(input_file.readlines())
matches = re.findall('<.*?>', html_string)
for m in matches:
    print m
</code>```

Hope this helps

ContentLicense: CC BY-SA 2.5

Title: How to get html tags?

Body:
Say I have a text file like this:

Headlinemore words
</script>even more words</script>
Headlinemore words
</script>even more words</script>

How would I get just the tags into a list like this:

</script>
</script>

</script>
</script>

Body:
I think this is what you want:

html_string = ''.join(input_file.readlines())
matches = re.findall('<.*?>', html_string)
for m in matches:
    print m

Hope this helps


问:
Fixed div on left of container, full height of container (but not of page) using CSS
I want the following layout in my page:

The header and footer are always visible. The gray area is an article tag. The green and dark red areas are both inside a nav tag. The dark red has a fixed width, and is going to be used as a handle to resize the green navigation panel (it will be very narrow, of course, and I'll use JavaScript for the resizing). Both the gray and green areas must have their own scrollbars.

That's the HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>CSS template</title>
</head>
<body>
<header>Header</header>
<main>
<nav>
    <div class='navcont'>
        <p>nav1</p>
        <p>nav2 with longer line just to make sure if everything is working as intended</p>
    </div>
    <div class='handle'>Handle</div>
</nav>
<article>
    <p>Article</p>
</article>
</main>
<footer>Footer</footer>
</body>
</html>
</code>```

That's the CSS:

```<code>html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#C0C0C0;
    width:80%;
    overflow:auto;
    padding:10px;
}
nav {
    width:20%;
    height:auto;
    overflow:hidden;
}
.navcont {
    background:#00FF00;
    width:auto;
}
.handle {
    background:#800000;
    float:right;
    width:30px;
}
footer {
    text-align:center;
}
</code>```

And a running example: https://jsfiddle.net/etwphhc8/

I tried many different solutions, from many different questions/answers here, but still haven't make it work as intended. So, how can I achieve the wanted layout using CSS?

答:
Add flex with the direction set to row in nav:</p>

```<code>nav {
  width:20%;
  height:auto;
  overflow:hidden;
  display:flex;
}
</code>```

Body:
I want the following layout in my page:

The header and footer are always visible. The gray area is an article tag. The green and dark red areas are both inside a nav tag. The dark red has a fixed width, and is going to be used as a handle to resize the green navigation panel (it will be very narrow, of course, and I'll use JavaScript for the resizing). Both the gray and green areas must have their own scrollbars.

That's the HTML:

<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS template</title>

Header

nav1

nav2 with longer line just to make sure if everything is working as intended

Handle

Article

Footer

That's the CSS:

html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#C0C0C0;
    width:80%;
    overflow:auto;
    padding:10px;
}
nav {
    width:20%;
    height:auto;
    overflow:hidden;
}
.navcont {
    background:#00FF00;
    width:auto;
}
.handle {
    background:#800000;
    float:right;
    width:30px;
}
footer {
    text-align:center;
}

And a running example: https://jsfiddle.net/etwphhc8/

I tried many different solutions, from many different questions/answers here, but still haven't make it work as intended. So, how can I achieve the wanted layout using CSS?

Body:
Add flex with the direction set to row in nav:

nav {
  width:20%;
  height:auto;
  overflow:hidden;
  display:flex;
}


问:
Python image recognition - accessing the dataset
I'm writing a Python program to recognize characters on images. I've already chosen a method of recognition and it's not what I'm having the problem with. It's the dataset access that bothers me. We are given a training dataset (pickle file), which contains images stored in a form of a single matrix (NxD). Each row is one, 60x60 image. We are supposed to implement a function that for matrix X will give us a vector y of predicted class of labels (label being {0...35} - a character/digit that's recognized on the image).

Now, I've read on the topic and all, I'm using HOG for feature extraction, along with a get_features function. I can't understand though how am I supposed to assign x_train and x_val, as well as y_train and y_val, having only what I have in my .pkl file. I decided to try and split the dataset into x_train and x_val randomly, 50-50. I'm getting y vector filled along the way, so should I split it up to get y_val as well? So far, I have this code for my final function (+ first I load the data):

```<code>def load_data():
    PICKLE_FILE_PATH = 'train.pkl'
    with open(PICKLE_FILE_PATH, 'rb') as f:
        return pkl.load(f)

def final():
    """
    :param x: matrix NxD
    :return: vector Nx1
    """
    train = load_data()
    x = get_features(train['x'])
    N, D = x.shape
    y = np.zeros((N, 1))
    np.random.shuffle(x)
    x_train = x[:50]
    x_val = x[50:]
    # calling functions i'm using for recognition....
    return y
</code>```

Now, I'm getting an error that says:

```<code>    x = get_features(train['x'])
TypeError: tuple indices must be integers or slices, not str
</code>```

After analyzing it for forever, I assume that in .pkl, the (NxD) matrix has one element per row, since it's supposed to contain one image per row. Maybe I'm seeing it wrong? Maybe there is no 'x' in .pkl yet, just a nameless matrix? I got lost and I just want to understand how to transform that bit of data I'm given in the .pkl file to my familiar variables, x_train, x_val, y_train, y_val which I all need for recognition. Any tips would be great!

答:
if you want the first elemnt of a tuple you must do:</p>

```<code>x = get_features(train[0])
</code>```

Body:
I'm writing a Python program to recognize characters on images. I've already chosen a method of recognition and it's not what I'm having the problem with. It's the dataset access that bothers me. We are given a training dataset (pickle file), which contains images stored in a form of a single matrix (NxD). Each row is one, 60x60 image. We are supposed to implement a function that for matrix X will give us a vector y of predicted class of labels (label being {0...35} - a character/digit that's recognized on the image).

Now, I've read on the topic and all, I'm using HOG for feature extraction, along with a get_features function. I can't understand though how am I supposed to assign x_train and x_val, as well as y_train and y_val, having only what I have in my .pkl file. I decided to try and split the dataset into x_train and x_val randomly, 50-50. I'm getting y vector filled along the way, so should I split it up to get y_val as well? So far, I have this code for my final function (+ first I load the data):

def load_data():
    PICKLE_FILE_PATH = 'train.pkl'
    with open(PICKLE_FILE_PATH, 'rb') as f:
        return pkl.load(f)

def final():
    """
    :param x: matrix NxD
    :return: vector Nx1
    """
    train = load_data()
    x = get_features(train['x'])
    N, D = x.shape
    y = np.zeros((N, 1))
    np.random.shuffle(x)
    x_train = x[:50]
    x_val = x[50:]
    # calling functions i'm using for recognition....
    return y

Now, I'm getting an error that says:

    x = get_features(train['x'])
TypeError: tuple indices must be integers or slices, not str

After analyzing it for forever, I assume that in .pkl, the (NxD) matrix has one element per row, since it's supposed to contain one image per row. Maybe I'm seeing it wrong? Maybe there is no 'x' in .pkl yet, just a nameless matrix? I got lost and I just want to understand how to transform that bit of data I'm given in the .pkl file to my familiar variables, x_train, x_val, y_train, y_val which I all need for recognition. Any tips would be great!

Body:
if you want the first elemnt of a tuple you must do:

x = get_features(train[0])


问:
Unable to install Docker on Ubuntu 17
I am installing Docker by following this official tutorial. It doesn't work for me. Is it because I am using Ubuntu 17?

```<code>sudo apt-get install docker-ce
</code>```

the error is

"E: Package 'docker-ce' has no installation candidate"

I did all the apt-get update.

looks like can not find docker-ce package. What should I do?

答:
The Docker installation package available in the official Ubuntu repository may not be the latest version. To get the latest and greatest version, install Docker from the official Docker repository. This section shows you how to do just that.

https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-16-04

Title: Unable to install Docker on Ubuntu 17

Body:
I am installing Docker by following this official tutorial. It doesn't work for me. Is it because I am using Ubuntu 17?

sudo apt-get install docker-ce

the error is

"E: Package 'docker-ce' has no installation candidate"

I did all the apt-get update.

looks like can not find docker-ce package. What should I do?


问:
Transaction with trigger that use a select max. It return wrong result
I have an complex database. I can simplify it like that:

The table a:

```<code>CREATE TABLE a
(
Id int(10) unsigned NOT NULL AUTO_INCREMENT,
A int(11) DEFAULT NULL,
CalcUniqId int(11) DEFAULT NULL,
PRIMARY KEY (Id)
) ENGINE=InnoDB;

CREATE TRIGGER a_before_ins_tr before INSERT on a
FOR EACH ROW
BEGIN
  select Max(CalcUniqId) from A into @MaxCalcUniqId;
  set new.CalcUniqId=IfNull(@MaxCalcUniqId,1)+1;
END $
</code>```

It works like that:

```<code>start transaction
insert into A(A)
... insert in other tables. It take between 30 and 60 seconds
commit;
</code>```

The problem is, the trigger returns the same CalcUniqId for all transaction that run at the same time.

Is there any solution or work arround.

Is this a solution:

```<code>start transaction;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
insert into A(A) values(10);
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
....
commit;
</code>```

Man can run this test:

Session 1:

```<code>Step1: start transaction;
Step2: insert into A(A) values(1);
Step3: commit;
</code>```

Session 2:

```<code>Step1: start transaction;
Step2: insert into A(A) values(2);
Step3: commit;
</code>```

Run in session 1 the steps 1,2 and in session 2 the steps 1,2. than step 3 in both. After that do

```<code>select Id, A, CalcUniqId from a;
</code>```

both have the same CalcUniqId=2.

答:
Change the SELECT in the Trigger to this:

```<code>select Max(CalcUniqId) from A into @MaxCalcUniqId
    FOR UPDATE;   -- add this
</code>```

That tells the transaction that you intend to change the value; that blocks the other transactions from changing it.

This will probably lead to your 30-60 sec transactions being run one after another.  And probably dying due to exceeding lock_wait_timeout.  Rather than increasing that setting (which is already "too high"), please explain the bigger picture.  Perhaps we can concoct a workaround that gets the 'correct' value and runs in parallel.

Body:
I have an complex database. I can simplify it like that:

The table a:

CREATE TABLE a
(
Id int(10) unsigned NOT NULL AUTO_INCREMENT,
A int(11) DEFAULT NULL,
CalcUniqId int(11) DEFAULT NULL,
PRIMARY KEY (Id)
) ENGINE=InnoDB;

CREATE TRIGGER a_before_ins_tr before INSERT on a
FOR EACH ROW
BEGIN
  select Max(CalcUniqId) from A into @MaxCalcUniqId;
  set new.CalcUniqId=IfNull(@MaxCalcUniqId,1)+1;
END $

It works like that:

start transaction
insert into A(A)
... insert in other tables. It take between 30 and 60 seconds
commit;

The problem is, the trigger returns the same CalcUniqId for all transaction that run at the same time.

Is there any solution or work arround.

Is this a solution:

start transaction;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
insert into A(A) values(10);
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
....
commit;

Man can run this test:

Session 1:

Step1: start transaction;
Step2: insert into A(A) values(1);
Step3: commit;

Session 2:

Step1: start transaction;
Step2: insert into A(A) values(2);
Step3: commit;

Run in session 1 the steps 1,2 and in session 2 the steps 1,2. than step 3 in both. After that do

select Id, A, CalcUniqId from a;

both have the same CalcUniqId=2.

Body:
Change the SELECT in the Trigger to this:

select Max(CalcUniqId) from A into @MaxCalcUniqId
    FOR UPDATE;   -- add this

That tells the transaction that you intend to change the value; that blocks the other transactions from changing it.

This will probably lead to your 30-60 sec transactions being run one after another.  And probably dying due to exceeding lock_wait_timeout.  Rather than increasing that setting (which is already "too high"), please explain the bigger picture.  Perhaps we can concoct a workaround that gets the 'correct' value and runs in parallel.


问:
Issue returning a Hashmap from a TestNg DataProvider
I am pretty new to Java and TestNg.  I have created the below DataProvider to return a hashmap to my test method but it seems to be failing and I can't work out where the issue is.  I am reading an excel file into a hashmap and storing this in the list.  I then want to return the hashmap in the object.

Any advice appreciated

```<code>@DataProvider(name = "DataProvider")
public Object[][] getTestData() throws Exception {
    LogUtil.error("in provider");
    ExcelUtils.setExcelFile("C://testData.xlsx", "Sheet1");

    int rowsUsed = ExcelUtils.getRowUsed();
    int colsUsed = ExcelUtils.getColumns();

    List<HashMap<String, String>> arrayMapList = new ArrayList<>();
    HashMap<String, String> map;

    for (int i = 0; i < rowsUsed; i++) {
        map = new HashMap<>();
        for (int j = 0; j < colsUsed; j++) {
            map.put(ExcelUtils.getCellData(0, j), ExcelUtils.getCellData(i +1, j));
        }

        arrayMapList.add(map);
    }

    Object[][] obj = new Object[rowsUsed][1];

    for (int i = 0; i <arrayMapList.size(); i++) {
        obj[i][0] = arrayMapList.get(i);
    }
    return obj;
}
</code>```

答: Changing the method to static fixed the issue.  As answered by RocketRaccoon I had to change it to static because the data provider was in a different class to the tests.</p>

Body:
I am pretty new to Java and TestNg.  I have created the below DataProvider to return a hashmap to my test method but it seems to be failing and I can't work out where the issue is.  I am reading an excel file into a hashmap and storing this in the list.  I then want to return the hashmap in the object.

Any advice appreciated

@DataProvider(name = "DataProvider")
public Object[][] getTestData() throws Exception {
    LogUtil.error("in provider");
    ExcelUtils.setExcelFile("C://testData.xlsx", "Sheet1");

    int rowsUsed = ExcelUtils.getRowUsed();
    int colsUsed = ExcelUtils.getColumns();

    List<HashMap<String, String>> arrayMapList = new ArrayList<>();
    HashMap<String, String> map;

    for (int i = 0; i < rowsUsed; i++) {
        map = new HashMap<>();
        for (int j = 0; j < colsUsed; j++) {
            map.put(ExcelUtils.getCellData(0, j), ExcelUtils.getCellData(i +1, j));
        }

        arrayMapList.add(map);
    }

    Object[][] obj = new Object[rowsUsed][1];

    for (int i = 0; i <arrayMapList.size(); i++) {
        obj[i][0] = arrayMapList.get(i);
    }
    return obj;
}


问:
How to exclude multiple groups when using dependencies with gradle
Just like this code:

```<code>dependencies {
    compile ('com.wdullaer:materialdatetimepicker:3.2.2') {
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'design'
    }
}
</code>```

In an android app build.gradle file, when I want to dependency a remote library, how to use exclude group syntax to exclude multiple groups?

Although the code above is a right way, but it`s a little bit complicated.Is there a simpler way?

答:
Well basically 'exclude' is just a method belongs to 'ModuleDependency' class which accepts a 'Map' of 'group' and 'module' and there's no way to pass more.

However you can use 'Groovy' power in this case and for each 'group' from list to call method 'exclude' on 'ModuleDependency' and to pass current 'group'. Take a look at approximate code below.

```<code>compile() { dep ->
    [group1, group2].each{ group -> dep.exclude group: group }
}
</code>```

Body:
Just like this code:

dependencies {
    compile ('com.wdullaer:materialdatetimepicker:3.2.2') {
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'design'
    }
}

In an android app build.gradle file, when I want to dependency a remote library, how to use exclude group syntax to exclude multiple groups?

Although the code above is a right way, but it`s a little bit complicated.Is there a simpler way?

Body:
Well basically 'exclude' is just a method belongs to 'ModuleDependency' class which accepts a 'Map' of 'group' and 'module' and there's no way to pass more.

However you can use 'Groovy' power in this case and for each 'group' from list to call method 'exclude' on 'ModuleDependency' and to pass current 'group'. Take a look at approximate code below.

compile() { dep ->
    [group1, group2].each{ group -> dep.exclude group: group }
}


问:
Find entity with latest date using Spring Data with MongoDB
Given next object structure:

```<code>class Foo {
  @Id
  String id;
  LocalDate date;
  ...
}
</code>```

We store these objects in MongoDB. Is there any possibility to get entity with the latest date via MongoRepository like in the next example?

```<code>interface FooRepository extends MongoRepository<Foo, String> {
    @Query(???)
    Foo getByLatestDate(LocalDate date);
}
</code>```

答:
You can try below query.

Using @Query annotation

```<code>@Query("{ 'date' : ?0 }")
Foo getByLatestDate(LocalDate date);
</code>```

Or

Using repository supported keywords

```<code>Foo findByDate(LocalDate date);
</code>```

Update: Use below query to get latest date.

```<code>Foo findFirstByOrderByDateDesc();

Foo findTopByOrderByDateDesc();
</code>```

Body:
Given next object structure:

class Foo {
  @Id
  String id;
  LocalDate date;
  ...
}

We store these objects in MongoDB. Is there any possibility to get entity with the latest date via MongoRepository like in the next example?

interface FooRepository extends MongoRepository<Foo, String> {
    @Query(???)
    Foo getByLatestDate(LocalDate date);
}

Body:
You can try below query.

Using @Query annotation

@Query("{ 'date' : ?0 }")
Foo getByLatestDate(LocalDate date);

Or

Using repository supported keywords

Foo findByDate(LocalDate date);

Update: Use below query to get latest date.

Foo findFirstByOrderByDateDesc();

Foo findTopByOrderByDateDesc();


问:
String lexical order compare function is not safe in Java?
I have this function isAsc(String a String b) in java to compare two string in lexical order

```<code>public static void quickSort(String[] arr, int low, int high) {
    if (arr == null || arr.length == 0)
        return;

    if (low >= high)
        return;

    int middle = low + (high - low) / 2;
    String pivot = arr[middle];

    int i = low;
    int j = high;

    while (i <= j) {
        while (isAsc(arr[i], pivot) == true)
            i++;

        while (isAsc(pivot, arr[j]) == true)
            j--;

        if (i <= j) {
            String temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j--;
        }
    }
    if (low < j)
        quickSort(arr, low, j);
    if (high > i)
        quickSort(arr, i, high);
}

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length()) {
        return true;
    } else if (a.length() == b.length()) {
        boolean yep = true;
        for (int i =0; i < a.length(); ++i) {
            if (a.charAt(i) < b.charAt(i)) {
                continue;
            } else {
                yep = false;
                break;
            }
        }
        return yep;
    } else {
        return false;
    }
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
      String[] unsorted = new String[n];
      for(int unsorted_i=0; unsorted_i < n; unsorted_i++){
         unsorted[unsorted_i] = in.next();
    }

    quickSort(unsorted, 0, n - 1);
    for (int i = 0; i < n; i++) {
        System.out.println(unsorted[i]);
    }
}
</code>```

Basically, I will compare same-length strings in lexical order, and I consider a==b and a>b case as non-ascending. It works for two strings. But when I invoke this function in another quick sort function as comparison function, it will fail to sort some String array for me. For example, if I pass in this case:

```<code>100
6046724675206781253805417697364063874537349942332939012160502967377173420319837265456476
72091970412420810
3746855980099062683149629582771
4763506513
4381858583387279277494367930538
195294541694873319042720380485249001380825565396311663127260228626400961443707964165554187168383846
57500297590012603652986133599394871645776460
3443449340302668605052308
799898013447209990576845913871859165418584121624031762316631
3300953792
8
63593696
24851084103
407248179926838952899179921191873979655396776466610725637337844938107386865231
347055068146981261045909920471491104435367358281493074132530787003286631891260
84617645710
79889616038675409793789137873748992624206633449485792697950955
89010681446075323502110552896366
56055923387811165695520181970960556995748385
982252143663373494231929681150950636211
689652207582048074063885557314598131439882640463089732166634627009727882839802329
103760370650030890704420196453564751405138564548779976442730
2568508222553899614989132
595511428927857027243741014585070698077724714702592038259539625900191041
2006589875623412145878326
5346081954679885708665439539884162946087234174562850518034347368864646546761391881199484426332
41417855736231689319726325108873908732322628
82
4513813970506423806366556964549587926118285563093984149180914445198582562248005532967426935363394
189464003228859631246844678939878442100631407094488634370181145
6766894084508701303181966954454442649
617218738782517673738696836650709347
138693350046179064920029198428
69689336023779290
3123578614526005010789440062175923385894745490067711730621296066747362
6920677972668613791679
98727463407922846430489331897187874972506399980149269216341792683934266326553372651336825100910502
887419023647277091177508895423672748680390346760451960405476096892458561446000021772
357047822507894621064882425810251495984339153706718863150434921883251916931938
721655363593196254631465218524410129464006729720524491959093939538800477879025
399461832935777584631551322242458863336488933972064475755775387970693429489605542902103453
4879666158760447227244804904490661525075569972625784785166402241961211585507098
424250809729923008382471798976997991102352666012166168135388490453419791993437348248692902
96648
3499362168023660581620889357853145012397063659728
44
75655297913491802872733439380949625942090642103288135379733240968108838187718699296561107131
6730285737803282364443175816103191082917262371727029128242169800609774
2226233916493298335782492406184
702616993760099773277701
6459413133895599543512093010172681584992295387756374602296715030084689407214761953434
88151
48048060500795311454501362396164002281
13350830253644406272592098943542479448539695237424116030768219886
8602096560157018758
4285137293297191396703
59064571843258418539809783946176028799168327197
7352625455571982316988892359385804345281600126036030867648944342681034
841914798700287274894330827423742367016300562418119497681768534733683171159
966
871937317295006166948610659392371453127620
97717671655657189481516207050719062493363178584
44466191365953341779604153931359991009249825932467038
4900146572543628830293235422623540449026979
663851293951736587506669665707856376236045468061542850096311090080985050730443008535949871380862
3266084681485344181145502865406724087976265728762903576706273055985600897547821990716776855603
3027671510958920867119822769967026975150513671872284364883316076664947814983178816236371615
6075082871705572350813503266092842439231032244
226308783007518652278892711651945969504116481446022861103004230456764884348840645054713740
4827062832427344897934914852861881127816196306013748993413309020967615943118038713
82226197486758707862569829863301345843404256425288167712035595632448134024
6853035336068603185837379598609710965901821183057340152937719965
96144167763113033526215836335259504732455722379148990370590444393
497010206818067722087306230802257700034825862515267073569769100385728461314
8029462867402623010267220669038328276828159277704969882249658925340931197482
29961611875126871444847810377719588732057005401
7140136715304755447794330632416535814668937888353462780963074
86212388
139324591
2531882366050391355575974134566968043538613212060996149075948904530719392416580359757169745461988195
2306089645405831114107370739922985090810725635160947600829254949567811391
527417408764964324623612928827357473756502731555819746574832578277354817830480916093943535732
166782206349090
5039608483812
22779394003240991729940635387402457235717080073
23174884008941354054844994242306457670422886007267519294811553498520062981088
9379888465970151122427941852081839147561125428377120361098516
4851370931160622254599150919117874463729978188996483031702235879658066666
263962446402901234512400757004778715587484543679574154252814321
386080725531661023940341523726123830253452637178276277203272636730408946001853813544261847
506026518112695319049401500113438880015883164168786587087613685577329244826505995
853765766003041571727941982752375129846256362542268503538675723550767627646485
64915691514101937300896922107778765032041587836421804752327362
9235574571590973726389090392147619820135193089943052820464889147983825
794262758048207670029386770065222950113126
91478800
32687310632916086625372418455638163341778982284204
783034075100973917425178065924838816191619704361135719202582740172462892170122963273533820990331
273617602525557769852631252187557240898061262540420559773149091644393300751865108665599596695445
360949692042264211417548128414147307892643411000394876422352
</code>```

And my result will be:

```<code>8
44
82
966
88151
96648
91478800
63593696
86212388
139324591
4763506513
3300953792
84617645710
24851084103
5039608483812
166782206349090
69689336023779290
72091970412420810
8602096560157018758
6920677972668613791679
4285137293297191396703
702616993760099773277701
2006589875623412145878326
3443449340302668605052308
2568508222553899614989132
138693350046179064920029198428
2226233916493298335782492406184
3746855980099062683149629582771
4381858583387279277494367930538
89010681446075323502110552896366
617218738782517673738696836650709347
6766894084508701303181966954454442649
48048060500795311454501362396164002281
982252143663373494231929681150950636211
794262758048207670029386770065222950113126
871937317295006166948610659392371453127620
4900146572543628830293235422623540449026979
56055923387811165695520181970960556995748385
41417855736231689319726325108873908732322628
57500297590012603652986133599394871645776460
6075082871705572350813503266092842439231032244
22779394003240991729940635387402457235717080073
97717671655657189481516207050719062493363178584
29961611875126871444847810377719588732057005401
59064571843258418539809783946176028799168327197
3499362168023660581620889357853145012397063659728
32687310632916086625372418455638163341778982284204
44466191365953341779604153931359991009249825932467038
[encoded data, 4097 characters]
</code>```

where these four strings are not sorted in place:

```<code>22779394003240991729940635387402457235717080073
97717671655657189481516207050719062493363178584
29961611875126871444847810377719588732057005401
59064571843258418539809783946176028799168327197
</code>```

I'm sure quickSort is correct and safe, because if I rewrite my isAsc function to:

```<code>private static boolean isAsc(String a, String b) {
    if (a.length() < b.length()) {
        return true;
    } else if (a.length() == b.length()) {
        if (a.compareTo(b) >= 0) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
</code>```

my program will pass the test case. In my view I didn't see there's anything wrong with my first approach, but why it failed to sort some of the strings?

答:
When you compare two string, character by character, the logic should be:

If ch1 < ch2 then return true (it's definitely ascending)

If ch1 > ch2 then return false (it's definitely descending)

Otherwise compare next character

But that is not what your code is doing.

First, let's simplify your code, so it's easier to see what it's doing. Let's stop using else after a return, and flip the second test so we can just return.

```<code>private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    boolean yep = true;
    for (int i =0; i < a.length(); ++i) {
        if (a.charAt(i) < b.charAt(i)) {
            continue;
        } else {
            yep = false;
            break;
        }
    }
    return yep;
}
</code>```

Second, setting yep to false and breaking the loop is the same as simply returning false. Again, lets flip the test.

```<code>private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    boolean yep = true;
    for (int i =0; i < a.length(); ++i) {
        if (a.charAt(i) >= b.charAt(i))
            return false;
        continue;
    }
    return yep;
}
</code>```

Now the continue is redundant, and yep is always true.

```<code>private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    for (int i =0; i < a.length(); ++i)
        if (a.charAt(i) >= b.charAt(i))
            return false;
    return true;
}
</code>```

Finally, we can easily see the problem of if (a.charAt(i) >= b.charAt(i)) return false;, so lets fix it.

```<code>private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    for (int i = 0; i < a.length(); ++i) {
        if (a.charAt(i) < b.charAt(i))
            return true;
        if (a.charAt(i) > b.charAt(i))
            return false;
    }
    return true;
}
</code>```

Of course, to be consistent with your other version, that uses compareTo(), you should change that last statement to return false, so both return false when strings are equal. Doesn't really matter to result, but still ...

Body:
I have this function isAsc(String a String b) in java to compare two string in lexical order

public static void quickSort(String[] arr, int low, int high) {
    if (arr == null || arr.length == 0)
        return;

    if (low >= high)
        return;

    int middle = low + (high - low) / 2;
    String pivot = arr[middle];

    int i = low;
    int j = high;

    while (i <= j) {
        while (isAsc(arr[i], pivot) == true)
            i++;

        while (isAsc(pivot, arr[j]) == true)
            j--;

        if (i <= j) {
            String temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j--;
        }
    }
    if (low < j)
        quickSort(arr, low, j);
    if (high > i)
        quickSort(arr, i, high);
}

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length()) {
        return true;
    } else if (a.length() == b.length()) {
        boolean yep = true;
        for (int i =0; i < a.length(); ++i) {
            if (a.charAt(i) < b.charAt(i)) {
                continue;
            } else {
                yep = false;
                break;
            }
        }
        return yep;
    } else {
        return false;
    }
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
      String[] unsorted = new String[n];
      for(int unsorted_i=0; unsorted_i < n; unsorted_i++){
         unsorted[unsorted_i] = in.next();
    }

    quickSort(unsorted, 0, n - 1);
    for (int i = 0; i < n; i++) {
        System.out.println(unsorted[i]);
    }
}

Basically, I will compare same-length strings in lexical order, and I consider a==b and a>b case as non-ascending. It works for two strings. But when I invoke this function in another quick sort function as comparison function, it will fail to sort some String array for me. For example, if I pass in this case:

100
6046724675206781253805417697364063874537349942332939012160502967377173420319837265456476
72091970412420810
3746855980099062683149629582771
4763506513
4381858583387279277494367930538
195294541694873319042720380485249001380825565396311663127260228626400961443707964165554187168383846
57500297590012603652986133599394871645776460
3443449340302668605052308
799898013447209990576845913871859165418584121624031762316631
3300953792
8
63593696
24851084103
407248179926838952899179921191873979655396776466610725637337844938107386865231
347055068146981261045909920471491104435367358281493074132530787003286631891260
84617645710
79889616038675409793789137873748992624206633449485792697950955
89010681446075323502110552896366
56055923387811165695520181970960556995748385
982252143663373494231929681150950636211
689652207582048074063885557314598131439882640463089732166634627009727882839802329
103760370650030890704420196453564751405138564548779976442730
2568508222553899614989132
595511428927857027243741014585070698077724714702592038259539625900191041
2006589875623412145878326
5346081954679885708665439539884162946087234174562850518034347368864646546761391881199484426332
41417855736231689319726325108873908732322628
82
4513813970506423806366556964549587926118285563093984149180914445198582562248005532967426935363394
189464003228859631246844678939878442100631407094488634370181145
6766894084508701303181966954454442649
617218738782517673738696836650709347
138693350046179064920029198428
69689336023779290
3123578614526005010789440062175923385894745490067711730621296066747362
6920677972668613791679
98727463407922846430489331897187874972506399980149269216341792683934266326553372651336825100910502
887419023647277091177508895423672748680390346760451960405476096892458561446000021772
357047822507894621064882425810251495984339153706718863150434921883251916931938
721655363593196254631465218524410129464006729720524491959093939538800477879025
399461832935777584631551322242458863336488933972064475755775387970693429489605542902103453
4879666158760447227244804904490661525075569972625784785166402241961211585507098
424250809729923008382471798976997991102352666012166168135388490453419791993437348248692902
96648
3499362168023660581620889357853145012397063659728
44
75655297913491802872733439380949625942090642103288135379733240968108838187718699296561107131
6730285737803282364443175816103191082917262371727029128242169800609774
2226233916493298335782492406184
702616993760099773277701
6459413133895599543512093010172681584992295387756374602296715030084689407214761953434
88151
48048060500795311454501362396164002281
13350830253644406272592098943542479448539695237424116030768219886
8602096560157018758
4285137293297191396703
59064571843258418539809783946176028799168327197
7352625455571982316988892359385804345281600126036030867648944342681034
841914798700287274894330827423742367016300562418119497681768534733683171159
966
871937317295006166948610659392371453127620
97717671655657189481516207050719062493363178584
44466191365953341779604153931359991009249825932467038
4900146572543628830293235422623540449026979
663851293951736587506669665707856376236045468061542850096311090080985050730443008535949871380862
3266084681485344181145502865406724087976265728762903576706273055985600897547821990716776855603
3027671510958920867119822769967026975150513671872284364883316076664947814983178816236371615
6075082871705572350813503266092842439231032244
226308783007518652278892711651945969504116481446022861103004230456764884348840645054713740
4827062832427344897934914852861881127816196306013748993413309020967615943118038713
82226197486758707862569829863301345843404256425288167712035595632448134024
6853035336068603185837379598609710965901821183057340152937719965
96144167763113033526215836335259504732455722379148990370590444393
497010206818067722087306230802257700034825862515267073569769100385728461314
8029462867402623010267220669038328276828159277704969882249658925340931197482
29961611875126871444847810377719588732057005401
7140136715304755447794330632416535814668937888353462780963074
86212388
139324591
2531882366050391355575974134566968043538613212060996149075948904530719392416580359757169745461988195
2306089645405831114107370739922985090810725635160947600829254949567811391
527417408764964324623612928827357473756502731555819746574832578277354817830480916093943535732
166782206349090
5039608483812
22779394003240991729940635387402457235717080073
23174884008941354054844994242306457670422886007267519294811553498520062981088
9379888465970151122427941852081839147561125428377120361098516
4851370931160622254599150919117874463729978188996483031702235879658066666
263962446402901234512400757004778715587484543679574154252814321
386080725531661023940341523726123830253452637178276277203272636730408946001853813544261847
506026518112695319049401500113438880015883164168786587087613685577329244826505995
853765766003041571727941982752375129846256362542268503538675723550767627646485
64915691514101937300896922107778765032041587836421804752327362
9235574571590973726389090392147619820135193089943052820464889147983825
794262758048207670029386770065222950113126
91478800
32687310632916086625372418455638163341778982284204
783034075100973917425178065924838816191619704361135719202582740172462892170122963273533820990331
273617602525557769852631252187557240898061262540420559773149091644393300751865108665599596695445
360949692042264211417548128414147307892643411000394876422352

And my result will be:

8
44
82
966
88151
96648
91478800
63593696
86212388
139324591
4763506513
3300953792
84617645710
24851084103
5039608483812
166782206349090
69689336023779290
72091970412420810
8602096560157018758
6920677972668613791679
4285137293297191396703
702616993760099773277701
2006589875623412145878326
3443449340302668605052308
2568508222553899614989132
138693350046179064920029198428
2226233916493298335782492406184
3746855980099062683149629582771
4381858583387279277494367930538
89010681446075323502110552896366
617218738782517673738696836650709347
6766894084508701303181966954454442649
48048060500795311454501362396164002281
982252143663373494231929681150950636211
794262758048207670029386770065222950113126
871937317295006166948610659392371453127620
4900146572543628830293235422623540449026979
56055923387811165695520181970960556995748385
41417855736231689319726325108873908732322628
57500297590012603652986133599394871645776460
6075082871705572350813503266092842439231032244
22779394003240991729940635387402457235717080073
97717671655657189481516207050719062493363178584
29961611875126871444847810377719588732057005401
59064571843258418539809783946176028799168327197
3499362168023660581620889357853145012397063659728
32687310632916086625372418455638163341778982284204
44466191365953341779604153931359991009249825932467038
[encoded data, 4097 characters]

where these four strings are not sorted in place:

22779394003240991729940635387402457235717080073
97717671655657189481516207050719062493363178584
29961611875126871444847810377719588732057005401
59064571843258418539809783946176028799168327197

I'm sure quickSort is correct and safe, because if I rewrite my isAsc function to:

private static boolean isAsc(String a, String b) {
    if (a.length() = 0) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

my program will pass the test case. In my view I didn't see there's anything wrong with my first approach, but why it failed to sort some of the strings?

Body:
When you compare two string, character by character, the logic should be:

If ch1 < ch2 then return true (it's definitely ascending)

If ch1 > ch2 then return false (it's definitely descending)

Otherwise compare next character

But that is not what your code is doing.

First, let's simplify your code, so it's easier to see what it's doing. Let's stop using else after a return, and flip the second test so we can just return.

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    boolean yep = true;
    for (int i =0; i < a.length(); ++i) {
        if (a.charAt(i) < b.charAt(i)) {
            continue;
        } else {
            yep = false;
            break;
        }
    }
    return yep;
}

Second, setting yep to false and breaking the loop is the same as simply returning false. Again, lets flip the test.

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    boolean yep = true;
    for (int i =0; i < a.length(); ++i) {
        if (a.charAt(i) >= b.charAt(i))
            return false;
        continue;
    }
    return yep;
}

Now the continue is redundant, and yep is always true.

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    for (int i =0; i < a.length(); ++i)
        if (a.charAt(i) >= b.charAt(i))
            return false;
    return true;
}

Finally, we can easily see the problem of if (a.charAt(i) >= b.charAt(i)) return false;, so lets fix it.

private static boolean isAsc(String a, String b) {
    if (a.length() < b.length())
        return true;
    if (a.length() > b.length())
        return false;
    for (int i = 0; i < a.length(); ++i) {
        if (a.charAt(i) < b.charAt(i))
            return true;
        if (a.charAt(i) > b.charAt(i))
            return false;
    }
    return true;
}

Of course, to be consistent with your other version, that uses compareTo(), you should change that last statement to return false, so both return false when strings are equal. Doesn't really matter to result, but still ...


问:
Website in wordpress redirects to old URL after migration
I had never done migrating a site on wordpress, I'll put step by step how I did, need to put the site on a new domain that are on the same server, so only the migrated files, the database is equal.

I copied all the files from the old wordpress to the new site folder,
I had the following result on the new site:
Home - The site carries the theme but a message appears: 404: PAGE OR FILE NOT FOUND.
newsite/wp-admin/ - redirect to oldsite/wp-admin/

I have the option in the site administrator old put the new URL but I'm afraid I could never access. it can go?

Thanks.

答:
STILL if nothing works

GOTO : www.yoursiteurl.com/wp-admin

['YES' IT WILL OPEN , if you have migrated correctly]

GOTO : Settings => General Tab =>

you will see two fields their

Wordpress Address URL  - Enter your site URL

Site Address URL  - Enter your site URL

Make URLs same in Both fields
SAVE changes

Enter your site URL in browser clear cache and reload
Yeahhh.... Worked for me

Enjoy

Dont forget  to modify  WP_Options table with your site URL details.
Take care
my site


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
Sometimes, data can be just data:</p>

```<code>files = {
   'total':  { count: 200, size: 3492834 },
   'office': { count: 25, size: 2344 },
   'exe':    { count: 30, size: 342344 },
   ...
}
</code>```

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

Body:
Sometimes, data can be just data:

files = {
   'total':  { count: 200, size: 3492834 },
   'office': { count: 25, size: 2344 },
   'exe':    { count: 30, size: 342344 },
   ...
}

OwnerDisplayName: Jimmy

LastEditorDisplayName: Jimmy


问:
Java parse String containing integers and multiple delimiters
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

```<code>"1,25,3-6,14,16-19"
</code>```

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

```<code>1,3,4,5,6,14,16,17,18,19,25
</code>```

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

```<code>List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}
</code>```

答: Take a look at the StringTokenizer.</p>

Body:
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

"1,25,3-6,14,16-19"

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

1,3,4,5,6,14,16,17,18,19,25

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}

Body: Take a look at the StringTokenizer.