问:
Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

```<code>private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

答:
This is my MapsActivity class with location updates, you can update your code using my code

```package com.example.vishal.gpsloc;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, com.google.android.gms.location.LocationListener, GoogleMap.OnMapClickListener, ResultCallback<Status> {

    GoogleMap mMap;

    private MarkerOptions marker1, marker2;
    private final int GEOFENCE_REQ_CODE = 0;
    private GoogleApiClient googleApiClient;
    private double longitude;
    private double latitude;
    double lat,lon;

    List latt=new ArrayList();
    List longi=new ArrayList();

    Location lastLocation;
    String ip=null;

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    int flag=1;String cityName,stateName,countryName,root;

    private ArrayList<LatLng> points; //added
    Polyline line; //added

    File log,myDir;

    private static MQTT mqtt;
    private static BlockingConnection connection;

    private final int UPDATE_INTERVAL = 60000 ;
    private final int FASTEST_INTERVAL = 60000 ;
    private static final float SMALLEST_DISPLACEMENT = 0.25F; //quarter of a meter

    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()), cord, devname, devid = android.os.Build.SERIAL;
    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            CheckConnection();
            if (!isGooglePlayServicesAvailable()) {
                System.out.println(" My Google Play Not Available");
                finish();
            }
            points = new ArrayList<LatLng>(); //added
            setContentView(R.layout.route_mapper);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

            InitializeDB();

            //Initializing googleApiClient
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            googleApiClient.connect();

            findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    PunchStop();
                }
            });

            if (this.mMap != null) {

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    mMap.setMyLocationEnabled(true);
                    return;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        mqtt=new MQTT();
        try{
            if(ip==null){
                System.out.println("Mqtt Initialized in Maps Activity");
                ip="demo.aiotm.in:1883";
            }
            //mqtt.setHost("tcp://"+ip);
            mqtt.setHost("tcp://10.30.60.242:1883");
            connection = mqtt.blockingConnection();
            connection.connect();
        }catch (Exception e){
            e.printStackTrace();

        }
    }

    private void InitializeDB() {
        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();
        if (isExternalStorageReadable() == true && isExternalStorageWritable() == true) {
            root = Environment.getExternalStorageDirectory().toString();
            myDir = new File(root + "/GpsTracking");
            myDir.mkdirs();
            log = new File (myDir, "GpsLog");
            if (myDir.exists()) {
                System.out.println("Directory Already Exsists............");
            } else {
                try {
                    myDir = new File(root + "/GpsTracking");
                    myDir.mkdirs();
                    log = new File (myDir, "GpsLog");

                } catch (Exception e) {
                    Toast.makeText(getBaseContext()
                            ,e.toString(),
                            Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }

            }
        }else {Toast.makeText(getBaseContext(),
                "Permissions Not Availiable'",
                Toast.LENGTH_SHORT).show();}
    }

    private void PunchStop() {
        System.out.println("stop Location is "+latitude+","+longitude+"\t"+cityName   );
try {
    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    PrintWriter out = new PrintWriter(new FileWriter(log, true));
   out.append(currentDateTimeString+"\t"+latitude+","+longitude+"\t"+cityName+"\n");
   out.close();
    Toast.makeText(getBaseContext(),
            "Done writing SD 'GpsLog.txt'",
            Toast.LENGTH_SHORT).show();

}catch (Exception e){e.printStackTrace();}

        }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    private void CheckConnection() {
        String answer=null;
        ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                answer="You are connected to a WiFi Network";
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                answer="You are connected to a Mobile Network";
        }
        else
            answer = "No internet Connectivity";
        Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        getCurrentLocation();
        mMap.setOnMapLongClickListener(this);
        mMap.setOnMapClickListener(this);

    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_POWER ) {
            //Handle what you want in long press.
            Toast.makeText(getApplicationContext(),"Power Key Pressed",Toast.LENGTH_LONG).show();
                flag=1;
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    private void getCurrentLocation() {
       //mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            System.out.println("Parameters are ::" + latitude + ":" + longitude);
            //moving the map to location
            moveMap();

        }
    }

    private void moveMap() {
        /**
         * Creating the latlng object to store lat, long coordinates
         * adding marker to map
         * move the camera with animation
         */
        LatLng latLng = new LatLng(latitude, longitude);
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                .draggable(true)
                .title(cityName))
                .showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("info", "Connection Failed");
        try {
          //  connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(MapsActivity.this, "Connected", Toast.LENGTH_SHORT).show();
        getCurrentLocation();

        Log.i("info", "onConnected()");
        getLastKnownLocation();

    }

    private void getLastKnownLocation() {
        Log.d("INFO", "getLastKnownLocation()");
        System.out.println("info :: getLastKnownLocation");
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
       lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (lastLocation != null) {
            Log.i("INFO", "LasKnown location. " +
                    "Long: " + lastLocation.getLongitude() +
                    " | Lat: " + lastLocation.getLatitude());
            writeLastLocation();
            startLocationUpdates();
        } else {
            Log.w("INFO", "No location retrieved yet");
            startLocationUpdates();
        }

    }

    private LocationRequest locationRequest;

    // Start location Updatess
    private void startLocationUpdates() {
        Log.i("INFO", "startLocationUpdates()");

        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();

        locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setSmallestDisplacement(SMALLEST_DISPLACEMENT)
                .setFastestInterval(FASTEST_INTERVAL);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {

        mMap.clear();
        marker1 = null;
        marker2 = null;
        getCurrentLocation();

    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("INFO", "onLocationChanged ["+location+"]");
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title(cityName))
                .showInfoWindow();

        points.add(latLng);
        redrawline();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);

        lastLocation = location;
        writeActualLocation(location);

    }

    private void redrawline() {
        mMap.clear();  //clears all Markers and Polylines

        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
        for (int i = 0; i < points.size(); i++) {
            LatLng point = points.get(i);
            options.add(point);
        }
       getCurrentLocation(); //add Marker in current position
        line = mMap.addPolyline(options); //add Polyline

    }

    // Write location coordinates on UI
    private void writeActualLocation(Location location) {
        Log.d( "Actual Lat: ", String.valueOf(location.getLatitude()));
        Log.d( "Actual Long: ", String.valueOf(location.getLongitude()));

        lat=location.getLatitude();
        lon=location.getLongitude();
        LatLng latLng=new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions()
        .position(latLng));

    }

    private void writeLastLocation() {
        writeActualLocation(lastLocation);
    }

    @Override
    public void onResult(@NonNull Status status) {
        Log.i("INFO", "onResult: " + status);
        if ( status.isSuccess() ) {
           System.out.println("Status Succes");
            Toast.makeText(getApplicationContext(),"Status Succes",Toast.LENGTH_LONG).show();
           // drawGeofence();
        } else {
            System.out.println("Status failed");
            Toast.makeText(getApplicationContext(),"Status Failed",Toast.LENGTH_LONG).show();
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

}
```

Body:
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

Body:
This is my MapsActivity class with location updates, you can update your code using my code

package com.example.vishal.gpsloc;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.vision.barcode.Barcode;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, com.google.android.gms.location.LocationListener, GoogleMap.OnMapClickListener, ResultCallback<Status> {

    GoogleMap mMap;

    private MarkerOptions marker1, marker2;
    private final int GEOFENCE_REQ_CODE = 0;
    private GoogleApiClient googleApiClient;
    private double longitude;
    private double latitude;
    double lat,lon;

    List latt=new ArrayList();
    List longi=new ArrayList();

    Location lastLocation;
    String ip=null;

    SharedPreferences pref;
    SharedPreferences.Editor editor;
    int flag=1;String cityName,stateName,countryName,root;

    private ArrayList<LatLng> points; //added
    Polyline line; //added

    File log,myDir;

    private static MQTT mqtt;
    private static BlockingConnection connection;

    private final int UPDATE_INTERVAL = 60000 ;
    private final int FASTEST_INTERVAL = 60000 ;
    private static final float SMALLEST_DISPLACEMENT = 0.25F; //quarter of a meter

    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()), cord, devname, devid = android.os.Build.SERIAL;
    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            CheckConnection();
            if (!isGooglePlayServicesAvailable()) {
                System.out.println(" My Google Play Not Available");
                finish();
            }
            points = new ArrayList<LatLng>(); //added
            setContentView(R.layout.route_mapper);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

            InitializeDB();

            //Initializing googleApiClient
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            googleApiClient.connect();

            findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    PunchStop();
                }
            });

            if (this.mMap != null) {

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    mMap.setMyLocationEnabled(true);
                    return;
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        mqtt=new MQTT();
        try{
            if(ip==null){
                System.out.println("Mqtt Initialized in Maps Activity");
                ip="demo.aiotm.in:1883";
            }
            //mqtt.setHost("tcp://"+ip);
            mqtt.setHost("tcp://10.30.60.242:1883");
            connection = mqtt.blockingConnection();
            connection.connect();
        }catch (Exception e){
            e.printStackTrace();

        }
    }

    private void InitializeDB() {
        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();
        if (isExternalStorageReadable() == true && isExternalStorageWritable() == true) {
            root = Environment.getExternalStorageDirectory().toString();
            myDir = new File(root + "/GpsTracking");
            myDir.mkdirs();
            log = new File (myDir, "GpsLog");
            if (myDir.exists()) {
                System.out.println("Directory Already Exsists............");
            } else {
                try {
                    myDir = new File(root + "/GpsTracking");
                    myDir.mkdirs();
                    log = new File (myDir, "GpsLog");

                } catch (Exception e) {
                    Toast.makeText(getBaseContext()
                            ,e.toString(),
                            Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }

            }
        }else {Toast.makeText(getBaseContext(),
                "Permissions Not Availiable'",
                Toast.LENGTH_SHORT).show();}
    }

    private void PunchStop() {
        System.out.println("stop Location is "+latitude+","+longitude+"\t"+cityName   );
try {
    String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    PrintWriter out = new PrintWriter(new FileWriter(log, true));
   out.append(currentDateTimeString+"\t"+latitude+","+longitude+"\t"+cityName+"\n");
   out.close();
    Toast.makeText(getBaseContext(),
            "Done writing SD 'GpsLog.txt'",
            Toast.LENGTH_SHORT).show();

}catch (Exception e){e.printStackTrace();}

        }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    private void CheckConnection() {
        String answer=null;
        ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                answer="You are connected to a WiFi Network";
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                answer="You are connected to a Mobile Network";
        }
        else
            answer = "No internet Connectivity";
        Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        getCurrentLocation();
        mMap.setOnMapLongClickListener(this);
        mMap.setOnMapClickListener(this);

    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_POWER ) {
            //Handle what you want in long press.
            Toast.makeText(getApplicationContext(),"Power Key Pressed",Toast.LENGTH_LONG).show();
                flag=1;
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    private void getCurrentLocation() {
       //mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            System.out.println("Parameters are ::" + latitude + ":" + longitude);
            //moving the map to location
            moveMap();

        }
    }

    private void moveMap() {
        /**
         * Creating the latlng object to store lat, long coordinates
         * adding marker to map
         * move the camera with animation
         */
        LatLng latLng = new LatLng(latitude, longitude);
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                .draggable(true)
                .title(cityName))
                .showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("info", "Connection Failed");
        try {
          //  connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(MapsActivity.this, "Connected", Toast.LENGTH_SHORT).show();
        getCurrentLocation();

        Log.i("info", "onConnected()");
        getLastKnownLocation();

    }

    private void getLastKnownLocation() {
        Log.d("INFO", "getLastKnownLocation()");
        System.out.println("info :: getLastKnownLocation");
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
       lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (lastLocation != null) {
            Log.i("INFO", "LasKnown location. " +
                    "Long: " + lastLocation.getLongitude() +
                    " | Lat: " + lastLocation.getLatitude());
            writeLastLocation();
            startLocationUpdates();
        } else {
            Log.w("INFO", "No location retrieved yet");
            startLocationUpdates();
        }

    }

    private LocationRequest locationRequest;

    // Start location Updatess
    private void startLocationUpdates() {
        Log.i("INFO", "startLocationUpdates()");

        pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        editor = pref.edit();

        locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setSmallestDisplacement(SMALLEST_DISPLACEMENT)
                .setFastestInterval(FASTEST_INTERVAL);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {

        mMap.clear();
        marker1 = null;
        marker2 = null;
        getCurrentLocation();

    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("INFO", "onLocationChanged ["+location+"]");
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            cityName = addresses.get(0).getAddressLine(0);
            stateName = addresses.get(0).getAddressLine(1);
            countryName = addresses.get(0).getAddressLine(2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title(cityName))
                .showInfoWindow();

        points.add(latLng);
        redrawline();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);

        lastLocation = location;
        writeActualLocation(location);

    }

    private void redrawline() {
        mMap.clear();  //clears all Markers and Polylines

        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
        for (int i = 0; i < points.size(); i++) {
            LatLng point = points.get(i);
            options.add(point);
        }
       getCurrentLocation(); //add Marker in current position
        line = mMap.addPolyline(options); //add Polyline

    }

    // Write location coordinates on UI
    private void writeActualLocation(Location location) {
        Log.d( "Actual Lat: ", String.valueOf(location.getLatitude()));
        Log.d( "Actual Long: ", String.valueOf(location.getLongitude()));

        lat=location.getLatitude();
        lon=location.getLongitude();
        LatLng latLng=new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions()
        .position(latLng));

    }

    private void writeLastLocation() {
        writeActualLocation(lastLocation);
    }

    @Override
    public void onResult(@NonNull Status status) {
        Log.i("INFO", "onResult: " + status);
        if ( status.isSuccess() ) {
           System.out.println("Status Succes");
            Toast.makeText(getApplicationContext(),"Status Succes",Toast.LENGTH_LONG).show();
           // drawGeofence();
        } else {
            System.out.println("Status failed");
            Toast.makeText(getApplicationContext(),"Status Failed",Toast.LENGTH_LONG).show();
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

}


来源: stackexchange

问:
How do I save classifier's most informative features into a variable? (Python NLTK)
Say I have this snippet of code:

```<code>classifier.show_most_informative_features(10)
</code>```

Python will display 10 features along with their pos,neg tags.
Is there any way to save the features into a variable?

答:
Solution works on python3, saved to output_string variable.</p>

```<code>from io import StringIO
import contextlib
import sys

@contextlib.contextmanager
def stdout_redirect(where):
    sys.stdout = where
    try:
        yield where
    finally:
        sys.stdout = sys.__stdout__

with stdout_redirect(StringIO()) as new_stdout:
    classifier.show_most_informative_features(15)

new_stdout.seek(0)

# output assigned to variable
output_string = new_stdout.read()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I have this snippet of code:

classifier.show_most_informative_features(10)

Python will display 10 features along with their pos,neg tags.
Is there any way to save the features into a variable?

Body:
Solution works on python3, saved to output_string variable.

from io import StringIO
import contextlib
import sys

@contextlib.contextmanager
def stdout_redirect(where):
    sys.stdout = where
    try:
        yield where
    finally:
        sys.stdout = sys.__stdout__

with stdout_redirect(StringIO()) as new_stdout:
    classifier.show_most_informative_features(15)

new_stdout.seek(0)

# output assigned to variable
output_string = new_stdout.read()


问:
MFMailComposeViewController in Android?
is there something like MFMailComposeViewController in iPhone for Android, basicly Activity which handles email addresses and email creation etc. ? or all must be made from scratch by me?

cheers,
/Marcin

答:
I dont know about the MFMailComposeViewController from iPhone but I don know Intents of Android. You can use these to send input gathered from user and allow device installed email clients to handle it for you.

```<code>try{
    Intent emailIntent=new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"sample@email.com"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Sample Body");
    emailIntent.setType("text/plain");
    startActivity(emailIntent);
}catch(android.content.ActivityNotFoundException ex){
//Theres no email client installed on users device.
}
</code>```

You can use EditText android widgets to accept input from user. Use EditText.getText() to
do so.
You can also specify that you want to use default email client of the device by setting up intent with

```<code>emailIntent.setClassName(com.android.email, com.android.email.activity.MessageCompose);
</code>```

This will launch default email clients compose window. Where use may choose to edit and send message.

Make sure you always catch ActivityNotFound exception since there might not be any available email clients installed and/or configured.

ContentLicense: CC BY-SA 2.5

Title: MFMailComposeViewController in Android?

Body:
I dont know about the MFMailComposeViewController from iPhone but I don know Intents of Android. You can use these to send input gathered from user and allow device installed email clients to handle it for you.

try{
    Intent emailIntent=new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"sample@email.com"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Sample Subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Sample Body");
    emailIntent.setType("text/plain");
    startActivity(emailIntent);
}catch(android.content.ActivityNotFoundException ex){
//Theres no email client installed on users device.
}

You can use EditText android widgets to accept input from user. Use EditText.getText() to
do so.
You can also specify that you want to use default email client of the device by setting up intent with

emailIntent.setClassName(com.android.email, com.android.email.activity.MessageCompose);

This will launch default email clients compose window. Where use may choose to edit and send message.

Make sure you always catch ActivityNotFound exception since there might not be any available email clients installed and/or configured.


问:
Best way to convert ArrayList to string
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

```<code>String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets
</code>```

答:
Instead of the regex you're currently using, use [\\[\\]].

```<code>List<Integer> list = Arrays.asList(1,2,3,4,5);
String s = list.toString().replaceAll("[\\[\\]]", "");
System.out.println(s);
</code>```

Or you can use substring, like

```<code>String s = list.toString().substring(1, list.toString().length()-1);
</code>```

Title: Best way to convert ArrayList to string

Body:
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets

Body:
Instead of the regex you're currently using, use [\\[\\]].

List<Integer> list = Arrays.asList(1,2,3,4,5);
String s = list.toString().replaceAll("[\\[\\]]", "");
System.out.println(s);

Or you can use substring, like

String s = list.toString().substring(1, list.toString().length()-1);


问:
Hibernate deletes occurring out of order
I have the following classes:

Category

```<code>@Entity
@Table(name = "category", schema = "customer")
public class Category extends CustomerOwned {
   ...
}
</code>```

CatalogueItem

```<code>@Entity
@Table(name = "catalogue_item", schema = "customer")
@EntityListeners(value = { CatalogueItemStatusListener.class })
public class CatalogueItem extends CatalogueOwned implements Statusable<CatalogueItem, CatalogueItemStatus> {
    ...
    @OneToMany(mappedBy = "catalogueItem", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CatalogueItemCategory> categories;
    ...
}
</code>```

CatalogueItemCategory

```<code>@Entity
@Table(name = "catalogue_item_category", schema = "customer")
public class CatalogueItemCategory extends CatalogueItemOwned implements CategoryOwner {
    ...
    @ManyToOne
    @JoinColumn(name = "category_id", nullable = false, insertable = true, updatable = false)
    private Category category;
    ...
}
</code>```

We perform very few hard deletes in our application, but Categorys are hard deleted. CatalogueItemCategorys are also hard deleted.

I'm creating a service to allow someone to delete a Category and at the same time I check all Category dependencies and delete those too, so I'm doing this:

```<code>@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> {
            item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
            sendEvent(prepareEvent(new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId()));
        });
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.delete(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}
</code>```

This is causing the following exception:

```<code>Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKLYKUEHJG9UL0LR36O5XDD3MLF: CUSTOMER.CATALOGUE_ITEM_CATEGORY FOREIGN KEY(CATEGORY_ID) REFERENCES CUSTOMER.CATEGORY(ID) (1)"; SQL statement:
delete from customer.category where id=? [23503-192]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:426)
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:443)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:318)
    at org.h2.table.Table.fireConstraints(Table.java:967)
    at org.h2.table.Table.fireAfterRow(Table.java:985)
    at org.h2.command.dml.Delete.update(Delete.java:101)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 109 common frames omitted
</code>```

I've tried replacing this bit:

```<code>item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
</code>```

with this:

```<code>item.getCategories().stream()
    .filter(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()))
    .forEach(catalogueItemCategoryRepository::delete);
</code>```

but it's not making any difference. Hibernate is deleting the objects out of order. It should be deleting the CatalogueItemCategory objects before the Category objects, but it's not.

How do I get it to delete in the correct order?

Edit: missed this class which provides the parent of the CatalogueItemCategory:

```<code>@MappedSuperclass
public class CatalogueItemOwned extends Updateable {
    ...
    @ManyToOne
    @JoinColumn(name = "catalogue_item_id", nullable = false, insertable = true)
    private CatalogueItem catalogueItem;
    ...
}
</code>```

答:
There are dirty solutions, that are both anti-pattern, but would probably work:

Either use a flush after each delete, or delete with a native query.

That said, I recommend not to use any of these solutions, but to search for a cleaner solution.

Body:
I have the following classes:

Category

@Entity
@Table(name = "category", schema = "customer")
public class Category extends CustomerOwned {
   ...
}

CatalogueItem

@Entity
@Table(name = "catalogue_item", schema = "customer")
@EntityListeners(value = { CatalogueItemStatusListener.class })
public class CatalogueItem extends CatalogueOwned implements Statusable<CatalogueItem, CatalogueItemStatus> {
    ...
    @OneToMany(mappedBy = "catalogueItem", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CatalogueItemCategory> categories;
    ...
}

CatalogueItemCategory

@Entity
@Table(name = "catalogue_item_category", schema = "customer")
public class CatalogueItemCategory extends CatalogueItemOwned implements CategoryOwner {
    ...
    @ManyToOne
    @JoinColumn(name = "category_id", nullable = false, insertable = true, updatable = false)
    private Category category;
    ...
}

We perform very few hard deletes in our application, but Categorys are hard deleted. CatalogueItemCategorys are also hard deleted.

I'm creating a service to allow someone to delete a Category and at the same time I check all Category dependencies and delete those too, so I'm doing this:

@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> {
            item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
            sendEvent(prepareEvent(new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId()));
        });
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.delete(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}

This is causing the following exception:

Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKLYKUEHJG9UL0LR36O5XDD3MLF: CUSTOMER.CATALOGUE_ITEM_CATEGORY FOREIGN KEY(CATEGORY_ID) REFERENCES CUSTOMER.CATEGORY(ID) (1)"; SQL statement:
delete from customer.category where id=? [23503-192]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:426)
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:443)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:318)
    at org.h2.table.Table.fireConstraints(Table.java:967)
    at org.h2.table.Table.fireAfterRow(Table.java:985)
    at org.h2.command.dml.Delete.update(Delete.java:101)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 109 common frames omitted

