问:
How to properly stop the Thread in Java?
I need a solution to properly stop the thread in Java.

I have IndexProcessorclass which implements the Runnable interface:

```<code>public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);

    @Override
    public void run() {
        boolean run = true;
        while (run) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                run = false;
            }
        }

    }
}
</code>```

And I have ServletContextListener class which starts and stops the thread:

```<code>public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        thread = new Thread(new IndexProcessor());
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (thread != null) {
            thread.interrupt();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}
</code>```

But when I shutdown tomcat, I get the exception in my IndexProcessor class:

```<code>2012-06-09 17:04:50,671 [Thread-3] ERROR  IndexProcessor Exception
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at lt.ccl.searchengine.processor.IndexProcessor.run(IndexProcessor.java:22)
    at java.lang.Thread.run(Unknown Source)
</code>```

I am using JDK 1.6. So the question is:

How can I stop the thread and not throw any exceptions?

P.S. I do not want to use .stop(); method because it is deprecated.

答:
I didn't get the interrupt to work in Android, so I used this method, works perfectly:</p>

```<code>boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }
</code>```

Body:
I need a solution to properly stop the thread in Java.

I have IndexProcessorclass which implements the Runnable interface:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);

    @Override
    public void run() {
        boolean run = true;
        while (run) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                run = false;
            }
        }

    }
}

And I have ServletContextListener class which starts and stops the thread:

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        thread = new Thread(new IndexProcessor());
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (thread != null) {
            thread.interrupt();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}

But when I shutdown tomcat, I get the exception in my IndexProcessor class:

2012-06-09 17:04:50,671 [Thread-3] ERROR  IndexProcessor Exception
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at lt.ccl.searchengine.processor.IndexProcessor.run(IndexProcessor.java:22)
    at java.lang.Thread.run(Unknown Source)

I am using JDK 1.6. So the question is:

How can I stop the thread and not throw any exceptions?

P.S. I do not want to use .stop(); method because it is deprecated.

Body:
I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }


来源: stackexchange

问:
if or condition produce "integer expression expected"
The following code produce error "integer expression expected":

```<code>for SOURCE_PATH in work/sources/*; do
    git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
    if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
        echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
    else
        echo "COMMIT FOR $SOURCE_PATH"
        git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
    fi
done
</code>```

Error is on line if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then. It seems [ "$SOMETHING_TO_COMMIT" -eq "0" ]or [ "$SOMETHING_TO_COMMIT" -eq "" ] should produce integer.

How to fix that ?

答:
The second test compares the variable with an empty string (""), but using -eq which is for integers only, so you should change it to the = operator:</p>

```<code> if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" = "" ] ; then
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following code produce error "integer expression expected":

for SOURCE_PATH in work/sources/*; do
    git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
    if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
        echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
    else
        echo "COMMIT FOR $SOURCE_PATH"
        git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
    fi
done

Error is on line if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then. It seems [ "$SOMETHING_TO_COMMIT" -eq "0" ]or [ "$SOMETHING_TO_COMMIT" -eq "" ] should produce integer.

How to fix that ?

Body:
The second test compares the variable with an empty string (""), but using -eq which is for integers only, so you should change it to the = operator:

 if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" = "" ] ; then


问:
How does MbUnit work with VS 2008
I set up MbUnit and have been trying to get it to work with VS 2008 using the MbUnit GUI but every time I run a test it closes and I get a this program needs to close error.

I had a similar problem with Gallio where I got a runner exception every time I ran a test.

Do I need an addin for VS like testDriven.Net to get this to work?

答:
I'd recommend testdriven.net for a free tool, and ReSharper as a better tool for running MbUnit tests.

The Gallio test running shouldn't be crashing on you like that, there is a problem somewhere.

OwnerDisplayName: Calum

LastEditorDisplayName: Kent Fredric

ContentLicense: CC BY-SA 2.5

Title: How does MbUnit work with VS 2008

OwnerDisplayName: Lance Fisher


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答:
Yes, the var keyword is only allowed for local variables.

It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var keyword in a local scope.

Additionally, it never works to use the var keyword without specifying a value, as that is used to infer the data type:

```<code>var x = "asdf"; // works

var x; // doesn't work
</code>```

The normal way of declaring a variable is using a specific data type. Use the var keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:

```<code>var x = new { Key = 42, Name = "asdf" };

var y = new System.Text.StringBuilder();
</code>```

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

Body:
Yes, the var keyword is only allowed for local variables.

It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var keyword in a local scope.

Additionally, it never works to use the var keyword without specifying a value, as that is used to infer the data type:

var x = "asdf"; // works

var x; // doesn't work

The normal way of declaring a variable is using a specific data type. Use the var keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:

var x = new { Key = 42, Name = "asdf" };

var y = new System.Text.StringBuilder();


问:
Android - Back button causes problems
I am trying to create an app that keeps track of the countries the user has visited. A country is selected from a drop down spinner and then a number is entered into a text field. The next screen should show the top three countries visited in order of frequency.

The first time you enter a country and frequency it works fine but the problem arises when you press the back button and then select a different country and enter another frequency, it does not assign the frequency to the correct country.

To give an example, if you first select Austria and Times Visited as 5 and the press next it shows:

```<code>Austria       5
Wales         0
Switzerland   0
</code>```

If you press back and then select Belgium and enter 10, it shows

```<code>Denmark       10
Austria       5
Wales         0
</code>```

If you go back for a third time and select Luxemburg and enter 15, it shows

```<code>Spain         15
Denmark       10
Austria       5
</code>```

It seems as though the countryList array is becoming out of sync from the spinner position and I am not sure how to fix it, any help would be much appreciated.

This is the first android app I have tried to make so there may be other mistakes of which I am not aware.

Thanks

Here is the first activity:

```<code>package com.example.country;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.util.Collections;

public class Select extends AppCompatActivity {

ImageView flagChoiceView;
Spinner spinnerCountry;
ArrayAdapter<CharSequence> adapter;
public static Button next2;
int elementPosition;

//Declaring all objects of type country
country Austria = new country("Austria");
country Belgium = new country("Belgium");
country Denmark = new country("Denmark");
country England = new country("England");
country France = new country("France");
country Germany = new country("Germany");
country Ireland = new country("Ireland");
country Italy = new country("Italy");
country Luxembourg = new country("Luxembourg");
country Portugal = new country("Portugal");
country Spain = new country("Spain");
country Sweden = new country("Sweden");
country Switzerland = new country("Switzerland");
country Wales = new country("Wales");

//Creating an array of type country in preparation for sorting
country[] countryList = {Austria, Belgium, Denmark,England,France,
        Germany,Ireland,Italy,Luxembourg,Portugal,Spain,Sweden,Switzerland,Wales};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    afterSecondClick();

