问:
How to get current Location in GoogleMap using FusedLocationProviderClient
I want to get periodic (say every 2 minutes) current location updates for this I'm following official documentation, I wrote this code but its not giving current location updates every two minutes even specified in LocationRequest object that I'm passing in requestLocationUpdates(), here is code:</p>

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map =
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}

@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude())
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
</code>```

答:
This is similar to my other answer here, updated to use the recently introduced FusedLocationProviderClient class.

In order to use a FusedLocationProviderClient in conjunction with a Google Map:

Wait until the Google Map is ready

Request the Location permission at runtime if needed

Request location updates once the permission is granted

Update the Google Map once the user's location is obtained

First ensure that you're using at least version 11 of Google Play Services, as older versions don't have the FusedLocationProviderClient class (newer versions will work as well):

```<code>dependencies {
      implementation 'com.google.android.gms:play-services-maps:17.0.0'
      implementation 'com.google.android.gms:play-services-location:17.0.0'
    //........
}
</code>```

Note that the FusedLocationProviderClient is present in version 11.0.2, but due to bugs in the initial implementation, it's recommended that you only use this class on 11.6.0 and later.
From the documentation:

Note: It's recommended to use Google Play services version 11.6.0 or
  higher, which includes bug fixes for this class.

Add the location permissions in the AndroidManifest.xml file, inside the manifest tag and outside of the application tag:

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

Add the API key to the AndroidManifest.xml inside the application tag:

```<code>    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza___YOUR_KEY_HERE______"/>
</code>```

Kotlin

Here is the full Activity class in Kotlin:

```<code>class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    lateinit var mGoogleMap: GoogleMap
    var mapFrag: SupportMapFragment? = null
    lateinit var mLocationRequest: LocationRequest
    var mLastLocation: Location? = null
    internal var mCurrLocationMarker: Marker? = null
    internal var mFusedLocationClient: FusedLocationProviderClient? = null

    internal var mLocationCallback: LocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val locationList = locationResult.locations
            if (locationList.isNotEmpty()) {
                //The last location in the list is the newest
                val location = locationList.last()
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude())
                mLastLocation = location
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker?.remove()
                }

                //Place current location marker
                val latLng = LatLng(location.latitude, location.longitude)
                val markerOptions = MarkerOptions()
                markerOptions.position(latLng)
                markerOptions.title("Current Position")
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions)

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11.0F))
            }
        }
    }

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

        supportActionBar?.title = "Map Location Activity"

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        mapFrag = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFrag?.getMapAsync(this)
    }

    public override fun onPause() {
        super.onPause()

        //stop location updates when Activity is no longer active
        mFusedLocationClient?.removeLocationUpdates(mLocationCallback)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mGoogleMap = googleMap
        mGoogleMap.mapType = GoogleMap.MAP_TYPE_HYBRID

        mLocationRequest = LocationRequest()
        mLocationRequest.interval = 120000 // two minute interval
        mLocationRequest.fastestInterval = 120000
        mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                //Location Permission already granted
                mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
                mGoogleMap.isMyLocationEnabled = true
            } else {
                //Request Location Permission
                checkLocationPermission()
            }
        } else {
            mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
            mGoogleMap.isMyLocationEnabled = true
        }
    }

    private fun checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            ) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                AlertDialog.Builder(this)
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton(
                        "OK"
                    ) { _, _ ->
                        //Prompt the user once explanation has been shown
                        ActivityCompat.requestPermissions(
                            this@MapsActivity,
                            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                            MY_PERMISSIONS_REQUEST_LOCATION
                        )
                    }
                    .create()
                    .show()

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    MY_PERMISSIONS_REQUEST_LOCATION
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            MY_PERMISSIONS_REQUEST_LOCATION -> {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {

                        mFusedLocationClient?.requestLocationUpdates(
                            mLocationRequest,
                            mLocationCallback,
                            Looper.myLooper()
                        )
                        mGoogleMap.setMyLocationEnabled(true)
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
                }
                return
            }
        }// other 'case' lines to check for other
        // permissions this app might request
    }

    companion object {
        val MY_PERMISSIONS_REQUEST_LOCATION = 99
    }
}
</code>```

Java

Here is the full Activity class in Java:

```<code>public class MapsActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        getSupportActionBar().setTitle("Map Location Activity");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(120000); // two minute interval
        mLocationRequest.setFastestInterval(120000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            List<Location> locationList = locationResult.getLocations();
            if (locationList.size() > 0) {
                //The last location in the list is the newest
                Location location = locationList.get(locationList.size() - 1);
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }

                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
            }
        }
    };

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}
</code>```

activity_maps.xml:

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

    <fragment android:id="@+id/map"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".map.MapsActivity"
              app:layout_constraintTop_toTopOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              android:name="com.google.android.gms.maps.SupportMapFragment"/>

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

The user will be prompted to accept the Location permission:

The location will be updated on app launch, and every two minutes:

Extra note regarding AndroidX

If you are using AndroidX, you might need to add these lines to your gradle.properties file (see here for more info):

```<code>android.useAndroidX=true
android.enableJetifier=true
</code>```

Body:
I want to get periodic (say every 2 minutes) current location updates for this I'm following official documentation, I wrote this code but its not giving current location updates every two minutes even specified in LocationRequest object that I'm passing in requestLocationUpdates(), here is code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map =
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}

@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude())
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}

Body:
This is similar to my other answer here, updated to use the recently introduced FusedLocationProviderClient class.

In order to use a FusedLocationProviderClient in conjunction with a Google Map:

Wait until the Google Map is ready

Request the Location permission at runtime if needed

Request location updates once the permission is granted

Update the Google Map once the user's location is obtained

First ensure that you're using at least version 11 of Google Play Services, as older versions don't have the FusedLocationProviderClient class (newer versions will work as well):

dependencies {
      implementation 'com.google.android.gms:play-services-maps:17.0.0'
      implementation 'com.google.android.gms:play-services-location:17.0.0'
    //........
}

Note that the FusedLocationProviderClient is present in version 11.0.2, but due to bugs in the initial implementation, it's recommended that you only use this class on 11.6.0 and later.
From the documentation:

Note: It's recommended to use Google Play services version 11.6.0 or
  higher, which includes bug fixes for this class.

Add the location permissions in the AndroidManifest.xml file, inside the manifest tag and outside of the application tag:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Add the API key to the AndroidManifest.xml inside the application tag:

    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza___YOUR_KEY_HERE______"/>

Kotlin

Here is the full Activity class in Kotlin:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    lateinit var mGoogleMap: GoogleMap
    var mapFrag: SupportMapFragment? = null
    lateinit var mLocationRequest: LocationRequest
    var mLastLocation: Location? = null
    internal var mCurrLocationMarker: Marker? = null
    internal var mFusedLocationClient: FusedLocationProviderClient? = null

    internal var mLocationCallback: LocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            val locationList = locationResult.locations
            if (locationList.isNotEmpty()) {
                //The last location in the list is the newest
                val location = locationList.last()
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude())
                mLastLocation = location
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker?.remove()
                }

                //Place current location marker
                val latLng = LatLng(location.latitude, location.longitude)
                val markerOptions = MarkerOptions()
                markerOptions.position(latLng)
                markerOptions.title("Current Position")
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions)

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11.0F))
            }
        }
    }

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

        supportActionBar?.title = "Map Location Activity"

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        mapFrag = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFrag?.getMapAsync(this)
    }

    public override fun onPause() {
        super.onPause()

        //stop location updates when Activity is no longer active
        mFusedLocationClient?.removeLocationUpdates(mLocationCallback)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mGoogleMap = googleMap
        mGoogleMap.mapType = GoogleMap.MAP_TYPE_HYBRID

        mLocationRequest = LocationRequest()
        mLocationRequest.interval = 120000 // two minute interval
        mLocationRequest.fastestInterval = 120000
        mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                //Location Permission already granted
                mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
                mGoogleMap.isMyLocationEnabled = true
            } else {
                //Request Location Permission
                checkLocationPermission()
            }
        } else {
            mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
            mGoogleMap.isMyLocationEnabled = true
        }
    }

    private fun checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            ) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                AlertDialog.Builder(this)
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton(
                        "OK"
                    ) { _, _ ->
                        //Prompt the user once explanation has been shown
                        ActivityCompat.requestPermissions(
                            this@MapsActivity,
                            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                            MY_PERMISSIONS_REQUEST_LOCATION
                        )
                    }
                    .create()
                    .show()

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    MY_PERMISSIONS_REQUEST_LOCATION
                )
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            MY_PERMISSIONS_REQUEST_LOCATION -> {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(
                            this,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {

                        mFusedLocationClient?.requestLocationUpdates(
                            mLocationRequest,
                            mLocationCallback,
                            Looper.myLooper()
                        )
                        mGoogleMap.setMyLocationEnabled(true)
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
                }
                return
            }
        }// other 'case' lines to check for other
        // permissions this app might request
    }

    companion object {
        val MY_PERMISSIONS_REQUEST_LOCATION = 99
    }
}

Java

Here is the full Activity class in Java:

public class MapsActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        getSupportActionBar().setTitle("Map Location Activity");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mFusedLocationClient != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(120000); // two minute interval
        mLocationRequest.setFastestInterval(120000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            List<Location> locationList = locationResult.getLocations();
            if (locationList.size() > 0) {
                //The last location in the list is the newest
                Location location = locationList.get(locationList.size() - 1);
                Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }

                //Place current location marker
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

                //move map camera
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
            }
        }
    };

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

activity_maps.xml:

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

    <fragment android:id="@+id/map"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".map.MapsActivity"
              app:layout_constraintTop_toTopOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              android:name="com.google.android.gms.maps.SupportMapFragment"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The user will be prompted to accept the Location permission:

The location will be updated on app launch, and every two minutes:

Extra note regarding AndroidX

If you are using AndroidX, you might need to add these lines to your gradle.properties file (see here for more info):

android.useAndroidX=true
android.enableJetifier=true


来源: stackexchange

问:
create Menu and Sub menu recursively in Extjs
Is there way i can create Menu and Submenu recursivesly like tree node creation in Treepanel Extjs

Say i have empty menu items

I read xml input for constructing a Menu and Submenu

my xml look like

```<code><r>
<sub>
 <sub1>
  <sub 1.1/>
  <sub 1.1.1/>