I've tried replacing this bit:

item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));

with this:

item.getCategories().stream()
    .filter(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()))
    .forEach(catalogueItemCategoryRepository::delete);

but it's not making any difference. Hibernate is deleting the objects out of order. It should be deleting the CatalogueItemCategory objects before the Category objects, but it's not.

How do I get it to delete in the correct order?

Edit: missed this class which provides the parent of the CatalogueItemCategory:

@MappedSuperclass
public class CatalogueItemOwned extends Updateable {
    ...
    @ManyToOne
    @JoinColumn(name = "catalogue_item_id", nullable = false, insertable = true)
    private CatalogueItem catalogueItem;
    ...
}


问:
Deleting "Android\sdk" folder from the path "C:\User\AppData\Local\Android\Sdk"
Will it cause any problem if I delete the "Android\sdk" [Size: 2 GB] folder from an old directory path "C:\User\AppData\Local\Android\Sdk" ?
I actually do have another "Android\sdk" folder [Size: 23 GB] on a different location [Local Disk D] since previously I faced WHITESPACE NAMING ISSUES while using Android Studio. So I think the folder is lying idle on my Local Disk C. Should I delete the folder on the path "C:\User\AppData\Local\Android\Sdk" ? Or, will it harm the IDE in the future ?

答:
You can simply make a link folder to your main android sdk folder (23gb). you can put that link in place of your first folder (2gb). even you can have your main folder in a path with spaces, but you've to create a link folder for some where like c:\android\sdk and in your favorite IDE sets the path to that. It's a OS level abstraction and everything works like a charm on top of that