    //Setting protocols for entering values into the text field
    final TextWatcher numberInput = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try{
                countryList[elementPosition].setFrequency(Integer.parseInt(s.toString()));
            }
            catch(NumberFormatException e)
            {
                countryList[elementPosition].setFrequency(0);
            }
        }

        @Override
        public void afterTextChanged(Editable s) { }
    };

    //Creating a listener for the input field
    EditText inputFrequency = (EditText)findViewById(R.id.inputFrequency);
    inputFrequency.addTextChangedListener(numberInput);

    //sortFunction(countryList);
    spinnerCountry = (Spinner)findViewById(R.id.dropdown);
    adapter = ArrayAdapter.createFromResource(this,R.array.country_list,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCountry.setAdapter(adapter);
    spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {

            flagChoiceView = (ImageView) findViewById(R.id.flagChoice);

            elementPosition = position;
           switch(position)
           {
               case 0:

                   flagChoiceView.setImageResource(R.drawable.austriaflag);
               break;

               case 1:
                   flagChoiceView.setImageResource(R.drawable.belgiumflag);
                   break;

               case 2:
                   flagChoiceView.setImageResource(R.drawable.denmarkflag);
                   break;

               case 3:
                   flagChoiceView.setImageResource(R.drawable.englandflag);
                   break;

               case 4:
                   flagChoiceView.setImageResource(R.drawable.franceflag);
                   break;

               case 5:
                   flagChoiceView.setImageResource(R.drawable.germanflag);
                   break;

               case 6:
                   flagChoiceView.setImageResource(R.drawable.irelandflag);
                   elementPosition = position;
                   break;

               case 7:
                   flagChoiceView.setImageResource(R.drawable.italyflag);
                   break;

               case 8:
                   flagChoiceView.setImageResource(R.drawable.luxembourgeflag);
                   break;

               case 9:
                   flagChoiceView.setImageResource(R.drawable.portugalflag);
                   break;

               case 10:
                   flagChoiceView.setImageResource(R.drawable.spainflag);
                   break;

               case 11:
                   flagChoiceView.setImageResource(R.drawable.swedenflag);
                   break;

               case 12:
                   flagChoiceView.setImageResource(R.drawable.switzerlandflag);
                   break;

               case 13:
                   flagChoiceView.setImageResource(R.drawable.walesflag);
                   break;

               default:
                   flagChoiceView.setImageResource(R.drawable.austriaflag);
                   break;

           }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}

//Linking the second activity to the third with a button click
public void afterSecondClick()
{
    next2 = (Button)findViewById(R.id.button);
    next2.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    sortFunction(countryList);

                    Intent proceedAgain = new Intent("com.example.country.Results");
                    proceedAgain.putExtra("firstCountry", countryList[13].getName());
                    proceedAgain.putExtra("secondCountry", countryList[12].getName());
                    proceedAgain.putExtra("thirdCountry", countryList[11].getName());
                    proceedAgain.putExtra("firstFrequency", countryList[13].getFrequency());
                    proceedAgain.putExtra("secondFrequency", countryList[12].getFrequency());
                    proceedAgain.putExtra("thirdFrequency", countryList[11].getFrequency());
                    startActivity(proceedAgain);
                    EditText inputFrequency=(EditText) findViewById(R.id.inputFrequency);
                    inputFrequency.setText("");

                }
            }
    );
}

//Declaring a new inner class known as country
private class country
{
    private String name;
    private int frequency;

    public country(String Name){
        this.name = Name;
        this.frequency = 0;
    }

    public country(){
        this.name = "";
        this.frequency = 0;
    }

    public void setFrequency(int freq){
        this.frequency = freq;
    }

    public int getFrequency(){
        return frequency;
    }

    public String getName(){
        return name;
    }
}

//Sorting algorithm from lowest frequency to highest
void sortFunction(country[] List){
    int count = 0;
    while(count < List.length){
        for(int n = 0; n < List.length - 1; n++){
            if(List[n].getFrequency() > List[n+1].getFrequency())
                swapFunction(List, n);
        }
        count++;
    }
}

//Counterpart Method to sortFunction
void swapFunction(country[] List, int m){
    country a, b, c;
    a = List[m];
    b = List[m+1];
    c = a;
    List[m+1] = c;
    List[m] = b;
}
}
</code>```

and here is the second activity:

```<code>package com.example.country;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

public class Results extends AppCompatActivity

{
//Inflation of GUI and toolbar for the activity
@Override
protected void onCreate(Bundle savedInstanceState)

{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Bundle extras = getIntent().getExtras();

    TextView countryOne = (TextView)findViewById(R.id.firstCountry);
    countryOne.setText(extras.getString("firstCountry"));

    TextView countryTwo = (TextView)findViewById(R.id.secondCountry);
    countryTwo.setText(extras.getString("secondCountry"));

    TextView countryThree = (TextView)findViewById(R.id.thirdCountry);
    countryThree.setText(extras.getString("thirdCountry"));

    TextView freqOne = (TextView)findViewById(R.id.firstFrequency);
    freqOne.setText(String.valueOf(extras.getInt("firstFrequency")));

    TextView freqTwo = (TextView)findViewById(R.id.secondFrequency);
    freqTwo.setText(String.valueOf(extras.getInt("secondFrequency")));

    TextView freqThree = (TextView)findViewById(R.id.thirdFrequency);
    freqThree.setText(String.valueOf(extras.getInt("thirdFrequency")));
}

}
</code>```

and the xml of the array is here:

```<code><resources>
<string name="app_name">COUNTry</string>
<string name="action_settings">Settings</string>
<string name="appName">Welcome!</string>
<string name="nextButtonValue">NEXT</string>
<string name="title_activity_select">Select</string>
<string-array name="country_list">
    <item>Austria</item>
    <item>Belgium</item>
    <item>Denmark</item>
    <item>England</item>
    <item>France</item>
    <item>Germany</item>
    <item>Ireland</item>
    <item>Italy</item>
    <item>Luxembourg</item>
    <item>Portugal</item>
    <item>Spain</item>
    <item>Sweden</item>
    <item>Switzerland</item>
