问:
Java - How to set timeout for Event Dispatch thread?
I have a Java application were some operations take some time to load, so instead of freezing the program while the operation completes i show a "Please wait..." dialog using this code:

```<code>SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        pleaseWaitDialog.setVisible( true );
    }
});
</code>```

Sometimes the operation being executed hangs for some reason, so i would like to set a timeout period for this "please wait..." dialog to automatically disappear after 5 minutes and show an error message. How can i do that?

答:
The basic concept would be to use a single run Swing Timer, that when triggered would allow you to dispose of the dialog, for example...

```<code>import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                TimeoutDialog dialog = new TimeoutDialog(5 * 60, (Window) null, "Testing");
                dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                dialog.add(new TestPane());
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(new JLabel("This is a bad idea"), gbc);
            add(new JButton("Don't tell me"), gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class TimeoutDialog extends JDialog {

        private long timeOut = 90 * 1000;
        private long startTime;
        private Timer timer;
        private String originalTitle;

        public TimeoutDialog(long timeOut) {
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, ModalityType modalityType) {
            super(owner, modalityType);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title, ModalityType modalityType) {
            super(owner, title, modalityType);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title, ModalityType modalityType, GraphicsConfiguration gc) {
            super(owner, title, modalityType, gc);
            init(timeOut);
        }

        protected void init(double timeOutValue) {

            this.timeOut = Math.round(timeOutValue * 1000);

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long runningTime = System.currentTimeMillis() - startTime;
                    System.out.println(runningTime + "/" + timeOut);
                    if (runningTime >= timeOut) {
                        timer.stop();
                        dispose();
                    } else {
                        String title = originalTitle + " [" + (((timeOut - runningTime) / 1000) + 1) + "]";
                        setTitle(title);
                    }
                }
            });

            originalTitle = getTitle();
            String title = originalTitle + " [" + ((timeOut / 1000)) + "]";
            setTitle(title);
            addPropertyChangeListener("title", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (!timer.isRunning()) {
                        originalTitle = (String) evt.getNewValue();
                    }
                }
            });

            addWindowListener(new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    timer.start();
                }

                @Override
                public void windowClosed(WindowEvent e) {
                    timer.stop();
                }

            });
        }

    }

}
</code>```

Another idea might be to use some kind of observer pattern whose intention is to send regular "heart beats" to all interested parties.

Your long running process would periodically send out a "heart beat"/"pulse" (at relatively regular intervals) while it was still working.  If for some reason, it stopped working, the interested parties would know because they'd not received a pulse within in prescribed timeout period and could take appropriate action - just as an idea

Body:
I have a Java application were some operations take some time to load, so instead of freezing the program while the operation completes i show a "Please wait..." dialog using this code:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        pleaseWaitDialog.setVisible( true );
    }
});

Sometimes the operation being executed hangs for some reason, so i would like to set a timeout period for this "please wait..." dialog to automatically disappear after 5 minutes and show an error message. How can i do that?

Body:
The basic concept would be to use a single run Swing Timer, that when triggered would allow you to dispose of the dialog, for example...

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                TimeoutDialog dialog = new TimeoutDialog(5 * 60, (Window) null, "Testing");
                dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                dialog.add(new TestPane());
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(new JLabel("This is a bad idea"), gbc);
            add(new JButton("Don't tell me"), gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class TimeoutDialog extends JDialog {

        private long timeOut = 90 * 1000;
        private long startTime;
        private Timer timer;
        private String originalTitle;

        public TimeoutDialog(long timeOut) {
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, boolean modal) {
            super(owner, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title, boolean modal) {
            super(owner, title, modal);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Dialog owner, String title, boolean modal, GraphicsConfiguration gc) {
            super(owner, title, modal, gc);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner) {
            super(owner);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, ModalityType modalityType) {
            super(owner, modalityType);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title) {
            super(owner, title);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title, ModalityType modalityType) {
            super(owner, title, modalityType);
            init(timeOut);
        }

        public TimeoutDialog(long timeOut, Window owner, String title, ModalityType modalityType, GraphicsConfiguration gc) {
            super(owner, title, modalityType, gc);
            init(timeOut);
        }

        protected void init(double timeOutValue) {

            this.timeOut = Math.round(timeOutValue * 1000);

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    long runningTime = System.currentTimeMillis() - startTime;
                    System.out.println(runningTime + "/" + timeOut);
                    if (runningTime >= timeOut) {
                        timer.stop();
                        dispose();
                    } else {
                        String title = originalTitle + " [" + (((timeOut - runningTime) / 1000) + 1) + "]";
                        setTitle(title);
                    }
                }
            });

            originalTitle = getTitle();
            String title = originalTitle + " [" + ((timeOut / 1000)) + "]";
            setTitle(title);
            addPropertyChangeListener("title", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (!timer.isRunning()) {
                        originalTitle = (String) evt.getNewValue();
                    }
                }
            });

            addWindowListener(new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    timer.start();
                }

                @Override
                public void windowClosed(WindowEvent e) {
                    timer.stop();
                }

            });
        }

    }

}

Another idea might be to use some kind of observer pattern whose intention is to send regular "heart beats" to all interested parties.