For example:
mklink /j C:\android-sdk "C:\Program Files (x86)\Android\android-sdk"


问:
Correct path to read an image in Opencv(c++)?
I wrote bellow code to read and show an image from a path in widows:

```<code>#include "SIFT.h"
#include <Windows.h>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/core.hpp>

int main(int argc, const char* argv[])
{

    cv::Mat input = cv::imread("F:/Personal/1.jpg", IMREAD_COLOR);
     if (input.empty()){
         cout << "is empty";
         getchar();
         return -1;

     }
     namedWindow("Display window", WINDOW_AUTOSIZE);// Create a window for display.
     imshow("Display window", input);
    cv::waitKey(0);
    //cv::Mat* m = &input;
    //implementSIFT s(input, nullptr, nullptr, nullptr);
    return 0;
}
</code>```

But the image seems empty. What is correct path to read an image?
Or Where is the problem from?

答:
Correct path should be :</p>

```<code>    cv::Mat input = cv::imread("F:\\Personal/1.jpg", IMREAD_COLOR);
</code>```

Body:
I wrote bellow code to read and show an image from a path in widows:

#include "SIFT.h"
#include <Windows.h>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/core.hpp>

int main(int argc, const char* argv[])
{

    cv::Mat input = cv::imread("F:/Personal/1.jpg", IMREAD_COLOR);
     if (input.empty()){
         cout << "is empty";
         getchar();
         return -1;

     }
     namedWindow("Display window", WINDOW_AUTOSIZE);// Create a window for display.
     imshow("Display window", input);
    cv::waitKey(0);
    //cv::Mat* m = &input;
    //implementSIFT s(input, nullptr, nullptr, nullptr);
    return 0;
}