</code>```

答:
Just you will be Add in MainActivity.java file Add this</p>

```<code>@Override
public void invokeDefaultOnBackPressed() {
    moveTaskToBack(true);
}
</code>```

Title: Android - Back button causes problems

Body:
I am trying to create an app that keeps track of the countries the user has visited. A country is selected from a drop down spinner and then a number is entered into a text field. The next screen should show the top three countries visited in order of frequency.

The first time you enter a country and frequency it works fine but the problem arises when you press the back button and then select a different country and enter another frequency, it does not assign the frequency to the correct country.

To give an example, if you first select Austria and Times Visited as 5 and the press next it shows:

Austria       5
Wales         0
Switzerland   0

If you press back and then select Belgium and enter 10, it shows

Denmark       10
Austria       5
Wales         0

If you go back for a third time and select Luxemburg and enter 15, it shows

Spain         15
Denmark       10
Austria       5

It seems as though the countryList array is becoming out of sync from the spinner position and I am not sure how to fix it, any help would be much appreciated.

This is the first android app I have tried to make so there may be other mistakes of which I am not aware.

Thanks

Here is the first activity:

package com.example.country;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.util.Collections;

public class Select extends AppCompatActivity {

ImageView flagChoiceView;
Spinner spinnerCountry;
ArrayAdapter<CharSequence> adapter;
public static Button next2;
int elementPosition;

//Declaring all objects of type country
country Austria = new country("Austria");
country Belgium = new country("Belgium");
country Denmark = new country("Denmark");
country England = new country("England");
country France = new country("France");
country Germany = new country("Germany");
country Ireland = new country("Ireland");
country Italy = new country("Italy");
country Luxembourg = new country("Luxembourg");
country Portugal = new country("Portugal");
country Spain = new country("Spain");
country Sweden = new country("Sweden");
country Switzerland = new country("Switzerland");
country Wales = new country("Wales");

//Creating an array of type country in preparation for sorting
country[] countryList = {Austria, Belgium, Denmark,England,France,
        Germany,Ireland,Italy,Luxembourg,Portugal,Spain,Sweden,Switzerland,Wales};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    afterSecondClick();

    //Setting protocols for entering values into the text field
    final TextWatcher numberInput = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try{
                countryList[elementPosition].setFrequency(Integer.parseInt(s.toString()));
            }
            catch(NumberFormatException e)
            {
                countryList[elementPosition].setFrequency(0);
            }
        }

        @Override
        public void afterTextChanged(Editable s) { }
    };

    //Creating a listener for the input field
    EditText inputFrequency = (EditText)findViewById(R.id.inputFrequency);
    inputFrequency.addTextChangedListener(numberInput);

    //sortFunction(countryList);
    spinnerCountry = (Spinner)findViewById(R.id.dropdown);
    adapter = ArrayAdapter.createFromResource(this,R.array.country_list,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCountry.setAdapter(adapter);
    spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {

            flagChoiceView = (ImageView) findViewById(R.id.flagChoice);

            elementPosition = position;
           switch(position)
           {
               case 0:

                   flagChoiceView.setImageResource(R.drawable.austriaflag);
               break;

               case 1:
                   flagChoiceView.setImageResource(R.drawable.belgiumflag);
                   break;

               case 2:
                   flagChoiceView.setImageResource(R.drawable.denmarkflag);
                   break;

               case 3:
                   flagChoiceView.setImageResource(R.drawable.englandflag);
                   break;

               case 4:
                   flagChoiceView.setImageResource(R.drawable.franceflag);
                   break;

               case 5:
                   flagChoiceView.setImageResource(R.drawable.germanflag);
                   break;

               case 6:
                   flagChoiceView.setImageResource(R.drawable.irelandflag);
                   elementPosition = position;
                   break;

               case 7:
                   flagChoiceView.setImageResource(R.drawable.italyflag);
                   break;

               case 8:
                   flagChoiceView.setImageResource(R.drawable.luxembourgeflag);
                   break;

               case 9:
                   flagChoiceView.setImageResource(R.drawable.portugalflag);
                   break;

               case 10:
                   flagChoiceView.setImageResource(R.drawable.spainflag);
                   break;

               case 11:
                   flagChoiceView.setImageResource(R.drawable.swedenflag);
                   break;

               case 12:
                   flagChoiceView.setImageResource(R.drawable.switzerlandflag);
                   break;

               case 13:
                   flagChoiceView.setImageResource(R.drawable.walesflag);
                   break;

               default:
                   flagChoiceView.setImageResource(R.drawable.austriaflag);
                   break;

           }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}

//Linking the second activity to the third with a button click
public void afterSecondClick()
{
    next2 = (Button)findViewById(R.id.button);
    next2.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    sortFunction(countryList);

                    Intent proceedAgain = new Intent("com.example.country.Results");
                    proceedAgain.putExtra("firstCountry", countryList[13].getName());
                    proceedAgain.putExtra("secondCountry", countryList[12].getName());
                    proceedAgain.putExtra("thirdCountry", countryList[11].getName());
                    proceedAgain.putExtra("firstFrequency", countryList[13].getFrequency());
                    proceedAgain.putExtra("secondFrequency", countryList[12].getFrequency());
                    proceedAgain.putExtra("thirdFrequency", countryList[11].getFrequency());
                    startActivity(proceedAgain);
                    EditText inputFrequency=(EditText) findViewById(R.id.inputFrequency);
                    inputFrequency.setText("");

                }
            }
    );
}

//Declaring a new inner class known as country
private class country
{
    private String name;
    private int frequency;

    public country(String Name){
        this.name = Name;
        this.frequency = 0;
    }

    public country(){
        this.name = "";
        this.frequency = 0;
    }

    public void setFrequency(int freq){
        this.frequency = freq;
    }

    public int getFrequency(){
        return frequency;
    }

    public String getName(){
        return name;
    }
}

//Sorting algorithm from lowest frequency to highest
void sortFunction(country[] List){
    int count = 0;
    while(count < List.length){
        for(int n = 0; n < List.length - 1; n++){
            if(List[n].getFrequency() > List[n+1].getFrequency())
                swapFunction(List, n);
        }
        count++;
    }
}

//Counterpart Method to sortFunction
void swapFunction(country[] List, int m){
    country a, b, c;
    a = List[m];
    b = List[m+1];
    c = a;
    List[m+1] = c;
    List[m] = b;
}
}

and here is the second activity:

package com.example.country;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

public class Results extends AppCompatActivity

{
//Inflation of GUI and toolbar for the activity
@Override
protected void onCreate(Bundle savedInstanceState)

{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Bundle extras = getIntent().getExtras();

    TextView countryOne = (TextView)findViewById(R.id.firstCountry);
    countryOne.setText(extras.getString("firstCountry"));

    TextView countryTwo = (TextView)findViewById(R.id.secondCountry);
    countryTwo.setText(extras.getString("secondCountry"));

    TextView countryThree = (TextView)findViewById(R.id.thirdCountry);
    countryThree.setText(extras.getString("thirdCountry"));

    TextView freqOne = (TextView)findViewById(R.id.firstFrequency);
    freqOne.setText(String.valueOf(extras.getInt("firstFrequency")));

    TextView freqTwo = (TextView)findViewById(R.id.secondFrequency);
    freqTwo.setText(String.valueOf(extras.getInt("secondFrequency")));

    TextView freqThree = (TextView)findViewById(R.id.thirdFrequency);
    freqThree.setText(String.valueOf(extras.getInt("thirdFrequency")));
}

}

and the xml of the array is here:

<resources>
<string name="app_name">COUNTry</string>
<string name="action_settings">Settings</string>
<string name="appName">Welcome!</string>
<string name="nextButtonValue">NEXT</string>
<string name="title_activity_select">Select</string>
<string-array name="country_list">
    <item>Austria</item>
    <item>Belgium</item>
    <item>Denmark</item>
    <item>England</item>
    <item>France</item>
    <item>Germany</item>
    <item>Ireland</item>
    <item>Italy</item>
    <item>Luxembourg</item>
    <item>Portugal</item>
    <item>Spain</item>
    <item>Sweden</item>
    <item>Switzerland</item>

Body:
Just you will be Add in MainActivity.java file Add this

@Override
public void invokeDefaultOnBackPressed() {
    moveTaskToBack(true);
}


问:
Google Drive API - 502 Bad Gateway
As of 7pm Eastern on 7/6/2017 all of my requests to the Google Drive API are returning 502 Bad Gateway error.  I even tried using Google API's Explorer in the browser and am getting the same error.

Here's an example:

Request:

```<code>GET https://www.googleapis.com/drive/v3/files?key={YOUR_API_KEY}
</code>```

Response:

```<code>502

content-length:  1613
content-type:  text/html; charset=UTF-8
date:  Thu, 06 Jul 2017 23:02:40 GMT

<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1,
width=device-width">
  <title>Error 502 (Server Error)!!1</title>
  <style>
    ...
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>502.</b> <ins>That’s an error.</ins>
  <p>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.  <ins>That’s all we know.</ins>
</code>```

Are others experiencing this problem?

答:
There was a widespread Google OAuth outage yesterday. Most Google service were affected.

https://www.google.com/appsstatus#hl=en-GB&v=status

Title: Google Drive API - 502 Bad Gateway

Body:
As of 7pm Eastern on 7/6/2017 all of my requests to the Google Drive API are returning 502 Bad Gateway error.  I even tried using Google API's Explorer in the browser and am getting the same error.

Here's an example:

Request:

GET https://www.googleapis.com/drive/v3/files?key={YOUR_API_KEY}

Response:

502

content-length:  1613
content-type:  text/html; charset=UTF-8
date:  Thu, 06 Jul 2017 23:02:40 GMT

<!DOCTYPE html>

  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1,
width=device-width">
  <title>Error 502 (Server Error)!!1</title>

502. That’s an error.

The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds.  That’s all we know.

Are others experiencing this problem?


问:
CSS change affect 2 elements?
I wanted to place one of menu pages into border with red background, so i used this CSS to do that:

```<code>.page-item-4  {
 border:3px; border-style:solid; border-color:#000; padding: 1em;background:
 red;font-weight: bold;
  }