Your long running process would periodically send out a "heart beat"/"pulse" (at relatively regular intervals) while it was still working.  If for some reason, it stopped working, the interested parties would know because they'd not received a pulse within in prescribed timeout period and could take appropriate action - just as an idea


来源: stackexchange

问:
LibreOffice Calc display formula reference cell
When i select the cell with formula, there will show the related cell with highlight in old version(new version don't have it). What is the setting in new version ?

答: Go to Tools -> Options -> LibreOffice Calc -> View and check the box Show references in color.

ContentLicense: CC BY-SA 3.0


问:
In Laravel how do I get the average of a sum of a value?
Lets say I have a database full of users. And a table filled with the "points" users have earned for various activities the Points table has these columns:

id, user_id, value, created_at, updated_at

I want to be able to get a user's total points, easy as pie using the ->sum() method, then compare that user's total points to the average user's total points.

I know that I can get a collection of each users total points via:

```<code>->groupBy('user_id')->selectRaw( "sum( value ) as sum" )->pluck( "sum" );
</code>```

but I'm drawing a blank as to how to get the average total score across all users, instead of an array of each user's total score.

Thanks!

答:
With laravel you can use the sum() method to sum up the values within a collection and the count() method to count the number elements in the collection. Sum/count is the average:

```<code>$sums=$whatever->groupBy('user_id')->selectRaw( "sum( value ) as sum" )->get( "sum" );
$avg=$sums->sum("sum")/$sums->count();
</code>```

Or you need to use a subquery in sql code.

Body:
Lets say I have a database full of users. And a table filled with the "points" users have earned for various activities the Points table has these columns:

id, user_id, value, created_at, updated_at

I want to be able to get a user's total points, easy as pie using the ->sum() method, then compare that user's total points to the average user's total points.

I know that I can get a collection of each users total points via:

->groupBy('user_id')->selectRaw( "sum( value ) as sum" )->pluck( "sum" );

but I'm drawing a blank as to how to get the average total score across all users, instead of an array of each user's total score.

Thanks!

Body:
With laravel you can use the sum() method to sum up the values within a collection and the count() method to count the number elements in the collection. Sum/count is the average:

$sums=$whatever->groupBy('user_id')->selectRaw( "sum( value ) as sum" )->get( "sum" );
$avg=$sums->sum("sum")/$sums->count();

Or you need to use a subquery in sql code.


问:
How to setup Kubernetes & Docker local environment for GCE on Windows 10 Home Edition?
I am new to Kubernetes and Docker, and trying to setup a good environment for working with GCE using the gcloud cli.

Since I am using Windows 10 Home Edition, I realized my only option to use Docker is installing Docker Toolbox, so any Docker commands can be run only from a VM (docker-machine, a boot2docker).
It also means, every time I want to create a docker image, I have to copy my local project folder to a share folder which the docker-machine would see, in order to build its image.

The docker-machine is a light version of linux, so it's not very user-friendly and difficult to use gcloud cli from.

I managed to work it all out up to the point where I want push my local docker image to my google's private registry.

gcloud cli is installed on my actual machine, can't be installed on the light-weight linux VM, so when I try to push the image from my Windows Powershell using:

```<code>gcloud docker -- push gcr.io/..../..
</code>```

I receive the following error:

ERROR: Docker CLI operation failed:

unknown flag: --email

See 'docker login --help'.

ERROR: (gcloud.docker) Docker login failed.

First, I'm not even sure if the image would be recognized, since it has been created on the docker-machine.

Second, I could not login to docker on my actual machine, since docker could not be installed, and any docker command should be made from inside the docker-machine.

So basically, now I'm stuck without being able to push my image. I feel like the whole process from the start has been very complicated, so it all made me wonder about my whole setup.

My question is, what would be the appropriate way to setup my environment for a smooth flow?

If you think the flow I described, given the fact I've been using Windows 10 Home, is the best I can achieve, I would appreciate your help with solving the pushing issue with the google cli.

答:
To get a local Kube environment you should also take a look at Minikube: https://github.com/kubernetes/minikube

It uses docker-machine and thus supports the virtualbox docker-machine driver, which should work on Windows 10 Home (it doesn't require Hyper-V).

Note that Docker (where I work) is working on Kube support in Docker for Mac and Windows: https://blog.docker.com/2017/10/docker-for-mac-and-windows-with-kubernetes-beta/

... although Docker for Windows won't work on Windows 10 Home, because Hyper-V is not enabled on that Windows version.

Body:
I am new to Kubernetes and Docker, and trying to setup a good environment for working with GCE using the gcloud cli.

Since I am using Windows 10 Home Edition, I realized my only option to use Docker is installing Docker Toolbox, so any Docker commands can be run only from a VM (docker-machine, a boot2docker).
It also means, every time I want to create a docker image, I have to copy my local project folder to a share folder which the docker-machine would see, in order to build its image.

The docker-machine is a light version of linux, so it's not very user-friendly and difficult to use gcloud cli from.

I managed to work it all out up to the point where I want push my local docker image to my google's private registry.

gcloud cli is installed on my actual machine, can't be installed on the light-weight linux VM, so when I try to push the image from my Windows Powershell using:

gcloud docker -- push gcr.io/..../..

I receive the following error:

ERROR: Docker CLI operation failed:

unknown flag: --email

See 'docker login --help'.

ERROR: (gcloud.docker) Docker login failed.

First, I'm not even sure if the image would be recognized, since it has been created on the docker-machine.

Second, I could not login to docker on my actual machine, since docker could not be installed, and any docker command should be made from inside the docker-machine.

So basically, now I'm stuck without being able to push my image. I feel like the whole process from the start has been very complicated, so it all made me wonder about my whole setup.

My question is, what would be the appropriate way to setup my environment for a smooth flow?

If you think the flow I described, given the fact I've been using Windows 10 Home, is the best I can achieve, I would appreciate your help with solving the pushing issue with the google cli.


问:
requestPermissions prompt not showing
I have an activity that extends AppCompatActivity. For this activity to run I need to grant the app with ACCESS_COARSE_LOCATION and WRITE_EXTERNAL_STORAGE permissions. Everything was working well until I updated to Android Studio 3.0.

Now, the prompt for requesting WRITE_EXTERNAL_STORAGE permissions is not showing, and the function

```<code>public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults)
</code>```

is returning -1 at grantResults without even asking.

This behavior is not happening if I request the permission ACCESS_COARSE_LOCATION, which works as it should. Below, the code invoking both checks:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect beacons.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                    }
                });

                builder.show();
            }
        }