But the image seems empty. What is correct path to read an image?
Or Where is the problem from?

Body:
Correct path should be :

    cv::Mat input = cv::imread("F:\\Personal/1.jpg", IMREAD_COLOR);


问:
heap overflow affecting other programs
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.</p>

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

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

    return(0);
}
</code>```

答:
So my question is whether the memory for heap is shared with other programs?

Physical memory (RAM) is a resource that is shared by all processes. The operating system makes decisions about how much RAM to allocate to each process and adjusts that over time.

If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution?

At the time the program starts executing, the operating system has no idea how much memory the program will want or need. Instead, it deals with allocations as they happen. Unless configured otherwise, it will typically do everything it possibly can to allow the program's allocation to succeed because presumably there's a reason the program is doing what it's doing and the operating system won't try to second guess it.

Title: heap overflow affecting other programs

Body:
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.

#include <stdio.h>
#include <malloc.h>

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

    return(0);
}


问:
How to set proxy authentication (user & password) using Python + Selenium
I am using Firefox WebDriver in Python 2.7 with Selenium. My python program starts Firefox browser and visits different websites when I run the program. But, I need to set the proxy with authentication, so that when program visits any website, it will visit through the proxy server.

There are some similar questions on SO. But, there is no specific solution for Selenium Firefox WebDriver of Python.

Python Selenium Webdriver - Proxy Authentication

Running selenium behind a proxy server

答:
In an addition to the answer with extension.

You can also use form filling to dynamically change credentials on your proxy. Just load the extension page, fill the form automatically and click save!

ContentLicense: CC BY-SA 4.0


答:
```<code>mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);   // 'this' is  onLocationChanged()