</code>```

and works OK when you are on homepage, or some other page. when click on SHOP page both elements : "SHOP" and "Programmes personnalisés" got the same styling. Why ? I want only SHOP to use that styling. Can someone to tell me where is issue? Issue is present only in this page.

答:
add below css for current_page_item97 class   </p>

```<code><style type="text/css">
     .current_page_item97  {
        border:none !important;
        padding: 1em 0 !important;
        background: none !important;
        font-weight: 400 !important;
      }
      </style>
</code>```

Title: CSS change affect 2 elements?

Body:
I wanted to place one of menu pages into border with red background, so i used this CSS to do that:

.page-item-4  {
 border:3px; border-style:solid; border-color:#000; padding: 1em;background:
 red;font-weight: bold;
  }

and works OK when you are on homepage, or some other page. when click on SHOP page both elements : "SHOP" and "Programmes personnalisés" got the same styling. Why ? I want only SHOP to use that styling. Can someone to tell me where is issue? Issue is present only in this page.

Body:
add below css for current_page_item97 class

<style type="text/css">
     .current_page_item97  {
        border:none !important;
        padding: 1em 0 !important;
        background: none !important;
        font-weight: 400 !important;
      }
      </style>


问:
Matplotlib, synchronize time axis between scatter-, violin- and boxplot
In order to combine various informations with synchronised x-axis (a time axis, numpy.datetime64) I have written the following example:

```<code>import numpy as np
import matplotlib.pyplot as plt

x_axis = [np.datetime64("2016-01-01"), np.datetime64("2016-02-01")]
y_data = [3, 5]

fig = plt.figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)
ax3 = fig.add_subplot(313, sharex=ax1)

# Plot the scatter plot
ax1.scatter(x_axis, y_data)

# Now draw the violinplot and the boxplot
for (timestamp, y) in zip(x_axis, y_data):
    data = np.random.rand(100) + y
    ax2.violinplot(data,
                   positions=[timestamp],
                   widths=[np.timedelta64(500000, 's')])
#    ax3.boxplot(data,
#                positions=[timestamp],
#                widths=[np.timedelta64(10, 's')])
</code>```

The problem now is the third (commented) part: when defining the positions and withs in correct units everything works fine, so a scatterplot can be plotted on a time axis, but the boxplot fails when plotting the whiskers. I receive a TypeError: ufunc multiply cannot use operands with types dtype('float64') and dtype('<M8[D]').

Is there any way to properly draw a boxplot on a real time axis, so that synchronisation works as required?

PS: Note, the widths are in units seconds, if the time unit is too large, the violinplot is not smooth any more...

答: You should check out seaborn for this. There are multiple options for violinplot() to include a boxplot etc.

Body:
In order to combine various informations with synchronised x-axis (a time axis, numpy.datetime64) I have written the following example:

import numpy as np
import matplotlib.pyplot as plt

x_axis = [np.datetime64("2016-01-01"), np.datetime64("2016-02-01")]
y_data = [3, 5]

fig = plt.figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)
ax3 = fig.add_subplot(313, sharex=ax1)

# Plot the scatter plot
ax1.scatter(x_axis, y_data)

# Now draw the violinplot and the boxplot
for (timestamp, y) in zip(x_axis, y_data):
    data = np.random.rand(100) + y
    ax2.violinplot(data,
                   positions=[timestamp],
                   widths=[np.timedelta64(500000, 's')])
#    ax3.boxplot(data,
#                positions=[timestamp],
#                widths=[np.timedelta64(10, 's')])

The problem now is the third (commented) part: when defining the positions and withs in correct units everything works fine, so a scatterplot can be plotted on a time axis, but the boxplot fails when plotting the whiskers. I receive a TypeError: ufunc multiply cannot use operands with types dtype('float64') and dtype('<M8[D]').

Is there any way to properly draw a boxplot on a real time axis, so that synchronisation works as required?

PS: Note, the widths are in units seconds, if the time unit is too large, the violinplot is not smooth any more...


问:
Best way to dynamically get column names from oracle tables
We are using an extractor application that will export data from the database to csv files. Based on some condition variable it extracts data from different tables, and for some conditions we have to use UNION ALL as the data has to be extracted from more than one table. So to satisfy the UNION ALL condition we are using nulls to match the number of columns.

Right now all the queries in the system are pre-built based on the condition variable. The problem is whenever there is change in the table projection (i.e new column added, existing column modified, column dropped) we have to manually change the code in the application.

Can you please give some suggestions how to extract the column names dynamically so that any changes in the table structure do not require change in the code?

My concern is the condition that decides which table to query. The variable condition is
like

if the condition is A, then load from TableX

if the condition is B  then load from TableA and TableY.

We must know from which table we need to get data.  Once we know the table it is  straightforward to query the column names from the data dictionary.  But there is one more condition, which is that some columns need to be excluded, and these columns are different for each table.

I am trying to solve the problem only for dynamically generating the list columns. But my manager told me to make solution on the conceptual level rather than just fixing. This is a very big system with providers and consumers constantly loading and consuming data. So he wanted solution that can be general.

So what is the best way for storing condition, tablename, excluded columns?  One way is storing in database.   Are there any other ways? If yes what is the best?  As I have to give at least a couple of ideas before finalizing.

Thanks,

答:
So what you are really after is designing a rule engine for building dynamic queries.  This is no small undertaking.  The requirements you have provided are:

Store rules (what you call a "condition variable")

Each rule selects from one or more tables

Additionally some rules specify columns to be excluded from a table

Rules which select from multiple tables are satisfied with the UNION ALL operator; tables whose projections do not match must be brought into alignment with null columns.

Some possible requirements you don't mention:

Format masking e.g. including or excluding the time element of DATE columns

Changing the order of columns in the query's projection

The previous requirement is particularly significant when it comes to the multi-table rules, because the projections of the tables need to match by datatype as well as number of columns.

Following on from that, the padding NULL columns may not necessarily be tacked on to the end of the projection e.g. a three column table may be mapped to a four column table as col1, col2, null, col3.

Some multi-table queries may need to be satisfied by joins rather than set operations.

Rules for adding WHERE clauses.

A mechanism for defining default sets of excluded columns (i.e. which are applied every time a table is queried) .

I would store these rules in database tables.   Because they are data and storing data is what databases are for.  (Unless you already have a rules engine to hand.)

Taking the first set of requirements you need three tables:

```<code>RULES
-----
RuleID
Description
    primary key (RuleID)

RULE_TABLES
-----------
RuleID
Table_Name
Table_Query_Order
All_Columns_YN
No_of_padding_cols
    primary key (RuleID, Table_Name)

RULE_EXCLUDED_COLUMNS
---------------------
RuleID
Table_Name
Column_Name
    primary key (RuleID, Table_Name, Column_Name)