</code>```

And the other:

```<code>        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs sd access");
                builder.setMessage("Please grant sd access so this app can save files.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });

                builder.show();
            }
        }
</code>```

The corresponding section in my manifest looks like this:

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

I've read many things, but this is pretty strange, when some type of permissions are showing up the request dialog, while others aren't.
By the way, there is no SD card in the device (always used internal storage), but that was never a problem.

Both my targetSdkVersion and compileSdkVersion are 26.

EDIT

Other relevant permissions, such as READ_EXTERNAL_STORAGE, are also working correctly. It's just an issue with the write permission.
Tested on two android devices and emulator

Complete onCreate Method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_device_discovery);

    context = this;
    wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    intent = getIntent();

    if(intent.getBooleanExtra("LOCAL_NETWORK", true) == true){
        ipAddress = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        port = DEFAULT_LIGHT_PORT;
    }
    else{
         ipAddress = intent.getStringExtra("TRACK_IP");
         port = intent.getIntExtra("TRACK_PORT", DEFAULT_GATEWAY_PORT);
    }

    font = Typeface.createFromAsset(MainActivity.mainActivity.getAssets(), "RepRg.ttf");
    mHandler = new Handler();

    deviceArrayList = new ArrayList<>();
    devicesBufferList = new ArrayList<>();

    lightListAdapter = new LightListAdapter(this, deviceArrayList, intent);

    discoveredListView = (ListView) findViewById(R.id.paired_devices);
    discoveredListView.setAdapter(lightListAdapter);

    listAllCheckBox = (CheckBox) findViewById(R.id.listAllCheckBox);
    refreshButton = (ImageButton) findViewById(R.id.refreshButton);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs sd access");
            builder.setMessage("Please grant sd access so this app can save files.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
            });

            builder.show();
        }
    }

    listAllCheckBox.setTypeface(font);
    listAllCheckBox.setTextSize(18);
    listAllCheckBox.setTextColor(Color.parseColor("#202020"));
    listAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            lightListAdapter.clear();
            processDeviceListing();
        }
    });

    refreshButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    refreshButton.setImageResource(R.drawable.refresh_down);
                    break;
                case MotionEvent.ACTION_UP:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    refreshDevicesList();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    break;
            }
            return false;
        }
    });

}
</code>```

Thanks in advance.

答:
Try this:

```<code>if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                PERMISSION_REQUEST_COARSE_LOCATION);
    }
</code>```

I suggest you check the documentation: https://developer.android.com/training/permissions/requesting.html

Update

Why are you using the same request code for both permissions?

```<code> requestPermissions(new String[]{Manifest.permission. ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); <-- PERMISSION_REQUEST_COARSE_LOCATION
</code>```

and

```<code> requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_COARSE_LOCATION);  <-- PERMISSION_REQUEST_COARSE_LOCATION
</code>```

Change the request code value for each one.

Title: requestPermissions prompt not showing

Body:
I have an activity that extends AppCompatActivity. For this activity to run I need to grant the app with ACCESS_COARSE_LOCATION and WRITE_EXTERNAL_STORAGE permissions. Everything was working well until I updated to Android Studio 3.0.

Now, the prompt for requesting WRITE_EXTERNAL_STORAGE permissions is not showing, and the function

public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults)

is returning -1 at grantResults without even asking.

This behavior is not happening if I request the permission ACCESS_COARSE_LOCATION, which works as it should. Below, the code invoking both checks:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect beacons.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                    }
                });

                builder.show();
            }
        }

And the other:

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs sd access");
                builder.setMessage("Please grant sd access so this app can save files.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                });

                builder.show();
            }
        }