@Override
public void onLocationChanged(Location location) {
         mCurrentLatitude = location.getLatitude();
         mCurrentLongitude = location.getLongitude();
}
</code>```

Title: Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER


问:
Allow Orgin in my API
I need to put allow origin in my Jersery Project.
m getting error:-
 access-control-allow-origin-issue-in-angular-2
Where should I need to put. </p>

```<code>@GET
@Produces("application/json")
public Response getLipid() {
    LipidDAO dao = new LipidDAO();
    List lipid = dao.getLipid();
    String json = new Gson().toJson(lipid);
    return Response.ok().entity(json.toString()).build();
}
</code>```

答:
You can tack it on as a header after the Response.ok()

```<code>return Response.ok()
    .entity(json.toString())
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
    .build();
</code>```

Or do it in an implementation of ContainerResponseFilter and register that filter to your application.

Probably don't want to leave it as * unless you want user's browsers from other sites accessing your API though.

Title: Allow Orgin in my API

Body:
I need to put allow origin in my Jersery Project.
m getting error:-
 access-control-allow-origin-issue-in-angular-2
Where should I need to put.

@GET
@Produces("application/json")
public Response getLipid() {
    LipidDAO dao = new LipidDAO();
    List lipid = dao.getLipid();
    String json = new Gson().toJson(lipid);
    return Response.ok().entity(json.toString()).build();
}

Body:
You can tack it on as a header after the Response.ok()

return Response.ok()
    .entity(json.toString())
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
    .build();

Or do it in an implementation of ContainerResponseFilter and register that filter to your application.

Probably don't want to leave it as * unless you want user's browsers from other sites accessing your API though.


问:
CodeIgniter / Ajax . Posting parameters through ajax to CodeIgniter controller
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

```<code>$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });
</code>```

Here is my controller function.

```<code>    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}
</code>```

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

答:
there is a syntax error

```<code>$(document).ready(function()
{

$('.add_cart').click(function(){
  var quantity = $('#qty').val();
  var product_id = $(this).data("productid");
  var product_name = $(this).data("productname");
  var product_price = $(this).data("price");

  if(quantity != '' && quantity > 0)
   {
       $.ajax({
        url:"<?php echo base_url(); ?>products/add_product_to_cart",
        method:"POST",
        data:{"product_id":product_id, "product_name":product_name, "product_price":product_price, "quantity":quantity},
        success:function(data)
        {
            alert('success');
        }
       });
      }
      else
      {
       alert("Please Enter quantity");
      }

    });
  });