</code>```

I've used compound primary keys just because it's easier to work with them in this context e.g. running impact analyses; I wouldn't recommend it for regular applications.

I think all of these are self-explanatory except the additional columns on RULE_TABLES.

Table_Query_Order specifies the order in which the tables appear in UNION ALL queries; this matters only if you want to use the column_names of the leading table as headings in the CSV file.

All_Columns_YN indicates whether the query can be written as SELECT * or whether you need to query the column names from the data dictionary and the RULE_EXCLUDED_COLUMNS table.

No_of_padding_cols is a simplistic implementation for matching projections in those UNION ALL columns, by specifying how many NULLs to add to the end of the column list.

I'm not going to tackle those requirements you didn't specify because I don't know whether you care about them.  The basic thing is, what your boss is asking for is an application in its own right.  Remember that as well as an application for generating queries you're going to need an interface for maintaining the rules.

Body:
So what you are really after is designing a rule engine for building dynamic queries.  This is no small undertaking.  The requirements you have provided are:

Store rules (what you call a "condition variable")

Each rule selects from one or more tables

Additionally some rules specify columns to be excluded from a table

Rules which select from multiple tables are satisfied with the UNION ALL operator; tables whose projections do not match must be brought into alignment with null columns.

Some possible requirements you don't mention:

Format masking e.g. including or excluding the time element of DATE columns

Changing the order of columns in the query's projection

The previous requirement is particularly significant when it comes to the multi-table rules, because the projections of the tables need to match by datatype as well as number of columns.

Following on from that, the padding NULL columns may not necessarily be tacked on to the end of the projection e.g. a three column table may be mapped to a four column table as col1, col2, null, col3.

Some multi-table queries may need to be satisfied by joins rather than set operations.

Rules for adding WHERE clauses.

A mechanism for defining default sets of excluded columns (i.e. which are applied every time a table is queried) .

I would store these rules in database tables.   Because they are data and storing data is what databases are for.  (Unless you already have a rules engine to hand.)

Taking the first set of requirements you need three tables:

RULES
-----
RuleID
Description
    primary key (RuleID)

RULE_TABLES
-----------
RuleID
Table_Name
Table_Query_Order
All_Columns_YN
No_of_padding_cols
    primary key (RuleID, Table_Name)

RULE_EXCLUDED_COLUMNS
---------------------
RuleID
Table_Name
Column_Name
    primary key (RuleID, Table_Name, Column_Name)

I've used compound primary keys just because it's easier to work with them in this context e.g. running impact analyses; I wouldn't recommend it for regular applications.

I think all of these are self-explanatory except the additional columns on RULE_TABLES.

Table_Query_Order specifies the order in which the tables appear in UNION ALL queries; this matters only if you want to use the column_names of the leading table as headings in the CSV file.

All_Columns_YN indicates whether the query can be written as SELECT * or whether you need to query the column names from the data dictionary and the RULE_EXCLUDED_COLUMNS table.

No_of_padding_cols is a simplistic implementation for matching projections in those UNION ALL columns, by specifying how many NULLs to add to the end of the column list.

I'm not going to tackle those requirements you didn't specify because I don't know whether you care about them.  The basic thing is, what your boss is asking for is an application in its own right.  Remember that as well as an application for generating queries you're going to need an interface for maintaining the rules.


问:
Coroutine not starting
I'm using a lightning GameObject prefab to have a visual effect when i'm firing my weapon. When I fire, I enable that lightning object and I have a generic component that deactivates it after a certain delay.

The problem is that the "should wait" log is never reached, and instead of waiting the set delay, it waits much longer and doesn't actually deactivate the GameObject.

Here's the code for the DeactivateAfter component

public class DestroyAfter : MonoBehaviour {

    [SerializeField]
    private float delay;
    private bool firstRun = true;

    void OnEnable () {
        if (firstRun == false) {
            StartCoroutine(DestroyMethod());
        }
        firstRun = false;
    }

    public IEnumerator DestroyMethod() {
        Debug.LogFormat("Should wait; Time: {0}", Time.time);
        yield return new WaitForSeconds(delay);
        Debug.LogFormat("Should deactivate; Time: {0}", Time.time);
        gameObject.SetActive(false);
    }
}
```

答:
I think you should use particle system for your weapon fire. Anyway I think your code is not working because you are deactivating the game object instead of deactivating the component. Activate and deactivate your component using  something like this :

gameObject.GetComponent<YourComponent>().enabled = false;

Title: Coroutine not starting


问:
Creating Nested Class
I am trying to create a nested class in VBA.

So far I have successfully created the following:

```<code>OurCompany.Department.Employee("John")
</code>```

How can I create a few groups of Department so I can store the data seperately.
Something like this

```<code>OurCompany.Department("Finance").Employee("John") = "Employee Number 100"
OurCompany.Department("Finance").Employee("Kim") = "Employee Number 101"
OurCompany.Department("Engineering").Employee("Sam") = "Employee Number 124"
</code>```

cDeparment Class

```<code>Private pDepartmentEmployee As Collection
Public Property Get Department(RefString As String) As cEmployee

    Set Department = pDepartment.Item(RefString)

End Property

Public Property Set Department(RefString As String, ByVal objDepartEmployee As cEmployee)

    pDepartmentEmployee.Add objDepartEmployee, RefString

End Property
</code>```

cEmployee Class

```<code>Private pEmployee As Collection
Public Property Get Employee(RefKey As String) As String

    Employee = pEmployee.Item(RefKey)

End Property

Public Property Let Employee(RefKey As String, RefItem As String)

    pEmployee.Add Item:=RefItem, Key:=RefKey

End Property
</code>```

答:
I strongly suggest to read the answer in this post including any attached references.

Nevertheless, a simple implementation could be as follows.

Company Class:

```<code>Option Explicit
Private mDepartmentsList As Object

Public Property Get Department(ByVal StringKey As String) As Department
    With mDepartmentsList
        If Not .Exists(StringKey) Then
            Dim objDepartment As New Department
            .Add StringKey, objDepartment
        End If
    End With

    Set Department = mDepartmentsList(StringKey)
End Property

Public Property Get Keys() As Variant
    Keys = mDepartmentsList.Keys
End Property

Private Sub Class_Initialize()
    Set mDepartmentsList = CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
    Set mDepartmentsList = Nothing
End Sub
</code>```

Department Class:

```<code>Option Explicit
Private mEmployeesList As Object

Public Property Get Employee(ByVal StringKey As String) As String
    Employee = mEmployeesList(StringKey)
End Property

Public Property Let Employee(ByVal StringKey As String, ByVal StringValue As String)
    mEmployeesList(StringKey) = StringValue
End Property

Public Property Get Keys() As Variant
    Keys = mEmployeesList.Keys
End Property

Private Sub Class_Initialize()
    Set mEmployeesList = CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
    Set mEmployeesList = Nothing
End Sub
</code>```

Testing:

```<code>Option Explicit

Sub TestCompanyClass()

    Dim OurCompany As Company
    Set OurCompany = New Company

    With OurCompany
        .Department("Finance").Employee("John") = "Employee Number 100"
        .Department("Finance").Employee("Kim") = "Employee Number 101"
        .Department("Engineering").Employee("Sam") = "Employee Number 124"
    End With

    Dim d As Variant, e As Variant
    With OurCompany
        For Each d In .Keys
            Debug.Print "Department: " & d
            For Each e In .Department(d).Keys
                Debug.Print vbTab & "Employee: " & e & " - " & .Department(d).Employee(e)
            Next e
        Next d
    End With

    Set OurCompany = Nothing
End Sub
</code>```

Output:

```<code>Department: Finance
    Employee: John - Employee Number 100
    Employee: Kim - Employee Number 101
Department: Engineering
    Employee: Sam - Employee Number 124
</code>```

ContentLicense: CC BY-SA 4.0

Title: Creating Nested Class

Body:
I am trying to create a nested class in VBA.

So far I have successfully created the following:

OurCompany.Department.Employee("John")

How can I create a few groups of Department so I can store the data seperately.
Something like this

OurCompany.Department("Finance").Employee("John") = "Employee Number 100"
OurCompany.Department("Finance").Employee("Kim") = "Employee Number 101"
OurCompany.Department("Engineering").Employee("Sam") = "Employee Number 124"

cDeparment Class

Private pDepartmentEmployee As Collection
Public Property Get Department(RefString As String) As cEmployee

    Set Department = pDepartment.Item(RefString)

End Property

Public Property Set Department(RefString As String, ByVal objDepartEmployee As cEmployee)

    pDepartmentEmployee.Add objDepartEmployee, RefString

End Property

cEmployee Class