The corresponding section in my manifest looks like this:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I've read many things, but this is pretty strange, when some type of permissions are showing up the request dialog, while others aren't.
By the way, there is no SD card in the device (always used internal storage), but that was never a problem.

Both my targetSdkVersion and compileSdkVersion are 26.

EDIT

Other relevant permissions, such as READ_EXTERNAL_STORAGE, are also working correctly. It's just an issue with the write permission.
Tested on two android devices and emulator

Complete onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_device_discovery);

    context = this;
    wm = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    intent = getIntent();

    if(intent.getBooleanExtra("LOCAL_NETWORK", true) == true){
        ipAddress = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        port = DEFAULT_LIGHT_PORT;
    }
    else{
         ipAddress = intent.getStringExtra("TRACK_IP");
         port = intent.getIntExtra("TRACK_PORT", DEFAULT_GATEWAY_PORT);
    }

    font = Typeface.createFromAsset(MainActivity.mainActivity.getAssets(), "RepRg.ttf");
    mHandler = new Handler();

    deviceArrayList = new ArrayList<>();
    devicesBufferList = new ArrayList<>();

    lightListAdapter = new LightListAdapter(this, deviceArrayList, intent);

    discoveredListView = (ListView) findViewById(R.id.paired_devices);
    discoveredListView.setAdapter(lightListAdapter);

    listAllCheckBox = (CheckBox) findViewById(R.id.listAllCheckBox);
    refreshButton = (ImageButton) findViewById(R.id.refreshButton);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("This app needs sd access");
            builder.setMessage("Please grant sd access so this app can save files.");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
            });

            builder.show();
        }
    }

    listAllCheckBox.setTypeface(font);
    listAllCheckBox.setTextSize(18);
    listAllCheckBox.setTextColor(Color.parseColor("#202020"));
    listAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            lightListAdapter.clear();
            processDeviceListing();
        }
    });

    refreshButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    refreshButton.setImageResource(R.drawable.refresh_down);
                    break;
                case MotionEvent.ACTION_UP:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    refreshDevicesList();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    refreshButton.setImageResource(R.drawable.refresh_up);
                    break;
            }
            return false;
        }
    });

}

Thanks in advance.

Body:
Try this:

if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                PERMISSION_REQUEST_COARSE_LOCATION);
    }

I suggest you check the documentation: https://developer.android.com/training/permissions/requesting.html

Update

Why are you using the same request code for both permissions?

 requestPermissions(new String[]{Manifest.permission. ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); <-- PERMISSION_REQUEST_COARSE_LOCATION

and

 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_COARSE_LOCATION);  <-- PERMISSION_REQUEST_COARSE_LOCATION

Change the request code value for each one.


问:
Check if user is actively present
Is there a way to determine if a user is actively present on phone (not just screen on).

I cannot depend on catching events.  These only fire off at points in time within a BroadcastReceiver:

```<code>intent.getAction().equals(Intent.ACTION_USER_PRESENT)
intent.getAction().equals(Intent.ACTION_SCREEN_ON)
</code>```

I need a simple way to perform an active check in that moment.  A service is firing off, and I do not want it to fire off while the phone is active (screen on).

答:
You can check it through PowerManager class of android SDK.

```<code>   PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
   boolean isScreenOn = pm.isScreenOn();
</code>```

Updated answer:
isScreenOn() method is deprecated, Replace it with isInteractive()

```<code>   boolean isScreenOn = pm.isInteractive();
</code>```

Title: Check if user is actively present

Body:
Is there a way to determine if a user is actively present on phone (not just screen on).

I cannot depend on catching events.  These only fire off at points in time within a BroadcastReceiver:

intent.getAction().equals(Intent.ACTION_USER_PRESENT)
intent.getAction().equals(Intent.ACTION_SCREEN_ON)

I need a simple way to perform an active check in that moment.  A service is firing off, and I do not want it to fire off while the phone is active (screen on).

Body:
You can check it through PowerManager class of android SDK.

   PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
   boolean isScreenOn = pm.isScreenOn();

Updated answer:
isScreenOn() method is deprecated, Replace it with isInteractive()

   boolean isScreenOn = pm.isInteractive();

ContentLicense: CC BY-SA 4.0


问:
How to convert DateTimeOffset to DateTime in Linq
I have this query which returns incorrect results:

```<code> return contextProvider
                      .Context
                      .OrderAccounts
                      .Where(orderAccount => listCSRId.Contains(orderAccount.OrderCust.UserId) &&
                                    orderAccount.OrderCust.SubmittedDate >= System.Data.Entity.DbFunctions.TruncateTime(startDate)
                                    && orderAccount.OrderCust.SubmittedDate <= startDate
                                    && orderAccount.OrderCust.OrderStatusId == (int)OrderStatus.Submitted)
                       .Select(x => new Order
                       {
                         UserId = x.OrderCust.UserId,
                         FacilityCode = x.FacilityCode,
                         GreenFlag = x.GreenFlag ?? false,
                         Payable = x.Payable,
                         OrderCustId = x.OrderCustId
                       })
                      .ToList();
</code>```