</code>```

the parameters shoulb be like this
data:{"product_id":product_id, "product_name":product_name, "product_price":product_price, "quantity":quantity},

Body:
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });

Here is my controller function.

    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

Body:
there is a syntax error

$(document).ready(function()
{

$('.add_cart').click(function(){
  var quantity = $('#qty').val();
  var product_id = $(this).data("productid");
  var product_name = $(this).data("productname");
  var product_price = $(this).data("price");

  if(quantity != '' && quantity > 0)
   {
       $.ajax({
        url:"<?php echo base_url(); ?>products/add_product_to_cart",
        method:"POST",
        data:{"product_id":product_id, "product_name":product_name, "product_price":product_price, "quantity":quantity},
        success:function(data)
        {
            alert('success');
        }
       });
      }
      else
      {
       alert("Please Enter quantity");
      }

    });
  });

the parameters shoulb be like this
data:{"product_id":product_id, "product_name":product_name, "product_price":product_price, "quantity":quantity},


问:
Should I break the atomicity rule storing a list of items when there is no reason to query about items?
The same item may belong to multiple lists, and each list has many items.

The "proper" design: Make a join table, which has list_ID and item_ID. When I want all the items in a list, query for list_ID.

Design that breaks the atomicity rule: Make a list table. Primary Key, and either repeating columns or non-atomic columns. These deviations suffer as drawback the inability to efficiently query on items.

Normalizing a database to 1NF makes sure each column is atomic, so I should NOT do option B. That would make querying items hard. E.g. "how many of this item got sold?" or "how many times is this item in a list?"

I will never need that data. Should I break the atomicity rule storing a list of items when there is no reason to query about items? Verses a join table that requires a whole join table be scanned.

Is that already a mistake? Is there a meme like "you'll always want to be able to query, and you won't have time to reorganize the database when you scale"? Am I overestimating how long it wouldd take MySQL to scan a join table?

It's common sense to accept that non-compliant form if I know that the drawback is not important to the application.

答:
TL; DR If you are going to write generic query/constraint expressions about parts of values of a column then the parts ought to get their own columns; otherwise not. If you change your mind then you can supply the old schema via a view, although typically updates would need recoding.

Relations have rows that have for each column one value of that column's type. Notions of "relation" or "normalized" or "1NF" in terms of some notion of "atomicity" are vague, confused and unhelpful. Eg a list is typically called "non-atomic", while a string is called "atomic"--even though a string is a list of characters. Bite the bullet--it's nonsense.

Every single design has to make this where-the-turtles-stop decision about its column types. It cannot be avoided. (Even when you get to a bit-typed column, you can decide to have a separate table for only the rows that would have 1s.) (Then there is no column hence no column type.) It is a design quality issue, but not an issue of normalization to higher NFs (normal forms).

Nothing in "normalization" to higher NFs (reducing certain update/redundancy problems by replacing a table by tables that join back to it) requires prior application-dependent "normalization" to "1NF" per "atomicity" (replacing a table by some table(s) with columns for parts of its columns). Because when rearranging to "1NF" would help we would need to write constraint expressions involving parts of values of columns so we would be doing that rearrangement anyway.

(Unfortunately "normalized" & "1NF" & "0NF" get used in many different ways, many nonsensical although common. Better to just say what exact property/properties you mean.)

PS 1 A list is generally considered to be an ordered collection of items, a set being an unordered collection of items. Predicate "collection C has item I as Nth member" records a list, "collection C has item I as a member" a set.

PS 2 PS Your presumption that a representation of a list or set "vertically" or "compactly" "down" a column in a table involves any more "scanning" than a representation "horizontally" or "compactly" "across" a value in a column in a row is naive/unjustified. Ie ((list, item1, 1), (list, item2, 2), ...) vs (list, [item1, item2, ...]).


问:
Simple search on Firebase database with swift 3
I'm new with Firebase and for the past two days, I've been trying to figure out how to perform a simple search on my db without any success.

And I want to perform search on all the channels children. For example I want to search if there is a channel named Klx0N4pxsBHGVkhYuY0. I try the

```<code>queryEqual(toValue: "Klx0N4pxsBHGVkhYuY0")
</code>```

but no luck.

Thank you so much in advance for your time and help.

答:
If you want only to "search if there is a channel named Klx0N4pxsBHGVkhYuY0", you can do this:

```<code>let ref = FIRDatabase.database().reference().child("channels")