</sub1>
<sub2/>
<sub3>
<sub 3.1>
<sub 3.1.1>
</sub3>
</r>
</code>```

xml may go any depth ,please provide suggestion

答:
```<code>buildHelpMenuItems: function () {

                var menuItemNodes = Ext.DomQuery.jsSelect('SUB', me.responseXML),
                mb = (toolbarHlpMenu) ? toolbarHlpMenu.menu : '',
                menu,
                menuArray = [];
                newMenuArray = [];
                if(menuItemNodes.length ==0 || !mb)
                    return;
                function buildMenuItem(node, scope) {
                    var menuitem = {};
                    menuitem.text = (node.attributes.getNamedItem('LABEL')) ? node.attributes.getNamedItem('LABEL').nodeValue : '';
                    menuitem.iconCls = (node.attributes.getNamedItem('clsName')) ? node.attributes.getNamedItem('clsName').nodeValue : '';
                    menuitem.url = (node.attributes.getNamedItem('URL')) ? node.attributes.getNamedItem('URL').nodeValue : '';
                    menuitem.handler = scope.helpMenuHandler;
                    menuitem.hidden = (node.attributes.getNamedItem('HIDDEN')) ? eval(node.attributes.getNamedItem('HIDDEN').nodeValue) : false;
                    menuitem.type = (node.attributes.getNamedItem('TYPE')) ? node.attributes.getNamedItem('TYPE').nodeValue : '';
                    return menuitem;
                }
                for (var i = 0; i < menuItemNodes.length; i++) {
                    var node = menuItemNodes[i];
                    menuItem = buildMenuItem(node,me);
                    if (!Ext.isEmpty(node.parentNode.getAttribute('LABEL'))) {
                        menuItem.parentEl = node.parentNode.getAttribute('LABEL');
                    } else {
                        menuItem.parentEl = "";
                    }
                    menuArray.push(menuItem);
                }
                for (var i = 0; i < menuArray.length; i++) {
                    var menuItem = menuArray[i];
                    if (menuItem.parentEl == "") {
                        newMenuArray.push(menuItem);
                    } else {
                        var parentEl = Ext.Array.findBy(menuArray, function (item) {
                                return (item.text == menuItem.parentEl);
                            });
                        if (Ext.isEmpty(parentEl.menu)) {
                            parentEl.menu = [];
                            parentEl.menu.push(menuItem);
                        } else {
                            parentEl.menu.push(menuItem);
                        }
                    }
                }
                mb.add(newMenuArray);

        },