The reason that the results are incorrect is that the SubmittedDate is a DateTimeOffSet in Sql Server.  So when the local DateTime of 11 PM on 2017-11-15 is stored, it is stored as 04:00 2017-11-16 due to the Offset between local time, and GMT.

When the query runs, the startDate is just a date without a time.  So what is needed is to convert the SubmittedDate in the table to a Local Date.  Then the query would be correct.

How do I do that?

答:
Convert the startDate to UTC, and add 1 day and convert and make sure the SubmittedDate is between the two:

```<code>return contextProvider
                      .Context
                      .OrderAccounts
                      .Where(orderAccount => listCSRId.Contains(orderAccount.OrderCust.UserId) &&
                                    orderAccount.OrderCust.SubmittedDate >= System.Data.Entity.DbFunctions.TruncateTime(startDate.ToUniversalTime())
                                    && orderAccount.OrderCust.SubmittedDate < startDate.AddDays(1).ToUniversalTime()
                                    && orderAccount.OrderCust.OrderStatusId == (int)OrderStatus.Submitted)
                       .Select(x => new Order {
                           UserId = x.OrderCust.UserId,
                           FacilityCode = x.FacilityCode,
                           GreenFlag = x.GreenFlag ?? false,
                           Payable = x.Payable,
                           OrderCustId = x.OrderCustId
                       })
                      .ToList();
</code>```

Body:
I have this query which returns incorrect results:

 return contextProvider
                      .Context
                      .OrderAccounts
                      .Where(orderAccount => listCSRId.Contains(orderAccount.OrderCust.UserId) &&
                                    orderAccount.OrderCust.SubmittedDate >= System.Data.Entity.DbFunctions.TruncateTime(startDate)
                                    && orderAccount.OrderCust.SubmittedDate <= startDate
                                    && orderAccount.OrderCust.OrderStatusId == (int)OrderStatus.Submitted)
                       .Select(x => new Order
                       {
                         UserId = x.OrderCust.UserId,
                         FacilityCode = x.FacilityCode,
                         GreenFlag = x.GreenFlag ?? false,
                         Payable = x.Payable,
                         OrderCustId = x.OrderCustId
                       })
                      .ToList();

The reason that the results are incorrect is that the SubmittedDate is a DateTimeOffSet in Sql Server.  So when the local DateTime of 11 PM on 2017-11-15 is stored, it is stored as 04:00 2017-11-16 due to the Offset between local time, and GMT.

When the query runs, the startDate is just a date without a time.  So what is needed is to convert the SubmittedDate in the table to a Local Date.  Then the query would be correct.

How do I do that?

Body:
Convert the startDate to UTC, and add 1 day and convert and make sure the SubmittedDate is between the two:

return contextProvider
                      .Context
                      .OrderAccounts
                      .Where(orderAccount => listCSRId.Contains(orderAccount.OrderCust.UserId) &&
                                    orderAccount.OrderCust.SubmittedDate >= System.Data.Entity.DbFunctions.TruncateTime(startDate.ToUniversalTime())
                                    && orderAccount.OrderCust.SubmittedDate < startDate.AddDays(1).ToUniversalTime()
                                    && orderAccount.OrderCust.OrderStatusId == (int)OrderStatus.Submitted)
                       .Select(x => new Order {
                           UserId = x.OrderCust.UserId,
                           FacilityCode = x.FacilityCode,
                           GreenFlag = x.GreenFlag ?? false,
                           Payable = x.Payable,
                           OrderCustId = x.OrderCustId
                       })
                      .ToList();


问:
Swift tvOS: Getting the screen center for AVPlayerView
I am writing an app for tvOS that launches videos from URL's into an AVPlayerView, which is not nested in another View.  The trouble is, the user had no idea anything was going on while loading was occurring, so I wanted to add an activity indicator in the center of the screen.

Getting the screen center is not straightforward while a video is loading, however, because the view's bounds are set to (0, 0, 0, 0) while the video is loading, so setting the subview's center = view.center doesn't work (it will just add my subviews in the upper left corner of the screen).

How can I add a subview into the center of the screen, when the frame is set to (0, 0, 0, 0)?

答:
Luckily, I was able to find the answer on my own.  UIScreen works just as well with tvOS as it would on an iOS device.  My complete solution is below, hope it helps save someone some time.  I am including my observers that trigger the end as well.

The class that I used to handle the activity

```<code>class VideoLoadingActivityIndicator {

var loadingActivityIndicator:UIActivityIndicatorView!
var loadingLabel: UILabel!

func beginLoadingActivity(viewController:UIViewController)
{
    loadingActivityIndicator = UIActivityIndicatorView(frame:CGRect(x: 500, y: 500, width: 500, height: 500)) as UIActivityIndicatorView
    loadingActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
    loadingActivityIndicator.sizeToFit()
    loadingActivityIndicator.color = UIColor.white
</code>```

This is the part where you use UIScreen to get the bounds

```<code>    let screenBounds = UIScreen.main.bounds
    let centerX = screenBounds.size.width / 2
    let centerY = screenBounds.size.height / 2
    let loadingLabelCenterY = centerY + 48
    let activityIndicatorCenter = CGPoint(x: centerX, y: centerY)

    loadingActivityIndicator.center = activityIndicatorCenter
</code>```