ref.observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.hasChild("Klx0N4pxsBHGVkhYuY0") {
         // yes, it is
    } else {
         // no, it isn't
    }
})
</code>```

Hope it helps.

Body:
I'm new with Firebase and for the past two days, I've been trying to figure out how to perform a simple search on my db without any success.

And I want to perform search on all the channels children. For example I want to search if there is a channel named Klx0N4pxsBHGVkhYuY0. I try the

queryEqual(toValue: "Klx0N4pxsBHGVkhYuY0")

but no luck.

Thank you so much in advance for your time and help.

Body:
If you want only to "search if there is a channel named Klx0N4pxsBHGVkhYuY0", you can do this:

let ref = FIRDatabase.database().reference().child("channels")

ref.observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.hasChild("Klx0N4pxsBHGVkhYuY0") {
         // yes, it is
    } else {
         // no, it isn't
    }
})

Hope it helps.


问:
Finding audio peaks in video files
I have a bunch of video files that I want to process. I want to write a program that can find the audio peaks in each file and return the times where those peaks occurred.

I've looked for a lot of different APIs in different languages but couldn't get any of them to work. I am partial to php and java, so if anyone knows any good audio processing libraries in those languages that would be great! But really I don't care too much about the language. I will need to run this program on a cron.

Also, is it possible to use system calls to ffmpeg from within a script to accomplish this? Thanks in advance.

答:
While I've only used this to work directly with audio files, the python wrapper around theechonest's audio analysis service can slurp in the audio from various video files.  It uses ffmpegs shared libs to do this, though I find this wrapper much easier to work with via python then the command line.

Of particular interest within the api is echonest.video which is, to quote the docs:

Framework that turns video into silly putty.

I'd add a couple other helpful urls but apparently I can only add one since I don't have a reputation...

anyway, hopefully that's a helpful lead.

Title: Finding audio peaks in video files


问:
How to write script tag inside build html in a javascript function?
I am trying open build html(inside js funtion) to show table on a new tab.
Now I am trying to add a js function for user to download table in excel format, but as soon as I try to add  tag code breaks.

I tried following:
Wrote download funtion inside script tag of built html code in js function.
Added a new javascript file containing download js function.
Added download function in a variable and tried including it in script tag.
Used '+
        '
'+Header+'

    Key	    Value
';

        for (var key in data) {
            var eachrow = '
'
            + '' + key + '	'
            + '' + data[key] + '	'
            + '
';
            html=html+eachrow;
        }
        html=html+'

<button id="exportExcel" onclick="download()">Export</button>';
        return html;
    }
```

The problem here is as soon as I close script tag(i.e ),
my main script tag (in which all functions are written) is shown as closed. And same appears on screen.

答: use "\" in a string. the symbol "\<" is an escape character for "<".</p>

Body:
I am trying open build html(inside js funtion) to show table on a new tab.
Now I am trying to add a js function for user to download table in excel format, but as soon as I try to add  tag code breaks.

I tried following:
Wrote download funtion inside script tag of built html code in js function.
Added a new javascript file containing download js function.
Added download function in a variable and tried including it in script tag.
Used '+
        '
'+Header+'

    Key	    Value
';

        for (var key in data) {
            var eachrow = '
'
            + '' + key + '	'
            + '' + data[key] + '	'
            + '
';
            html=html+eachrow;
        }
        html=html+'

<button id="exportExcel" onclick="download()">Export</button>';
        return html;
    }

The problem here is as soon as I close script tag(i.e ),
my main script tag (in which all functions are written) is shown as closed. And same appears on screen.


问:
How to create a custom route for show action in rails 5?
I have a model 'Item'. It all works fine, however am not completely satisfied with its show path. I want to use certain parameters from items table to construct a more SEO friendly url. So here is my question..

How can I change my Show action url
from
'mysite.com/items/1'
to
'mysite.com/items/item-name/item-city/item-id' where item-name, item-city, and item-id are dynamic for each specific item.

Is it possible to achieve this without a gem? if yes, how? If no, which gem would you suggest to achieve this in simplest way?

Thanks

答:
You can do something relatively simple and stays true to Rails by adding a to_param method to your model like so:

```<code>def to_param
  "#{id}-#{name}-#{city.name}"
end
</code>```

What this does is every time you use a method like the item_path, it will use the @item.to_param method (this is what it does now, and returns :id).  Generating the normal route, but replacing the :id param with the SEO friendly one.

And, on the other end, when you go to find(params[:id]) in the controller in your show, edit, delete, or update actions, it will to a to_i on it and turn it back into an id.  This is what it does now, but to_i on an int is still an int.

Your urls will look something like

```<code>/items/56-boston-itemname
</code>```

The other benefit to this, if you happen to change the item name or the city name, it will change all the urls appropriately, but old urls that were sent in email will still work.

Body:
You can do something relatively simple and stays true to Rails by adding a to_param method to your model like so:

def to_param
  "#{id}-#{name}-#{city.name}"
end

What this does is every time you use a method like the item_path, it will use the @item.to_param method (this is what it does now, and returns :id).  Generating the normal route, but replacing the :id param with the SEO friendly one.

And, on the other end, when you go to find(params[:id]) in the controller in your show, edit, delete, or update actions, it will to a to_i on it and turn it back into an id.  This is what it does now, but to_i on an int is still an int.

Your urls will look something like

/items/56-boston-itemname

The other benefit to this, if you happen to change the item name or the city name, it will change all the urls appropriately, but old urls that were sent in email will still work.


问:
echo specific part of array in php
I'm still learning php arrays and I'm trying to echo a

```<code>array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=> string(5) "title" [3]=> string(11) "description" [4]=> string(4) "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=> string(12) "image:height" } NULL site_name => Playbuzzurl => http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842
</code>```

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=>
  string(5) "title" [3]=> string(11) "description" [4]=> string(4)
  "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=>
  string(12) "image:height" } NULL site_name => Playbuzzurl =>
  http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle
  => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage
  => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

I'm trying to echo just the value for description which is It's 2017, so it's about time we update the books!

I've tried several different things, but nothing works. Any help is greatly appreciated.

```<code>echo $array[0]['description'];      // returns nothing
var_dump($key);                     // returns string(12) "image:height"
</code>```

Current Code

```<code><?php
require_once('OpenGraph.php');

$graph = OpenGraph::fetch('http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personality');
var_dump($graph->keys());
var_dump($graph->schema);

foreach ($graph as $key => $value) {
    echo "$key => $value<br><hr>";
}
echo "Value Below<hr>";
echo $array['description'];

?>
</code>```

答:
Just call

```<code>echo $array[3];
</code>```

Or use associative arrays which can be called

```<code>echo $array['description'];
</code>```

http://php.net/manual/en/language.types.array.php

Title: echo specific part of array in php

Body:
I'm still learning php arrays and I'm trying to echo a

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=> string(5) "title" [3]=> string(11) "description" [4]=> string(4) "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=> string(12) "image:height" } NULL site_name => Playbuzzurl => http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=>
  string(5) "title" [3]=> string(11) "description" [4]=> string(4)
  "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=>
  string(12) "image:height" } NULL site_name => Playbuzzurl =>
  http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle
  => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage
  => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