</code>```

this Code tested in Extjs 4.2

ContentLicense: CC BY-SA 3.0

Body:
Is there way i can create Menu and Submenu recursivesly like tree node creation in Treepanel Extjs

Say i have empty menu items

I read xml input for constructing a Menu and Submenu

my xml look like

<r>

 <sub1>

</sub1>
<sub2/>
<sub3>

</sub3>
</r>

xml may go any depth ,please provide suggestion

Body:
buildHelpMenuItems: function () {

                var menuItemNodes = Ext.DomQuery.jsSelect('SUB', me.responseXML),
                mb = (toolbarHlpMenu) ? toolbarHlpMenu.menu : '',
                menu,
                menuArray = [];
                newMenuArray = [];
                if(menuItemNodes.length ==0 || !mb)
                    return;
                function buildMenuItem(node, scope) {
                    var menuitem = {};
                    menuitem.text = (node.attributes.getNamedItem('LABEL')) ? node.attributes.getNamedItem('LABEL').nodeValue : '';
                    menuitem.iconCls = (node.attributes.getNamedItem('clsName')) ? node.attributes.getNamedItem('clsName').nodeValue : '';
                    menuitem.url = (node.attributes.getNamedItem('URL')) ? node.attributes.getNamedItem('URL').nodeValue : '';
                    menuitem.handler = scope.helpMenuHandler;
                    menuitem.hidden = (node.attributes.getNamedItem('HIDDEN')) ? eval(node.attributes.getNamedItem('HIDDEN').nodeValue) : false;
                    menuitem.type = (node.attributes.getNamedItem('TYPE')) ? node.attributes.getNamedItem('TYPE').nodeValue : '';
                    return menuitem;
                }
                for (var i = 0; i < menuItemNodes.length; i++) {
                    var node = menuItemNodes[i];
                    menuItem = buildMenuItem(node,me);
                    if (!Ext.isEmpty(node.parentNode.getAttribute('LABEL'))) {
                        menuItem.parentEl = node.parentNode.getAttribute('LABEL');
                    } else {
                        menuItem.parentEl = "";
                    }
                    menuArray.push(menuItem);
                }
                for (var i = 0; i < menuArray.length; i++) {
                    var menuItem = menuArray[i];
                    if (menuItem.parentEl == "") {
                        newMenuArray.push(menuItem);
                    } else {
                        var parentEl = Ext.Array.findBy(menuArray, function (item) {
                                return (item.text == menuItem.parentEl);
                            });
                        if (Ext.isEmpty(parentEl.menu)) {
                            parentEl.menu = [];
                            parentEl.menu.push(menuItem);
                        } else {
                            parentEl.menu.push(menuItem);
                        }
                    }
                }
                mb.add(newMenuArray);

        },

this Code tested in Extjs 4.2


问:
Angular 2 Chrome DOM rendering problems
Our team (not only my computer) has a wierd rendering issue for Angular 2, that only happens in Chrome.

Namely, when navigating the app or refreshing in mid app, many of the items in DOM are invisible. EG. paragraphs and headers that have text in them, but the text is not rendered for the end user, but the text is seen in the inspector DOM.

The DOM will regain visibility if you edit a random CSS attribute in the inspector. This CSS doesnt even have to be applicable to the invisible DOM item at hand, ala. the invisible item could be a paragraph in the header, and switching a random footer span-s top position on/off will make the header paragraph regain visibility.

Before toggling a random CSS element

After toggling a random CSS element

This happens on pages that have a fixed loader applied to them, eg. a component that has position fixed, a superhigh z-index and encompasses the whole screen. This page loader is displayed until ngOnInit finishes, meaning it is pretty fast most of the time. Disabling this loader seems to fix the issue.

This also sometimes happens to text in {{ var }} tags, when the var value is loaded after the page has loaded.

We have tried toggling the loader with either

```<code>*ngIf="true/false"
</code>```

OR

```<code>[style.display]="block/none"
</code>```

Neither of these solutions work, some of the dom is still invisible.

Does anyone have a clue as to why this happens?

答: The issue is multiple inclusion in google chrome, I face similar issue when using angular4 and material lite.The problem is i imported fonts in every component and fixed it by importing font in single main parent component.</p>

Title: Angular 2 Chrome DOM rendering problems

Body:
Our team (not only my computer) has a wierd rendering issue for Angular 2, that only happens in Chrome.

Namely, when navigating the app or refreshing in mid app, many of the items in DOM are invisible. EG. paragraphs and headers that have text in them, but the text is not rendered for the end user, but the text is seen in the inspector DOM.

The DOM will regain visibility if you edit a random CSS attribute in the inspector. This CSS doesnt even have to be applicable to the invisible DOM item at hand, ala. the invisible item could be a paragraph in the header, and switching a random footer span-s top position on/off will make the header paragraph regain visibility.

Before toggling a random CSS element

After toggling a random CSS element

This happens on pages that have a fixed loader applied to them, eg. a component that has position fixed, a superhigh z-index and encompasses the whole screen. This page loader is displayed until ngOnInit finishes, meaning it is pretty fast most of the time. Disabling this loader seems to fix the issue.

This also sometimes happens to text in {{ var }} tags, when the var value is loaded after the page has loaded.

We have tried toggling the loader with either

*ngIf="true/false"

OR

[style.display]="block/none"

Neither of these solutions work, some of the dom is still invisible.

Does anyone have a clue as to why this happens?


问:
Single-page display, multi-page print problem
A web page displays the following:-

Bob

Fred

John

However when the user (that would be me) prints the web page I want multiple repeats of this output with slight variations to be printed on separate pages :-

Bob

Fred

John

>page break here<

Bob

Fred

John

>page break here<

Bob

Fred

John

In reality the page content is larger (although well within a standard A4 page worth) and the number of output pages is about 20.  I'd prefer an elegant cross-browser solution but ultimately a solution that works on Internet Explorer 7 is acceptable.

I'm using ASP.NET MVC with jQuery (although a straight JavaScript solution is fine).

Edit:  Page-Break-XXX css style is going be part of the answer, but I'm particularly interested in a means to dynamically create the print version HTML from the screen version.  Note I don't want to navigate to a 'printer friendly' page and then print that.  I just want to hit the browsers print button and magic happens.

答:
I'm not sure you can do it all via CSS, but here's some to get you started.

To get a page break in CSS when printing use one of:

page-break-before

page-break-after

These take values of:

```<code>auto   // Default. Insert a page break before/after the element if necessary
always // Insert a page break before/after the element
avoid  // Avoid inserting a page break before/after the element
left   // Insert page breaks before/after the element until it reaches a blank left page
right  // Insert page breaks before/after the element until it reaches a blank right page
</code>```

If you're prepared to have some sort of "Print" page that lists the information as you want, with those styles on the repeated elements, you should be good to go.

OwnerDisplayName: AnthonyWJones

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: AnthonyWJones

Body:
I'm not sure you can do it all via CSS, but here's some to get you started.

To get a page break in CSS when printing use one of:

page-break-before

page-break-after

These take values of:

auto   // Default. Insert a page break before/after the element if necessary
always // Insert a page break before/after the element
avoid  // Avoid inserting a page break before/after the element
left   // Insert page breaks before/after the element until it reaches a blank left page
right  // Insert page breaks before/after the element until it reaches a blank right page

If you're prepared to have some sort of "Print" page that lists the information as you want, with those styles on the repeated elements, you should be good to go.

OwnerDisplayName: Zhaph

LastEditorDisplayName: Zhaph


问:
Angular 2 - how to fill a local variable with JSON data from an external file
The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.

```<code>import {Component} from 'angular2/core';
import {Foo} from './foo';