I added a label to add some clarity

```<code>    loadingLabel = UILabel(frame: CGRect(x: centerX, y: loadingLabelCenterY, width: 600, height: 100))
    loadingLabel.font = UIFont(name: "Helvetica", size: 30)
    loadingLabel.text = "Loading Video"
    loadingLabel.numberOfLines = 1
    loadingLabel.sizeToFit()
    loadingLabel.textAlignment = .center
    // reset frame so it is centered in screen
    let labelWidth = loadingLabel.frame.width
    let labelHeight = loadingLabel.frame.height
    let loadingLabelCenterX = centerX - (labelWidth / 2)
    loadingLabel.frame = CGRect(x: loadingLabelCenterX, y: loadingLabelCenterY, width: labelWidth, height: labelHeight)
    loadingLabel.textColor = UIColor.white

    // Add indicator and label to subview
    viewController.view.addSubview(loadingActivityIndicator)
    viewController.view.addSubview(loadingLabel)

    self.loadingActivityIndicator.startAnimating()
}

func endLoadingActivity(viewController:UIViewController)-> Void
{
    loadingActivityIndicator.removeFromSuperview()
    loadingLabel.removeFromSuperview()
}
</code>```

And then in the AVPlayerViewController that you want to add some the loading activity to...

First create the activity indicator object:

```<code>let indicator = VideoLoadingActivityIndicator()
</code>```

Create your asset, and playerItem (I set some player item keys)

```<code>let asset = AVAsset(url: runFile)
let assetKeys = [
        "playable",
        "hasProtectedContent"
    ]
let playerItem = AVPlayerItem(asset: asset, automaticallyLoadedAssetKeys: assetKeys)
</code>```

start the activity indicator animations

```<code>indicator.beginLoadingActivity(viewController: self, color: .white)
</code>```

Add notification to player and start playback

```<code>playerItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
player = AVPlayer(playerItem: playerItem)
    player?.play()
</code>```

Finally, handle the observer:

```<code>    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "status" && player?.status == AVPlayerStatus.readyToPlay {
        indicator.endLoadingActivity(viewController: self)
    }
}
</code>```

Hope this helps someone else who runs into some of the same issues I did.

Body:
Luckily, I was able to find the answer on my own.  UIScreen works just as well with tvOS as it would on an iOS device.  My complete solution is below, hope it helps save someone some time.  I am including my observers that trigger the end as well.

The class that I used to handle the activity

class VideoLoadingActivityIndicator {

var loadingActivityIndicator:UIActivityIndicatorView!
var loadingLabel: UILabel!

func beginLoadingActivity(viewController:UIViewController)
{
    loadingActivityIndicator = UIActivityIndicatorView(frame:CGRect(x: 500, y: 500, width: 500, height: 500)) as UIActivityIndicatorView
    loadingActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
    loadingActivityIndicator.sizeToFit()
    loadingActivityIndicator.color = UIColor.white

This is the part where you use UIScreen to get the bounds

    let screenBounds = UIScreen.main.bounds
    let centerX = screenBounds.size.width / 2
    let centerY = screenBounds.size.height / 2
    let loadingLabelCenterY = centerY + 48
    let activityIndicatorCenter = CGPoint(x: centerX, y: centerY)

    loadingActivityIndicator.center = activityIndicatorCenter

I added a label to add some clarity

    loadingLabel = UILabel(frame: CGRect(x: centerX, y: loadingLabelCenterY, width: 600, height: 100))
    loadingLabel.font = UIFont(name: "Helvetica", size: 30)
    loadingLabel.text = "Loading Video"
    loadingLabel.numberOfLines = 1
    loadingLabel.sizeToFit()
    loadingLabel.textAlignment = .center
    // reset frame so it is centered in screen
    let labelWidth = loadingLabel.frame.width
    let labelHeight = loadingLabel.frame.height
    let loadingLabelCenterX = centerX - (labelWidth / 2)
    loadingLabel.frame = CGRect(x: loadingLabelCenterX, y: loadingLabelCenterY, width: labelWidth, height: labelHeight)
    loadingLabel.textColor = UIColor.white

    // Add indicator and label to subview
    viewController.view.addSubview(loadingActivityIndicator)
    viewController.view.addSubview(loadingLabel)

    self.loadingActivityIndicator.startAnimating()
}

func endLoadingActivity(viewController:UIViewController)-> Void
{
    loadingActivityIndicator.removeFromSuperview()
    loadingLabel.removeFromSuperview()
}

And then in the AVPlayerViewController that you want to add some the loading activity to...

First create the activity indicator object:

let indicator = VideoLoadingActivityIndicator()

Create your asset, and playerItem (I set some player item keys)

let asset = AVAsset(url: runFile)
let assetKeys = [
        "playable",
        "hasProtectedContent"
    ]
let playerItem = AVPlayerItem(asset: asset, automaticallyLoadedAssetKeys: assetKeys)

start the activity indicator animations

indicator.beginLoadingActivity(viewController: self, color: .white)

Add notification to player and start playback

playerItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
player = AVPlayer(playerItem: playerItem)
    player?.play()

Finally, handle the observer:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "status" && player?.status == AVPlayerStatus.readyToPlay {
        indicator.endLoadingActivity(viewController: self)
    }
}