Private pEmployee As Collection
Public Property Get Employee(RefKey As String) As String

    Employee = pEmployee.Item(RefKey)

End Property

Public Property Let Employee(RefKey As String, RefItem As String)

    pEmployee.Add Item:=RefItem, Key:=RefKey

End Property

Body:
I strongly suggest to read the answer in this post including any attached references.

Nevertheless, a simple implementation could be as follows.

Company Class:

Option Explicit
Private mDepartmentsList As Object

Public Property Get Department(ByVal StringKey As String) As Department
    With mDepartmentsList
        If Not .Exists(StringKey) Then
            Dim objDepartment As New Department
            .Add StringKey, objDepartment
        End If
    End With

    Set Department = mDepartmentsList(StringKey)
End Property

Public Property Get Keys() As Variant
    Keys = mDepartmentsList.Keys
End Property

Private Sub Class_Initialize()
    Set mDepartmentsList = CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
    Set mDepartmentsList = Nothing
End Sub

Department Class:

Option Explicit
Private mEmployeesList As Object

Public Property Get Employee(ByVal StringKey As String) As String
    Employee = mEmployeesList(StringKey)
End Property

Public Property Let Employee(ByVal StringKey As String, ByVal StringValue As String)
    mEmployeesList(StringKey) = StringValue
End Property

Public Property Get Keys() As Variant
    Keys = mEmployeesList.Keys
End Property

Private Sub Class_Initialize()
    Set mEmployeesList = CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
    Set mEmployeesList = Nothing
End Sub

Testing:

Option Explicit

Sub TestCompanyClass()

    Dim OurCompany As Company
    Set OurCompany = New Company

    With OurCompany
        .Department("Finance").Employee("John") = "Employee Number 100"
        .Department("Finance").Employee("Kim") = "Employee Number 101"
        .Department("Engineering").Employee("Sam") = "Employee Number 124"
    End With

    Dim d As Variant, e As Variant
    With OurCompany
        For Each d In .Keys
            Debug.Print "Department: " & d
            For Each e In .Department(d).Keys
                Debug.Print vbTab & "Employee: " & e & " - " & .Department(d).Employee(e)
            Next e
        Next d
    End With

    Set OurCompany = Nothing
End Sub

Output:

Department: Finance
    Employee: John - Employee Number 100
    Employee: Kim - Employee Number 101
Department: Engineering
    Employee: Sam - Employee Number 124


问:
Curve on the top/bottom of a div or element
I am looking to achieve as shown:

I have tried border-radius on a pseudo element but the curve is ugly and smoothly as opposed to ending 'abruptly' with sharp corners - if you know what I mean.

The same div needs the same curve on the bottom, but inverted version of the one in image.
Also, considering an image:

How would I achieve this in CSS?

答:
You can use border-radius with different values for the vertical radius and the horizontal radius using the slash syntax:

.picture {
  border-radius: 50%/10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="picture" src="https://static-s.aa-cdn.net/img/ios/608437635/d606ff565c22f64d84e4c2195981c386?v=1"></code>```

Body:
You can use border-radius with different values for the vertical radius and the horizontal radius using the slash syntax:

.picture {
  border-radius: 50%/10%;
}

<img class="picture" src="https://static-s.aa-cdn.net/img/ios/608437635/d606ff565c22f64d84e4c2195981c386?v=1">


问:
Delivring a project in a VM(LINUX)
I have a project to work on using Joomla
So, My question is can I do the work in Windows and then deliver it in a VM(LINUX), or I have no choice,I have to do it in VM(LINUX).
Thanks

答:
Yes, you can.
You can set .htaccess and url friendly when you put it on Linux, the only thing that changes</p>

Title: Delivring a project in a VM(LINUX)


问:
How to use Retrofit2 to parse json into class with subclass(es)
How to convert given json response

```<code>{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}
</code>```

into

```<code>class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}
</code>```

It's all about nested Location class that is inside Person class

答:
Use a combination of Gson + Retrofit.

First of all use the annotation @SerializedName("yourFieldName") that Retrofit provides in the fields of your model class.

Init your Gson configuration with a RuntimeTypeAdapterFactory:

```<code>RuntimeTypeAdapterFactory<Person> itemFactory = RuntimeTypeAdapterFactory
        .of(Person.class) // The field that defines the type
        .registerSubtype(Location.class, "location")
        .registerSubtype(YourSubclass.class) // if the flag equals the class name, you can skip the second parameter.

Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(itemFactory)
        .create();
</code>```

Then you init Retrofit:

```<code>Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(BASE_URL);
builder.addConverterFactory(GsonConverterFactory.create(gson));

Retrofit retrofit = builder.build();
</code>```

Body:
How to convert given json response

{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}

into

class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}

It's all about nested Location class that is inside Person class

Body:
Use a combination of Gson + Retrofit.

First of all use the annotation @SerializedName("yourFieldName") that Retrofit provides in the fields of your model class.

Init your Gson configuration with a RuntimeTypeAdapterFactory:

RuntimeTypeAdapterFactory<Person> itemFactory = RuntimeTypeAdapterFactory
        .of(Person.class) // The field that defines the type
        .registerSubtype(Location.class, "location")
        .registerSubtype(YourSubclass.class) // if the flag equals the class name, you can skip the second parameter.

Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(itemFactory)
        .create();

Then you init Retrofit:

Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(BASE_URL);
builder.addConverterFactory(GsonConverterFactory.create(gson));

Retrofit retrofit = builder.build();


问:
Parsing XML to JSON in Amazon Lambda using external js libraries
I am trying to convert an XML String that I get from a server to JSON inside my Lambda function.

I have set up this rather simple example to simulate the XML answer that i get from the server using DynamoDB. (Currently I'm just trying to get the convertion going)

```<code>'use strict';

var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'});