@Component({
   etc.
});

export class AppComponent {
   bar = BAR;
}

var BAR: Foo[] = [
   { 'id': 1 },
   { 'id': 2 }
];
</code>```

However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?

答:
Best option is to create json file and store json details inside file and call that file using like below.

If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

```<code>return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}
</code>```

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.

Body:
The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.

import {Component} from 'angular2/core';
import {Foo} from './foo';

@Component({
   etc.
});

export class AppComponent {
   bar = BAR;
}

var BAR: Foo[] = [
   { 'id': 1 },
   { 'id': 2 }
];

However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?

Body:
Best option is to create json file and store json details inside file and call that file using like below.

If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.


问:
I am getting Error saying "TypeError: callback is not a function"
Here is my code, I am getting Error saying "callback is undefined" and I am so confused that even though I have sent function as parameter to Search function it is considering it as an undefined.

```<code>    class Tree{
    constructor(){
        this.data;
        this.left;
        this.right;
    }
    Insert(data)
    {
       if(this.data)
       {
         if(this.data<data)
         {
             if(this.right)
             {
               this.right.Insert(data)
             }
             else{
                 this.right=new Tree();
                 this.right.Insert(data)
             }
         }
         else{
              if(this.left)
             {
               this.left.Insert(data)
             }
             else{
                 this.left=new Tree();
                 this.left.Insert(data)
             }
         }
       }
       else{
           this.data=data;
       }
    }
    Display(){
        if(this.left)
        {

            this.left.Display();
        }
        console.log(this.data);
        if(this.right)
        {
            this.right.Display();
        }
    }
    Search(data,callback){

        if(data==this.data)
        {
            console.log("found")
            callback("found")
        }
        else if(data>this.data)
        {
            if(this.right)
            {
                this.right.Search(data);
            }
            else callback("not found")
        }
        else if(data<this.data){
            if(this.left)
            {
                this.left.Search(data);
            }
            else callback("not found")
        }
    }
}