Hope this helps someone else who runs into some of the same issues I did.


问:
Delete not specific lines in a text file
I'm looking for a way to delete lines that don't meet a criteria in VB.net. I'll just give a example of what I want done below.

Basically, I want the program to go through a text document (Each line) and if the line doesn't contain a certain string it would get erased.

Basically:

```<code>hgfhfghhfo TRUE

hdfgdfhdfh MAYBE

tytrteyuet POSSIBLE

ghjfgjgfjf FALSE
</code>```

That's what the text document would look like, now I want it to not focus on the "RandomInfo" but on the "True/False" If it says TRUE I want it too keep the line. If the line contains anything except True I want it deleted. Can you guys help me with this?

答:
Try this,</p>

```<code>Dim filename = "sample.txt"

Dim result = From n In System.IO.File.ReadAllLines(filename).Where(Function(s) s.EndsWith("TRUE"))

System.IO.File.WriteAllLines(filename, result.ToArray())
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm looking for a way to delete lines that don't meet a criteria in VB.net. I'll just give a example of what I want done below.

Basically, I want the program to go through a text document (Each line) and if the line doesn't contain a certain string it would get erased.

Basically:

hgfhfghhfo TRUE

hdfgdfhdfh MAYBE

tytrteyuet POSSIBLE

ghjfgjgfjf FALSE

That's what the text document would look like, now I want it to not focus on the "RandomInfo" but on the "True/False" If it says TRUE I want it too keep the line. If the line contains anything except True I want it deleted. Can you guys help me with this?

Body:
Try this,

Dim filename = "sample.txt"

Dim result = From n In System.IO.File.ReadAllLines(filename).Where(Function(s) s.EndsWith("TRUE"))

System.IO.File.WriteAllLines(filename, result.ToArray())


问:
Tkinter Entry to accept Unicode text?
I have a Tkinter Entry widget and a Hungarian keyboard. When I press the ő button on the keyboard, the Entry widget displays õ. ű becomes û. (I haven't had this problem in other applications since Windows 3.1.)

Edit:

I do have two language settings on this computer and when I start changing them around, the problem disappears.

What can I do to make Tkinter handle my input correctly?

答: Can't reproduce your problem. Works for me with Tk and tkinter as well. See the Tk ticket.</p>

Title: Tkinter Entry to accept Unicode text?


问:
How long is a azure subscription consent (in Azure AD) valid for? Does it have to be renewed
When we login and using admin consent. How long is a subscription consent valid for?  Does it have to be renewed. Thanks</p>

答:
Consent in Azure Active Directory is valid until it is explicitly revoked.

Do note though that there is an expiryTime property on the OAuth2PermissionGrant, however it is not implemented yet.

expiryTime

Edm.DateTime POST, GET, PATCH

Reserved. Returns null. Do not use.


问:
How to call method to plot Graph Android
I've been trying to plot a graph from two ArrayLists on my Android Application. I got the values from ArrayList succeed, but I can't call method to get values.

I create this method which gets values from my database:

```<code>public DataPoint[] setData(String data)
{
    TextView editText4;
    editText4 = (TextView) findViewById(R.id.editText4);
    String[] lucas = data.split(",");

    List<String> ok = new ArrayList<String>(Arrays.asList(lucas));
    List<String> yes = new ArrayList<String>(Arrays.asList(lucas));

    int n = ok.size();     //to find out the no. of data-points
    editText4.setText(String.valueOf(n));
    DataPoint[] values = new DataPoint[n];     //creating an object of type DataPoint[] of size 'n'
    for (int i = 0; i < n; i++)
     {
        DataPoint v = new DataPoint(Double.parseDouble(ok.get(i)), Double.parseDouble(yes.get(i)));
        values[i] = v;
     }
     return values;
 }