exports.handler = function (e, ctx, callback){
    let table = "dsbTable";
    let bpNumber = 1337;
    var test;
    var x2js = new X2JS();
    let params = {
            TableName: table,
            Key:{
                "bpNumber": bpNumber
            },
        };
    docClient.get(params, function(err, data) {
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                callback(err, null);
            } else {
                console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
                console.log('test' +data.Item.getBp);
                //var jsonObj = x2js.xml_str2json(data.Item.getBp);
                //console.log(jsonObj);

                callback(null, data);
            }

    });

}  ;
</code>```

getting the item works just fine and is returned like this

```<code>{
  "Item": {
    "getBp": "<message version=\"1.0\" system=\"AVS/3\"><header><client>553</client><avs3-sales-organization>7564</avs3-sales-organization><avs3-service-provider>DSD</avs3-service-provider></header><body><business-partner><salutation-code>01</salutation-code><titel-code-academic/><titel-academic/><titel-code-royal/><titel-royal/><job-titel/><last-name1>Pickle</last-name1><last-name2/><first-name>N</first-name><street/><street-suffix/><street-number/><street-number-suffix/><address-line-1>10 Waterside Way</address-line-1><address-line-2/><address-line-3/><zipcode>NN4 7XD</zipcode><country-code>GB</country-code><city>NORTHAMPTON</city><district/><region-code>NH</region-code><region-text>Northamptonshire</region-text><company1/><company2/><company3/><department/><po-box/><po-box-zipcode/><po-box-city/><po-box-country-code/><major-customer-zipcode/><address-source/><advertisement>Y</advertisement><category/><bp-number>1100000772</bp-number><bp-number-external/><bp-group>ABON</bp-group><eu-sales-tax-number/><bic-master-number/><sector/><communication><communication-type>WW</communication-type><communication-value>kate.southorn@dsbnet.co.uk</communication-value><communication-default>Y</communication-default></communication><attribute><attribute-type>ACC</attribute-type><attribute-value>Y</attribute-value></attribute><attribute><attribute-type>OIEMEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OINLIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OISMEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OISMIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOEMIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOFXEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOFXIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOPTEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOPTIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOTEEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOTEIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>THEDSU</attribute-type><attribute-value/></attribute></business-partner></body></message>",
    "bpNumber": 1337
  }
}
</code>```

My main issue now is that I can not figure out how i can import any XMLtoJSON library files like this one here

I hope my code in this case is not completely worthless and there is a rather simple solution.

答: Always the handler name is the <filename>.<handler> function name> and if the filename is incorrectly mentioned then also such error is thrown in cloudwatch logs.

Body:
I am trying to convert an XML String that I get from a server to JSON inside my Lambda function.

I have set up this rather simple example to simulate the XML answer that i get from the server using DynamoDB. (Currently I'm just trying to get the convertion going)

'use strict';

var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'});

exports.handler = function (e, ctx, callback){
    let table = "dsbTable";
    let bpNumber = 1337;
    var test;
    var x2js = new X2JS();
    let params = {
            TableName: table,
            Key:{
                "bpNumber": bpNumber
            },
        };
    docClient.get(params, function(err, data) {
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                callback(err, null);
            } else {
                console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
                console.log('test' +data.Item.getBp);
                //var jsonObj = x2js.xml_str2json(data.Item.getBp);
                //console.log(jsonObj);

                callback(null, data);
            }

    });

}  ;

getting the item works just fine and is returned like this

{
  "Item": {
    "getBp": "<message version=\"1.0\" system=\"AVS/3\"><client>553</client><avs3-sales-organization>7564</avs3-sales-organization><avs3-service-provider>DSD</avs3-service-provider><business-partner><salutation-code>01</salutation-code><titel-code-academic/><titel-academic/><titel-code-royal/><titel-royal/><job-titel/><last-name1>Pickle</last-name1><last-name2/><first-name>N</first-name><street/><street-suffix/><street-number/><street-number-suffix/><address-line-1>10 Waterside Way</address-line-1><address-line-2/><address-line-3/><zipcode>NN4 7XD</zipcode><country-code>GB</country-code><city>NORTHAMPTON</city><district/><region-code>NH</region-code><region-text>Northamptonshire</region-text><company1/><company2/><company3/><department/><po-box/><po-box-zipcode/><po-box-city/><po-box-country-code/><major-customer-zipcode/><address-source/><advertisement>Y</advertisement><category/><bp-number>1100000772</bp-number><bp-number-external/><bp-group>ABON</bp-group><eu-sales-tax-number/><bic-master-number/><sector/><communication><communication-type>WW</communication-type><communication-value>kate.southorn@dsbnet.co.uk</communication-value><communication-default>Y</communication-default></communication><attribute><attribute-type>ACC</attribute-type><attribute-value>Y</attribute-value></attribute><attribute><attribute-type>OIEMEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OINLIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OISMEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OISMIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOEMIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOFXEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOFXIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOPTEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOPTIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOTEEX</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>OOTEIN</attribute-type><attribute-value>N20121211</attribute-value></attribute><attribute><attribute-type>THEDSU</attribute-type><attribute-value/></attribute></business-partner></message>",
    "bpNumber": 1337
  }
}

My main issue now is that I can not figure out how i can import any XMLtoJSON library files like this one here

I hope my code in this case is not completely worthless and there is a rather simple solution.


问:
SQL-Query for a table with a foreign-key-field that references other foreign-key-fields
I have the following structure of tables in my database:

```<code>[table workers]
ID [PK] | worker | combined [FK]
--------+--------+--------------+
1       | John   |    2
--------------------------------+
2       | Adam   |    1

[table combined]
ID [PK] | name   | helper [FK]
--------+----------------------+
1       | name1  |  1
2       | name2  |  2

[table helper]
ID [PK] | department [FK] | location [FK]
--------+-------------+-------------------
1       |       2         |     3
2       |       1         |     1

[table departments]
ID [PK] | department
--------+-------------+
1       | Development |
2       | Production  |

[table location]
ID [PK] | department
--------+--------------+
1       | Paris        |
2       | London       |
3       | Berlin       |
</code>```

The table "workers" has an foreign-key-field ("combined"). The table "combined" has a field name and a foreign-key-field "helper" which again is a table with two foreign-key-fields.

My question is now, what is the simplest SQL-Query to get the following table:

```<code>[table workers]
ID [PK] | worker | combined-Name| department | location
--------+--------+--------------+------------+-----------
1       | John   |    name2     | Development|   Paris
--------------------------------+------------+-----------
2       | Adam   |    name1     | Production |   Berlin
</code>```

I tried it already with some LEFT-JOINS but did not manage it to get all "clearnames" to the table "workers"

答:
This query would work:

```<code>SELECT w.ID, worker, c.name AS `combined-Name`, d.department, l.department as
location FROM workers w
LEFT JOIN combined c ON c.ID = w.combined
LEFT JOIN helper h ON h.ID = c.helper
LEFT JOIN departments d ON d.ID = h.department
LEFT JOIN location l ON l.ID = h.location
GROUP BY w.ID
</code>```

I used the AS keyword to set the names to your preferred output.

This was tested locally using the provided structures and data.

It's basically 4 simple left joins, and then instead of selecting the ID's I select the name columns of the foreign tables.

The alias on c.name is quoted because we need to escape the special character -

Body:
I have the following structure of tables in my database:

[table workers]
ID [PK] | worker | combined [FK]
--------+--------+--------------+
1       | John   |    2
--------------------------------+
2       | Adam   |    1

[table combined]
ID [PK] | name   | helper [FK]
--------+----------------------+
1       | name1  |  1
2       | name2  |  2

[table helper]
ID [PK] | department [FK] | location [FK]
--------+-------------+-------------------
1       |       2         |     3
2       |       1         |     1

[table departments]
ID [PK] | department
--------+-------------+
1       | Development |
2       | Production  |

[table location]
ID [PK] | department
--------+--------------+
1       | Paris        |
2       | London       |
3       | Berlin       |

The table "workers" has an foreign-key-field ("combined"). The table "combined" has a field name and a foreign-key-field "helper" which again is a table with two foreign-key-fields.

My question is now, what is the simplest SQL-Query to get the following table:

[table workers]
ID [PK] | worker | combined-Name| department | location
--------+--------+--------------+------------+-----------
1       | John   |    name2     | Development|   Paris
--------------------------------+------------+-----------
2       | Adam   |    name1     | Production |   Berlin

I tried it already with some LEFT-JOINS but did not manage it to get all "clearnames" to the table "workers"

Body:
This query would work:

SELECT w.ID, worker, c.name AS `combined-Name`, d.department, l.department as
location FROM workers w
LEFT JOIN combined c ON c.ID = w.combined
LEFT JOIN helper h ON h.ID = c.helper
LEFT JOIN departments d ON d.ID = h.department
LEFT JOIN location l ON l.ID = h.location
GROUP BY w.ID

I used the AS keyword to set the names to your preferred output.

This was tested locally using the provided structures and data.

It's basically 4 simple left joins, and then instead of selecting the ID's I select the name columns of the foreign tables.

The alias on c.name is quoted because we need to escape the special character -


问:
How do I enable @click.middle?
I want to catch middle mouse button click event using @click.middle, but it seems that nothing happens. anyone know why? https://jsfiddle.net/c25e35uh/

  <button @click.middle="test()">
    Click Me
  </button>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})
```

In their document, they said clearly that using @click.middle to catch event https://v2.vuejs.org/v2/guide/events.html#Mouse-Button-Modifiers

答:
I think this is the same bug as @click.right that isn't working in 2.2.1: bug report.

It seems to be fixed in Vue 2.3+