I'm trying to echo just the value for description which is It's 2017, so it's about time we update the books!

I've tried several different things, but nothing works. Any help is greatly appreciated.

echo $array[0]['description'];      // returns nothing
var_dump($key);                     // returns string(12) "image:height"

Current Code

<?php
require_once('OpenGraph.php');

$graph = OpenGraph::fetch('http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personality');
var_dump($graph->keys());
var_dump($graph->schema);

foreach ($graph as $key => $value) {
    echo "$key => $value

";
}
echo "Value Below
";
echo $array['description'];

?>

Body:
Just call

echo $array[3];

Or use associative arrays which can be called

echo $array['description'];

http://php.net/manual/en/language.types.array.php


问:
Link within a text in another column php
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.</p>

```<code> echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></b></h4><hr>";
</code>```

答:
Try this:

```<code>echo '<b><h4><a href="'.$list["link1"].'">'.$list["updates1"].'</a></h4></b><hr>';
</code>```

As per OP's example in the comment:

```<code>echo '<b><h4><a href="upload/'.$list["link1"].'" target=_"blank">'.$list["updates1"].'</a></b></h4><hr>';
</code>```

Body:
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.

 echo "
{$list["updates1"]}{$list["link1"]}

";

Body:
Try this:

echo '<b><h4><a href="'.$list["link1"].'">'.$list["updates1"].'</a></h4></b><hr>';

As per OP's example in the comment:

echo '<b><h4><a href="upload/'.$list["link1"].'" target=_"blank">'.$list["updates1"].'</a></b></h4><hr>';


问:
How to use Aadhar card api in our android application
I have tried below given code to integrate Aadhar card api in android  but i am unable to find any solution. Please suggest me.

I have use this code.
https://authportal.uidai.gov.in/developer

答:
Android SDK is available for Aadhaar. You have to register on Aadhaar Bridge website and then you can get SDK.

If you want to scan QR code on Aadhaar card, check out these Android code here and here on github.


问:
problem with getting the value of a textarea in spring framework, web-flow
I'm a newbie in Spring MVC Framework, and the spring web flows.
I just wanna define a textfield, get the value and store it in the database.
Here is what I got:

in "myflow.xml" file first I've definned

<var name="varName" class="java.lang.String"/>

then in an action state

```
    <action-state id="someFlowId">
        <evaluate expression="someEJBService.doTheStaff(varName)"/>
        <transition to="anotherFlow"/>
    </action-state>```

finally In the "myPage.xhtml" file I got

```
    <h:panelGrid columns="2">
        <injsf:inputtextarea id="richText_varName" label="MyLabel" rows="1" size="50" required="true" value="#{varName}"/>
    </h:panelGrid>
```

there I also have the implementation of the java file, but
when I run the application, I can not see the value I've entered to the textarea, in debugging, the varName value is just ""

what sholud be the reason, thanks for your help.

答:
Thank you Bozho, your comment let me think different :)

from the <injsf:textarea> component I was supposed to get the value with entityValue, not just value

```
<injsf:inputtextarea id="richText_aciklama" label="#{lbl.label.gnl.aciklama}" rows="1" size="50" required="true" entityValue="#{fh.aciklama}"/>
```

Body:
I'm a newbie in Spring MVC Framework, and the spring web flows.
I just wanna define a textfield, get the value and store it in the database.
Here is what I got:

in "myflow.xml" file first I've definned

<var name="varName" class="java.lang.String"/>

then in an action state

    <action-state id="someFlowId">
        <evaluate expression="someEJBService.doTheStaff(varName)"/>
        <transition to="anotherFlow"/>
    </action-state>

finally In the "myPage.xhtml" file I got

    <h:panelGrid columns="2">
        <injsf:inputtextarea id="richText_varName" label="MyLabel" rows="1" size="50" required="true" value="#{varName}"/>
    </h:panelGrid>

there I also have the implementation of the java file, but
when I run the application, I can not see the value I've entered to the textarea, in debugging, the varName value is just ""

what sholud be the reason, thanks for your help.

Body:
Thank you Bozho, your comment let me think different :)

from the <injsf:textarea> component I was supposed to get the value with entityValue, not just value

<injsf:inputtextarea id="richText_aciklama" label="#{lbl.label.gnl.aciklama}" rows="1" size="50" required="true" entityValue="#{fh.aciklama}"/>


问:
Python Tkinter first script - window not showing
I am really really new to Python, and have not done any serious coding for many years, so please bear with me.

I used the following script just to learn about Tkinter GUI codes.

```<code>import tkinter as tk
MYwindow=tk.Tk()
input("wait")
</code>```

When using the IDLE line interpreter of Python, line 1 and line 2 would show the window frame created.

But when saving the code in a .py file, running the file, would not show the window anywhere at all.  So I added line #3, to stop the CMD window from closing, but the MYwindow is still not showing.

Have I missed some other initialisation code, environment setup, or something else?  Please help

答:
You’re required to call the Tk’s mainloop when running the tkinter program as a script. It keeps the program alive and constantly receiving event. P.S. in most cases, you should never have a while True loop or anything that will interrupt the mainloop.

```<code>import tkinter as tk
MYwindow=tk.Tk()
Mywindow.mainloop()
</code>```

Body:
I am really really new to Python, and have not done any serious coding for many years, so please bear with me.

I used the following script just to learn about Tkinter GUI codes.

import tkinter as tk
MYwindow=tk.Tk()
input("wait")

When using the IDLE line interpreter of Python, line 1 and line 2 would show the window frame created.

But when saving the code in a .py file, running the file, would not show the window anywhere at all.  So I added line #3, to stop the CMD window from closing, but the MYwindow is still not showing.

Have I missed some other initialisation code, environment setup, or something else?  Please help

Body:
You’re required to call the Tk’s mainloop when running the tkinter program as a script. It keeps the program alive and constantly receiving event. P.S. in most cases, you should never have a while True loop or anything that will interrupt the mainloop.

import tkinter as tk
MYwindow=tk.Tk()
Mywindow.mainloop()