var k =new Tree();
k.Insert(41);
k.Insert(34);
k.Insert(53);
k.Insert(384);
k.Search(34,function (res){
  console.log(res)
});
</code>```

Could you guys help me on this? Many thanks in advance

答:
In this part

```<code>else if(data>this.data)
    {
        if(this.right)
        {
            this.right.Search(data);
        }
</code>```

You don't send the call back, You should send the callback every time you call it.

Solution

```<code>else if(data>this.data)
    {
        if(this.right)
        {
            this.right.Search(data, callback);
        }
</code>```

Body:
Here is my code, I am getting Error saying "callback is undefined" and I am so confused that even though I have sent function as parameter to Search function it is considering it as an undefined.

    class Tree{
    constructor(){
        this.data;
        this.left;
        this.right;
    }
    Insert(data)
    {
       if(this.data)
       {
         if(this.data<data)
         {
             if(this.right)
             {
               this.right.Insert(data)
             }
             else{
                 this.right=new Tree();
                 this.right.Insert(data)
             }
         }
         else{
              if(this.left)
             {
               this.left.Insert(data)
             }
             else{
                 this.left=new Tree();
                 this.left.Insert(data)
             }
         }
       }
       else{
           this.data=data;
       }
    }
    Display(){
        if(this.left)
        {

            this.left.Display();
        }
        console.log(this.data);
        if(this.right)
        {
            this.right.Display();
        }
    }
    Search(data,callback){

        if(data==this.data)
        {
            console.log("found")
            callback("found")
        }
        else if(data>this.data)
        {
            if(this.right)
            {
                this.right.Search(data);
            }
            else callback("not found")
        }
        else if(data<this.data){
            if(this.left)
            {
                this.left.Search(data);
            }
            else callback("not found")
        }
    }
}

var k =new Tree();
k.Insert(41);
k.Insert(34);
k.Insert(53);
k.Insert(384);
k.Search(34,function (res){
  console.log(res)
});

Could you guys help me on this? Many thanks in advance

Body:
In this part

else if(data>this.data)
    {
        if(this.right)
        {
            this.right.Search(data);
        }

You don't send the call back, You should send the callback every time you call it.

Solution

else if(data>this.data)
    {
        if(this.right)
        {
            this.right.Search(data, callback);
        }


问:
sys_id arrays to is one of not displaying records
I am creating one report. In report condition I am using 'is one of' and passing sys_id array by calling client callable script include  javascript: new GetMoreInfoUpdatedChangeTickets().getSysIds();as. I can see sys_ids as "Data source conditions:Sys ID in 60a219744fc73200d6940e428110c72b". But corresponding record is not getting displayed. But corresponding sys_id record is available.</p>

答:
I think I see the issue here. Unfortunately, that is not how client-callable script includes typically work. Script includes, even client-callable ones, ALWAYS execute on the server. They are meant to be called via an asynchronous GlideAjax call from a client-side script.

For more information on this, I encourage you to have a look at this article on GlideAjax.

However, luckily for you, your actual query executes on the server, not the client. So a Script Include is probably the right way to go, but the problem you're facing is (probably) that by making it a GlideAjax script include, you're telling ServiceNow to override the constructor (initialize()) method, but leave it as a Class.

Since you say you're getting a sys_id returned, it's possible that what I described isn't the issue, and this solution won't work. However, I don't have enough information to give any other answer; so if that's the case, please run the query that isn't showing you the correct results, then right-click on the last query breadcrumb at the top of the list, and click "Copy Query", then paste the query in a reply on this thread (replying specifically to my comment so I get notified) so I can have a look.

Please also obviously provide the code in your script include so I can help you troubleshoot.

EDIT:
Now what you've added your code in a reply to this comment, I can see several issues.

Your original:

```<code>var GetMoreInfoUpdatedChangeTickets = Class.create();
GetMoreInfoUpdatedChangeTickets.prototype = {
    initialize:   function() {
    }, getSysIds: function getMyGroupMembers() {
        var ga = new GlideRecord('sysapproval_group');
        ga.addQuery('parent.sys_class_name', '=', 'change_request');
        ga.query();
        gs.log("TotalRecords1 Before:: " + ga.getRowCount());
        var sysIdArray = [];
        while (ga.next()) {
            sysIdArray.push(ga.sys_id);
        }
        return sysIdArray;
    }, type:      'GetMoreInfoUpdatedChangeTickets'
}
</code>```

Here are all of the changes I made to your code, and an explanation for each:

First, on line 5 in the code below, I've changed how your member function (aka: "method") is declared. You had it declared like so:
getSysIds: function getMyGroupMembers() {}
So here, you've essentially given it two names and declared it in two ways at once.
Normally, a function is declared like this:
function functionName(args) {}
However, inside of an object (or in this case, a Class - which is an object with a constructor that returns copies of itself using the "new" keyword) we declare functions like this:
functionName: function(args) {},
So as you can see in the code below, I've made that adjustment for you.

Next, on line 8 below, I've removed the redundant '=' operator from your addQuery() method call, as "=" is implied when not specified. This isn't required, but it looks cleaner this way.
(I've also renamed your GlideRecord variable from ga to grApprovalGroup throughout, so that it makes more sense.)

I've moved the declaration of sysIdArray to the top of the function for consistency with how it's executed (and for clarity). This is also not required, but is generally recommended.

Line 12 below, in your original code, looked like this:
sysIdArray.push(grApprovalGroup.sys_id);
However, since gr.sys_id is an object (type: "GlideElement" - documentation here), this is pushing a reference to that object into the array. As the string value property of that object (the one at location gr.sys_id changes, so does the string value property of each and every element in the array, since every single element is a reference to the same object! More information on this, in an article (which I wrote) that you can find here.
Suffice it to say that this is not a good idea, and will result in a list of the same sys_id over and over! To fix this, we simply use the best-practice recommended "getter" method (as the article I linked recommends), as you can see on line 12 in the code below.

```<code>var GetMoreInfoUpdatedChangeTickets = Class.create();
GetMoreInfoUpdatedChangeTickets.prototype = {
    initialize: function() {
    },
    getSysIds:  function() {
        var sysIdArray = [];
        var grApprovalGroup = new GlideRecord('sysapproval_group');
        grApprovalGroup.addQuery('parent.sys_class_name', 'change_request');
        grApprovalGroup.query();

        while (grApprovalGroup.next()) {
            sysIdArray.push(grApprovalGroup.getValue('sys_id'));
        }
        return sysIdArray;
    },
    type:       'GetMoreInfoUpdatedChangeTickets'
};
</code>```

Finally, we need to actually extract the function from the class and rename it so the script include itself is just the function.

```<code>function GetMoreInfoUpdatedChangeTickets() {
    var sysIdArray = [];
    var grApprovalGroup = new GlideRecord('sysapproval_group');
    grApprovalGroup.addQuery('parent.sys_class_name', 'change_request');
    grApprovalGroup.query();

    while (grApprovalGroup.next()) {
        sysIdArray.push(grApprovalGroup.getValue('sys_id'));
    }
    return sysIdArray;
}
</code>```

Since you can't use the "new" keyword in query javascript, it's necessary to define it like this (without the class), and once we've done that we can re-enable the "client callable" option you had enabled previously.

Once you've done that, you should be able to go to the following URL, and see your query script in action:

https://YOUR_INSTANCE.service-now.com/sysapproval_group_list.do?sysparm_query=sys_id%3Djavascript%3A%20GetMoreInfoUpdatedChangeTickets()%3B

Body:
I think I see the issue here. Unfortunately, that is not how client-callable script includes typically work. Script includes, even client-callable ones, ALWAYS execute on the server. They are meant to be called via an asynchronous GlideAjax call from a client-side script.

For more information on this, I encourage you to have a look at this article on GlideAjax.

However, luckily for you, your actual query executes on the server, not the client. So a Script Include is probably the right way to go, but the problem you're facing is (probably) that by making it a GlideAjax script include, you're telling ServiceNow to override the constructor (initialize()) method, but leave it as a Class.

Since you say you're getting a sys_id returned, it's possible that what I described isn't the issue, and this solution won't work. However, I don't have enough information to give any other answer; so if that's the case, please run the query that isn't showing you the correct results, then right-click on the last query breadcrumb at the top of the list, and click "Copy Query", then paste the query in a reply on this thread (replying specifically to my comment so I get notified) so I can have a look.

Please also obviously provide the code in your script include so I can help you troubleshoot.

EDIT:
Now what you've added your code in a reply to this comment, I can see several issues.

Your original:

var GetMoreInfoUpdatedChangeTickets = Class.create();
GetMoreInfoUpdatedChangeTickets.prototype = {
    initialize:   function() {
    }, getSysIds: function getMyGroupMembers() {
        var ga = new GlideRecord('sysapproval_group');
        ga.addQuery('parent.sys_class_name', '=', 'change_request');
        ga.query();
        gs.log("TotalRecords1 Before:: " + ga.getRowCount());
        var sysIdArray = [];
        while (ga.next()) {
            sysIdArray.push(ga.sys_id);
        }
        return sysIdArray;
    }, type:      'GetMoreInfoUpdatedChangeTickets'
}

Here are all of the changes I made to your code, and an explanation for each:

First, on line 5 in the code below, I've changed how your member function (aka: "method") is declared. You had it declared like so:
getSysIds: function getMyGroupMembers() {}
So here, you've essentially given it two names and declared it in two ways at once.
Normally, a function is declared like this:
function functionName(args) {}
However, inside of an object (or in this case, a Class - which is an object with a constructor that returns copies of itself using the "new" keyword) we declare functions like this:
functionName: function(args) {},
So as you can see in the code below, I've made that adjustment for you.

Next, on line 8 below, I've removed the redundant '=' operator from your addQuery() method call, as "=" is implied when not specified. This isn't required, but it looks cleaner this way.
(I've also renamed your GlideRecord variable from ga to grApprovalGroup throughout, so that it makes more sense.)

I've moved the declaration of sysIdArray to the top of the function for consistency with how it's executed (and for clarity). This is also not required, but is generally recommended.

Line 12 below, in your original code, looked like this:
sysIdArray.push(grApprovalGroup.sys_id);
However, since gr.sys_id is an object (type: "GlideElement" - documentation here), this is pushing a reference to that object into the array. As the string value property of that object (the one at location gr.sys_id changes, so does the string value property of each and every element in the array, since every single element is a reference to the same object! More information on this, in an article (which I wrote) that you can find here.
Suffice it to say that this is not a good idea, and will result in a list of the same sys_id over and over! To fix this, we simply use the best-practice recommended "getter" method (as the article I linked recommends), as you can see on line 12 in the code below.

var GetMoreInfoUpdatedChangeTickets = Class.create();
GetMoreInfoUpdatedChangeTickets.prototype = {
    initialize: function() {
    },
    getSysIds:  function() {
        var sysIdArray = [];
        var grApprovalGroup = new GlideRecord('sysapproval_group');
        grApprovalGroup.addQuery('parent.sys_class_name', 'change_request');
        grApprovalGroup.query();

        while (grApprovalGroup.next()) {
            sysIdArray.push(grApprovalGroup.getValue('sys_id'));
        }
        return sysIdArray;
    },
    type:       'GetMoreInfoUpdatedChangeTickets'
};

Finally, we need to actually extract the function from the class and rename it so the script include itself is just the function.

function GetMoreInfoUpdatedChangeTickets() {
    var sysIdArray = [];
    var grApprovalGroup = new GlideRecord('sysapproval_group');
    grApprovalGroup.addQuery('parent.sys_class_name', 'change_request');
    grApprovalGroup.query();

    while (grApprovalGroup.next()) {
        sysIdArray.push(grApprovalGroup.getValue('sys_id'));
    }
    return sysIdArray;
}

Since you can't use the "new" keyword in query javascript, it's necessary to define it like this (without the class), and once we've done that we can re-enable the "client callable" option you had enabled previously.

Once you've done that, you should be able to go to the following URL, and see your query script in action:

https://YOUR_INSTANCE.service-now.com/sysapproval_group_list.do?sysparm_query=sys_id%3Djavascript%3A%20GetMoreInfoUpdatedChangeTickets()%3B


问:
ADF Architecture
we need to develop a web application using Oracle ADF and jdeveloper 12c. we have 10 modules. Which architecture pattern is best approach in the below 2 patterns.
1. Sum of Parts.
2. Cylinder .
Or is there any other patterns for Production Project.</p>

答:
I work 3 years on ADF framework (11.1.1.7 - 11.1.1.9) and familiar with 12c; There have been a lot of changes that make work easier than before!

I suggest develop modular system and use every module in a base application (present last view to end user), this help you to keep agile development; You can easy test, debug, trace, and update project without trouble! (We hurt this issue, a single big app)

this your choice, every module been an application, or all module been under a unified App, BUT KEEP AWAY TO MERGE ALL OF THEME TO AN APP!!!

Title: ADF Architecture


问:
Bash script assistance with find
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

```<code>#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"
</code>```

.gitrepos generated file:

```<code>./codeigniter/.git
./magento/.git
./magento2/.git
</code>```

My problem:

```<code>gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'
</code>```

答:
Problem is that you've already changed directory to first repo i.e. codeigniter using cd in your while loop. After that your script is not going back to parent directory using cd - at the end.

You can even avoid temporary file creation by using process substitution:

```<code>while IFS= read -d '' -r line; do
  cd "$line"/..
  git pull --all

  while read -r branch; do
     git branch --track "${branch##*/}" "$branch"
  done < <(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$')

  cd -
done < <(find . -maxdepth 2 -name .git -type d -print0)
</code>```

Title: Bash script assistance with find

Body:
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"

.gitrepos generated file:

./codeigniter/.git
./magento/.git
./magento2/.git

My problem:

gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'

Body:
Problem is that you've already changed directory to first repo i.e. codeigniter using cd in your while loop. After that your script is not going back to parent directory using cd - at the end.

You can even avoid temporary file creation by using process substitution:

while IFS= read -d '' -r line; do
  cd "$line"/..
  git pull --all

  while read -r branch; do
     git branch --track "${branch##*/}" "$branch"
  done < <(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$')

  cd -
done < <(find . -maxdepth 2 -name .git -type d -print0)


问:
PHP Header Redirect in a new window?
For a banner management system i use a

```<code> header("Location: http://www.awebsite.com");
</code>```

to redirect to the proper website. Is it possible to force this header script to open in a new window?

答:
You should redirect to a page with a redirect metà tag like the one on the most voted answer at Open HTML meta redirect in new window

So the page you redirect your headers to will contain a metà tag with:

```<code><meta http-equiv="refresh" />
<meta content="0; URL=javascript:window.open('http://uri.of
.your.pagewhereyouwabtoredirect/path','_parent');"/>
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP Header Redirect in a new window?

Body:
For a banner management system i use a

 header("Location: http://www.awebsite.com");

to redirect to the proper website. Is it possible to force this header script to open in a new window?

Body:
You should redirect to a page with a redirect metà tag like the one on the most voted answer at Open HTML meta redirect in new window

So the page you redirect your headers to will contain a metà tag with:

<meta http-equiv="refresh" />
<meta content="0; URL=javascript:window.open('http://uri.of
.your.pagewhereyouwabtoredirect/path','_parent');"/>


答:
As a workaround, try the same find command, but with absolute paths:

```<code>find $(pwd) -maxdepth 2 -name .git -type d -print > .gitrepos
</code>```

That way, cd will access those folder through their full and complete path.

Even if your first cd changed the current path, it won't maater.

Title: Bash script assistance with find

Body:
As a workaround, try the same find command, but with absolute paths:

find $(pwd) -maxdepth 2 -name .git -type d -print > .gitrepos

That way, cd will access those folder through their full and complete path.

Even if your first cd changed the current path, it won't maater.


问:
String to Double in Java
I have in my Java app double numbers. I need to convert String to Double, but string representation of number is

, - separates decimal part of number (
  example    1,5  eq 6/4 )

. - separates groups of three digits (
  example  1.000.000  eq 1000000 )

.
How to achieve this conversion String to Double ?

答:
Here is one way of solving it using DecimalFormat without worrying about locales.

```<code>import java.text.*;

public class Test {

    public static void main(String[] args) throws ParseException {

        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setGroupingSeparator('.');
        dfs.setDecimalSeparator(',');

        DecimalFormat df = new DecimalFormat();
        df.setGroupingSize(3);

        String[] tests = { "15,151.11", "-7,21.3", "8.8" };
        for (String test : tests)
            System.out.printf("\"%s\" -> %f%n", test, df.parseObject(test));
    }
}
</code>```

Output:

```<code>"15,151.11" -> 15151.110000
"-7,21.3" -> -721.300000
"8.8" -> 8.800000
</code>```

Title: String to Double in Java

Body:
Here is one way of solving it using DecimalFormat without worrying about locales.

import java.text.*;

public class Test {

    public static void main(String[] args) throws ParseException {

        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setGroupingSeparator('.');
        dfs.setDecimalSeparator(',');

        DecimalFormat df = new DecimalFormat();
        df.setGroupingSize(3);

        String[] tests = { "15,151.11", "-7,21.3", "8.8" };
        for (String test : tests)
            System.out.printf("\"%s\" -> %f%n", test, df.parseObject(test));
    }
}

Output:

"15,151.11" -> 15151.110000
"-7,21.3" -> -721.300000
"8.8" -> 8.800000


问:
Postgres could not connect to server
After I did brew update and brew upgrade, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well.

This is the error message. (I also got this error message when I try to do rake db:migrate)

$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
```
<p>How can I solve it?</p>
<p>Mac version: Mountain lion.</p>
<p>homebrew version: 0.9.3</p>
<p>postgres version: psql (PostgreSQL) 9.2.1</p>
<p>And this is what I did:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.2.1...
$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.1.4...
$ psql --version
bash: /usr/local/bin/psql: No such file or directory
$ brew install postgresql
==> Downloading http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Already downloaded: /Library/Caches/Homebrew/postgresql-9.2.1.tar.bz2
......
......
==> Summary
/usr/local/Cellar/postgresql/9.2.1: 2814 files, 38M, built in 2.7 minutes
$ initdb /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "laigary".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default text search configuration will be set to "english".

initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".
$ mkdir -p ~/Library/LaunchAgents
$ cp /usr/local/Cellar/postgresql/9.2.1/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
homebrew.mxcl.postgresql: Already loaded
$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
$ env ARCHFLAGS="-arch x86_64" gem install pg
Building native extensions.  This could take a while...
Successfully installed pg-0.14.1
1 gem installed
$ psql --version
psql (PostgreSQL) 9.2.1
$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?</code>```

Now, after I reinstalled homebrew, when I use $ psql, it doesn't show any error message.

But I run rake db:migrate in my Rails app, it shows:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `call'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:144:in `invoke'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:88:in `top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:66:in `block in run'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:63:in `run'
/usr/local/bin/rake:32:in `'
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"riy_development", "pool"=>5, "username"=>nil, "password"=>nil}```
</div>
</div>
</p>
<p><strong>Finally I've found a solution.</strong></p>
<pre class="lang-sh prettyprint-override"><code>sudo mkdir /var/pgsql_socket/
sudo ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/
</code>```

This solution is a little tricky, but it works. Hope anyone has a better solution

Update

This works for me as well.

rm /usr/local/var/postgres/postmaster.pid
```

答:
I used the Bitnami stack and installed as non-root user psql. On using psql I did receive the mentioned error.

Turns out, there are 2 versions of psql

a root level psql prepackaged in the linux distro. This points to /usr/bin/psql

a non-root level psql installed by the Bitnami stack. This points to /bitnami/postgresql/postgresql/bin/psql

You might want to change the alias of the psql, so that it points to the non-root user.

```<code>alias psql='/bitnami/postgresql/postgresql/bin/psql'
</code>```

The above worked for me on doing psql -U postgres

Title: Postgres could not connect to server

Body:
After I did brew update and brew upgrade, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well.

This is the error message. (I also got this error message when I try to do rake db:migrate)

$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

How can I solve it?

Mac version: Mountain lion.

homebrew version: 0.9.3

postgres version: psql (PostgreSQL) 9.2.1

And this is what I did:

$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.2.1...
$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.1.4...
$ psql --version
bash: /usr/local/bin/psql: No such file or directory
$ brew install postgresql
==> Downloading http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Already downloaded: /Library/Caches/Homebrew/postgresql-9.2.1.tar.bz2
......
......
==> Summary
/usr/local/Cellar/postgresql/9.2.1: 2814 files, 38M, built in 2.7 minutes
$ initdb /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "laigary".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default text search configuration will be set to "english".

initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".
$ mkdir -p ~/Library/LaunchAgents
$ cp /usr/local/Cellar/postgresql/9.2.1/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
homebrew.mxcl.postgresql: Already loaded
$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
$ env ARCHFLAGS="-arch x86_64" gem install pg
Building native extensions.  This could take a while...
Successfully installed pg-0.14.1
1 gem installed
$ psql --version
psql (PostgreSQL) 9.2.1
$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

Now, after I reinstalled homebrew, when I use $ psql, it doesn't show any error message.

But I run rake db:migrate in my Rails app, it shows:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `call'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:144:in `invoke'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:88:in `top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:66:in `block in run'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:63:in `run'
/usr/local/bin/rake:32:in `'
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"riy_development", "pool"=>5, "username"=>nil, "password"=>nil}

Finally I've found a solution.

sudo mkdir /var/pgsql_socket/
sudo ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/

This solution is a little tricky, but it works. Hope anyone has a better solution

Update

This works for me as well.

rm /usr/local/var/postgres/postmaster.pid

Body:
I used the Bitnami stack and installed as non-root user psql. On using psql I did receive the mentioned error.

Turns out, there are 2 versions of psql

a root level psql prepackaged in the linux distro. This points to /usr/bin/psql

a non-root level psql installed by the Bitnami stack. This points to /bitnami/postgresql/postgresql/bin/psql

You might want to change the alias of the psql, so that it points to the non-root user.

alias psql='/bitnami/postgresql/postgresql/bin/psql'

The above worked for me on doing psql -U postgres


问:
Android SwitchPreference not working
I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is.
Here's the code.

NotificationUtils.java

```<code>SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }
</code>```

preferences.xml

```<code><SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />
</code>```

I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.

答: I solved it, actually the value wasn't toggling, in settings screen the Switch was turning off and on but the value remained the default. Solved it by setting the new value in OnPreferenceChangeListener and that worked.</p>

Title: Android SwitchPreference not working

Body:
I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is.
Here's the code.

NotificationUtils.java

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }

preferences.xml

<SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />

I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.