PS can't test it, as my laptop hasn't a middle mouse button. Also double tab is a right click on my laptop ;)

Title: How do I enable @click.middle?

Body:
I want to catch middle mouse button click event using @click.middle, but it seems that nothing happens. anyone know why? https://jsfiddle.net/c25e35uh/

  <button @click.middle="test()">
    Click Me
  </button>

new Vue({
  el: '#root',
  methods: {
    test () {
        alert('me')
    }
  }
})

In their document, they said clearly that using @click.middle to catch event https://v2.vuejs.org/v2/guide/events.html#Mouse-Button-Modifiers


答:
You can do it like this. I have used black background in div to make it more clear. You can remove that black color as per your requirements.

.figure {
  width: 200px;
  background-color: black;
  overflow:hidden;
}
img{
  width:100%;
  border-bottom-left-radius: 100%30px;
  border-bottom-right-radius: 100%30px;
  border-top-left-radius: 100%30px;
  border-top-right-radius: 100%30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="figure">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/1/14/Quaidportrait.jpg/220px-Quaidportrait.jpg" />
</div>    </code>```

You can check working CodePen here. https://codepen.io/sajiddesigner/pen/BZOwWa

Title: Curve on the top/bottom of a div or element

Body:
I am looking to achieve as shown:

I have tried border-radius on a pseudo element but the curve is ugly and smoothly as opposed to ending 'abruptly' with sharp corners - if you know what I mean.

The same div needs the same curve on the bottom, but inverted version of the one in image.
Also, considering an image:

How would I achieve this in CSS?

Body:
You can do it like this. I have used black background in div to make it more clear. You can remove that black color as per your requirements.

.figure {
  width: 200px;
  background-color: black;
  overflow:hidden;
}
img{
  width:100%;
  border-bottom-left-radius: 100%30px;
  border-bottom-right-radius: 100%30px;
  border-top-left-radius: 100%30px;
  border-top-right-radius: 100%30px;
}

<div class="figure">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/1/14/Quaidportrait.jpg/220px-Quaidportrait.jpg" />
</div>

You can check working CodePen here. https://codepen.io/sajiddesigner/pen/BZOwWa


问:
Force R to print 0/0 as 1
When I execute 0 / 0 in R, I would get a NaN as an output. But is there any way I could print 0 / 0 as 1? I know I could use some if statements to achieve it. I would like to know if there is any other way to achieve this.

答:
Other way than using If statement would be

```<code># Assign NaN to vector
a <- 0 / 0
# If is NaN assign value 1
a[is.nan(a)] <- 1
</code>```

Title: Force R to print 0/0 as 1

Body:
Other way than using If statement would be

# Assign NaN to vector
a <- 0 / 0
# If is NaN assign value 1
a[is.nan(a)] <- 1


答:
use following query:</p>

```<code>select [workers].worker,[combined].name as combined-name,[departments].name as department,[location].name as location  from [workers]
left join [combined] on [workers].combined = [combined].combined
left join [helper] on [helper].ID = [combined].helper
left join [departments] on [departments].ID = [helper].department
left join [location] on [location].ID = [helper].location
</code>```

Title: SQL-Query for a table with a foreign-key-field that references other foreign-key-fields

Body:
use following query:

select [workers].worker,[combined].name as combined-name,[departments].name as department,[location].name as location  from [workers]
left join [combined] on [workers].combined = [combined].combined
left join [helper] on [helper].ID = [combined].helper
left join [departments] on [departments].ID = [helper].department
left join [location] on [location].ID = [helper].location


问:
undefined is not an object (evaluating 'LoginManager.loginWithPermissions')
Trying simple react-native app with facebook SDK, getting the following error:

undefined is not an object (evaluating 'LoginManager.loginWithPermissions')

Steps to reproduce:

react-native init app

react-native install react-native-fbsdk

react-native link react-native-fbsdk

Facebook guide https://developers.facebook.com/docs/ios/getting-started/

react-native run-ios

error

Any suggestions?

I think that react-native-fbsdk doesnt links with xcode project correctly...How to check it?
I don't have any exceptions while linking:

21:17 $ react-native link react-native-fbsdk
  Scanning 559 folders for symlinks in /Users/denis/Projects/app/node_modules (7ms)

It looks like libRCTFBSDK.a is not included into the project, how to include it manually?

答:
This solution helped me: https://github.com/fbsamples/f8app/issues/118#issuecomment-283670056

Download fb react native sdk and then drag ios/RCTFBSDK.xcodeproj to the Libraries group

Then add libRCTFBSDK to "Build Phases" -> "Link Binary With Libraries" (using the + button below)


问:
Custom buttons in different APIs
I did a custom button class for making square buttons. Buttons works fine in Nougat, but not showing in Lollipop and marshmallow. What is wrong with my code?

Java class:

```<code>public class SquareButton extends ToggleButton {

        public SquareButton(Context context) {
            super(context);
        }

        public SquareButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int size = width > height ? height : width;
            setMeasuredDimension(size, size);

        }
    }
</code>```

XML:

```<code>    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="ru.energyhouse.energyhouse.presenter.Light.MainMenuLightFragment"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:id="@+id/main_menu_light_icon_IV"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline9"
        app:srcCompat="@drawable/light_lightoff_big_ic" />

    <TextView
        android:id="@+id/main_menu_light_icon_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorPrimary"
        app:layout_constraintLeft_toLeftOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintRight_toRightOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintTop_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.5" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline9"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <HorizontalScrollView
        android:id="@+id/main_menu_light_scroll"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="16dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_menu_light_icon_TV"
        app:layout_constraintVertical_bias="0.0">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="2">

            <LinearLayout
                android:id="@+id/main_menu_light_firstRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_bright_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_soft_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_manual_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="24dp"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/main_menu_light_secondRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_allOff_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_backLight_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

        </LinearLayout>

    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

Nougat: enter image description here

Lollipop: enter image description here

UPD.

if set width 200dp - it works. I need width like height and height - match_parent.

答:
Try to change onMeasure method to following:</p>

```<code>@Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int size = widthMeasureSpec > heightMeasureSpec ? heightMeasureSpec : widthMeasureSpec;
        super.onMeasure(size, size);

    }
</code>```

Title: Custom buttons in different APIs

Body:
I did a custom button class for making square buttons. Buttons works fine in Nougat, but not showing in Lollipop and marshmallow. What is wrong with my code?

Java class:

public class SquareButton extends ToggleButton {

        public SquareButton(Context context) {
            super(context);
        }

        public SquareButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int size = width > height ? height : width;
            setMeasuredDimension(size, size);

        }
    }

XML:

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="ru.energyhouse.energyhouse.presenter.Light.MainMenuLightFragment"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:id="@+id/main_menu_light_icon_IV"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline9"
        app:srcCompat="@drawable/light_lightoff_big_ic" />

    <TextView
        android:id="@+id/main_menu_light_icon_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorPrimary"
        app:layout_constraintLeft_toLeftOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintRight_toRightOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintTop_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.5" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline9"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <HorizontalScrollView
        android:id="@+id/main_menu_light_scroll"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="16dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_menu_light_icon_TV"
        app:layout_constraintVertical_bias="0.0">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="2">

            <LinearLayout
                android:id="@+id/main_menu_light_firstRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_bright_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_soft_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_manual_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="24dp"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/main_menu_light_secondRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_allOff_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_backLight_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

        </LinearLayout>

    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>

Nougat: enter image description here

Lollipop: enter image description here

UPD.

if set width 200dp - it works. I need width like height and height - match_parent.

Body:
Try to change onMeasure method to following:

@Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int size = widthMeasureSpec > heightMeasureSpec ? heightMeasureSpec : widthMeasureSpec;
        super.onMeasure(size, size);

    }