</code>```

My problem is here in setData (Cannot Resolve symbol 'setData') :

```<code>GraphView graph;
PointsGraphSeries<DataPoint> series;       //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graph);
series = new PointsGraphSeries<>(setData);   //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series);                   //adding the series to the GraphView
series.setShape(PointsGraphSeries.Shape.POINT);
series.setSize(6);
</code>```

答: As looking for your code looks that you have method setData(String data) but in series = new PointsGraphSeries<>(setData); you are calling variable. Please assing result from setData(String data) method to local variable and then use it in mentioned line of code.

Body:
I've been trying to plot a graph from two ArrayLists on my Android Application. I got the values from ArrayList succeed, but I can't call method to get values.

I create this method which gets values from my database:

public DataPoint[] setData(String data)
{
    TextView editText4;
    editText4 = (TextView) findViewById(R.id.editText4);
    String[] lucas = data.split(",");

    List<String> ok = new ArrayList<String>(Arrays.asList(lucas));
    List<String> yes = new ArrayList<String>(Arrays.asList(lucas));

    int n = ok.size();     //to find out the no. of data-points
    editText4.setText(String.valueOf(n));
    DataPoint[] values = new DataPoint[n];     //creating an object of type DataPoint[] of size 'n'
    for (int i = 0; i < n; i++)
     {
        DataPoint v = new DataPoint(Double.parseDouble(ok.get(i)), Double.parseDouble(yes.get(i)));
        values[i] = v;
     }
     return values;
 }

My problem is here in setData (Cannot Resolve symbol 'setData') :

GraphView graph;
PointsGraphSeries<DataPoint> series;       //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graph);
series = new PointsGraphSeries<>(setData);   //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series);                   //adding the series to the GraphView
series.setShape(PointsGraphSeries.Shape.POINT);
series.setSize(6);


问:
Finding what methods a Python object has
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?

Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called?

答:
Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:

```<code>user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__(           s.__rmod__(          s.istitle(
s.__class__(         s.__rmul__(          s.isupper(
s.__contains__(      s.__setattr__(       s.join(
s.__delattr__(       s.__sizeof__(        s.ljust(
s.__dir__(           s.__str__(           s.lower(
s.__doc__            s.__subclasshook__(  s.lstrip(
s.__eq__(            s.capitalize(        s.maketrans(
s.__format__(        s.casefold(          s.partition(
s.__ge__(            s.center(            s.replace(
s.__getattribute__(  s.count(             s.rfind(
s.__getitem__(       s.encode(            s.rindex(
s.__getnewargs__(    s.endswith(          s.rjust(
s.__gt__(            s.expandtabs(        s.rpartition(
s.__hash__(          s.find(              s.rsplit(
s.__init__(          s.format(            s.rstrip(
s.__iter__(          s.format_map(        s.split(
s.__le__(            s.index(             s.splitlines(
s.__len__(           s.isalnum(           s.startswith(
s.__lt__(            s.isalpha(           s.strip(
s.__mod__(           s.isdecimal(         s.swapcase(
s.__mul__(           s.isdigit(           s.title(
s.__ne__(            s.isidentifier(      s.translate(
s.__new__(           s.islower(           s.upper(
s.__reduce__(        s.isnumeric(         s.zfill(
s.__reduce_ex__(     s.isprintable(
s.__repr__(          s.isspace(
</code>```

OwnerDisplayName: La-Z

Body:
Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:

user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__(           s.__rmod__(          s.istitle(
s.__class__(         s.__rmul__(          s.isupper(
s.__contains__(      s.__setattr__(       s.join(
s.__delattr__(       s.__sizeof__(        s.ljust(
s.__dir__(           s.__str__(           s.lower(
s.__doc__            s.__subclasshook__(  s.lstrip(
s.__eq__(            s.capitalize(        s.maketrans(
s.__format__(        s.casefold(          s.partition(
s.__ge__(            s.center(            s.replace(
s.__getattribute__(  s.count(             s.rfind(
s.__getitem__(       s.encode(            s.rindex(
s.__getnewargs__(    s.endswith(          s.rjust(
s.__gt__(            s.expandtabs(        s.rpartition(
s.__hash__(          s.find(              s.rsplit(
s.__init__(          s.format(            s.rstrip(
s.__iter__(          s.format_map(        s.split(
s.__le__(            s.index(             s.splitlines(
s.__len__(           s.isalnum(           s.startswith(
s.__lt__(            s.isalpha(           s.strip(
s.__mod__(           s.isdecimal(         s.swapcase(
s.__mul__(           s.isdigit(           s.title(
s.__ne__(            s.isidentifier(      s.translate(
s.__new__(           s.islower(           s.upper(
s.__reduce__(        s.isnumeric(         s.zfill(
s.__reduce_ex__(     s.isprintable(
s.__repr__(          s.isspace(


问:
Are there any guarantees about the order of elements that select returns?
I have a nine textboxes nested inside of vertical panels that I want grab the text from and use. For convenience, I'm just using select to grab them by class, then applying them to the constructor of a record. Basically something like:

```<code>(ns example.core
    (:require [seesaw.core :as sc]))

(apply ->RecordConstructor
       (sc/select root [:.textbox]))
</code>```

This seems to work as I expect, but I haven't been able to find anything official on what defines the order that select returns its elements in.

It seems to be based on the order that the elements were given to their parent. Is this correct?

答: I'm no expert, but it looks like seesaw just does a depth-first tree walk of its document model. So there's nothing guaranteed, but sure, it sounds like you will get things in that order: depth-first, leftmost-first. Here "left" is whatever order seesaw stores its stuff in, not necessarily display order. Again I don't know what order that is, but your guess of "the order you added stuff to the model" seems as good as any to me.</p>

Body:
I have a nine textboxes nested inside of vertical panels that I want grab the text from and use. For convenience, I'm just using select to grab them by class, then applying them to the constructor of a record. Basically something like:

(ns example.core
    (:require [seesaw.core :as sc]))

(apply ->RecordConstructor
       (sc/select root [:.textbox]))

This seems to work as I expect, but I haven't been able to find anything official on what defines the order that select returns its elements in.

It seems to be based on the order that the elements were given to their parent. Is this correct?