问:
null pointer exception in Googlemap.moveCamera
I created a Google Map app to list nearby hotels. I followed the complete tutorial from this tutorial link

Now I'm getting a error like this

```<code>     E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.futuro.gplace, PID: 30974
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.futuro.gplace/com.example.futuro.gplace.MainActivity}: java.lang.NullPointerException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:141)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5336)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:873)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NullPointerException
                  at com.example.futuro.gplace.MainActivity.onLocationChanged(MainActivity.java:361)
                  at com.example.futuro.gplace.MainActivity.onCreate(MainActivity.java:123)
                  at android.app.Activity.performCreate(Activity.java:5302)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:141)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5336)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:873)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

my code is

```<code>public class MainActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback {

  GoogleMap mGoogleMap;
    Spinner mSprPlaceType;

    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;

    double mLatitude = 0;
    double mLongitude = 0;

    HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = (Button) findViewById(R.id.btn_find);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            fragment.getMapAsync(this);
            if (ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)                 // Enabling MyLocation in Google Map
                mGoogleMap.setMyLocationEnabled(true);

                // Getting LocationManager object from System Service LOCATION_SERVICE
                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);

            mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                @Override
                public void onInfoWindowClick(Marker arg0) {
                    Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                    String reference = mMarkerPlaceLink.get(arg0.getId());
                    intent.putExtra("reference", reference);

                    // Starting the Place Details Activity
                    startActivity(intent);
                }
            });

            // Setting click event lister for the find button
            btnFind.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                    String type = mPlaceType[selectedPosition];

                    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                    sb.append("location=" + mLatitude + "," + mLongitude);
                    sb.append("&radius=5000");
                    sb.append("&types=" + type);
                    sb.append("&sensor=true");
                    sb.append("AIzaSyAjd_-MyhsY0-Bbdb_wrYv507oG7D__ZGg");

                    // Creating a new non-ui thread task to download Google place json data
                    PlacesTask placesTask = new PlacesTask();

                    // Invokes the "doInBackground()" method of the class PlaceTask
                    placesTask.execute(sb.toString());
                }
            });
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exceptionl", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

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

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    /**
     * A class, to download Google Places
     */
    private class PlacesTask extends AsyncTask<String, Integer, String> {

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try {
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            // Clears all the existing markers
            mGoogleMap.clear();

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);

                // Linking Marker id and place reference
                mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));  /// error is shown in this line
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

}
</code>```

I'm new to this forum and android.

What does this is really mean? I solved all error with your help. Now I'm able to open the map and the map is showing my current location (not with the marker). When i click find nothig happens and this is my run window show

```<code>    W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/ActivityThread: com.example.futuro.gplace query other app provider, pkg:com.google.android.gms uid:10010, send to pg
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 29 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0012
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 28 (SUPPORTED_32_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0021
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 29 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0008
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001d at 0x17 in Lv;.a
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001c at 0x26 in Lv;.a
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001d at 0x0d in Lv;.b
I/dalvikvm: Could not find method b.createCredentialProtectedStorageContext, referenced from method c.createCredentialProtectedStorageContext
W/dalvikvm: VFY: unable to resolve virtual method 181: Lb;.createCredentialProtectedStorageContext ()Landroid/content/Context;
D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
I/dalvikvm: Could not find method b.createDeviceProtectedStorageContext, referenced from method c.createDeviceProtectedStorageContext
W/dalvikvm: VFY: unable to resolve virtual method 182: Lb;.createDeviceProtectedStorageContext ()Landroid/content/Context;
D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
I/ActivityThread: com.example.futuro.gplace query other app provider, pkg:com.google.android.gsf uid:10010, send to pg
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
D/dalvikvm: GC_FOR_ALLOC freed 7235K, 59% free 8106K/19316K, paused 77ms, total 78ms
</code>```

my Gradle file

```<code>    apply plugin: 'com.android.application'

    android {
     compileSdkVersion 25
         buildToolsVersion "25.0.2"
               defaultConfig {
                  applicationId "com.example.futuro.gplace"
               minSdkVersion 15
                targetSdkVersion 25
                 versionCode 1
                  versionName "1.0"
                    multiDexEnabled true
                  testInstrumentationRunner                                                "                        "android.support.test.runner.AndroidJUnitRunner"
                                }

                  buildTypes {
                         release {
                           minifyEnabled false
                                                                                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

               dependencies {
                     compile fileTree(include: ['*.jar'], dir: 'libs')
                            androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
              compile 'com.android.support:appcompat-v7:25.2.0'
                  testCompile 'junit:junit:4.12'

                compile 'com.google.android.gms:play-services-maps:10.2.1'
             compile 'com.google.android.gms:play-services-location:10.2.1'
          compile 'com.google.android.gms:play-services-places:10.2.1'
          compile 'com.google.firebase:firebase-appindexing:10.2.0'

           //  compile 'com.google.android.gms:play-services-appindexing:10.2.1'

           compile 'com.android.support:multidex:1.0.1'
                 }
             android {
                   aaptOptions.cruncherEnabled = false
                   aaptOptions.useNewCruncher = false

                 }
</code>```

Whenever I click the find button
it comes like this

```<code>   Manager: playSoundEffect   effectType: 0
   V/AudioManager: querySoundEffectsEnabled...
</code>```

is there any issue with this link to show my api enabled.

答:
Google map is initialized within the method
public void onMapReady(GoogleMap googleMap)

but as onLocationChanged(Location location) is a callback method from LocationListener, which might get called before the map is ready and initialized.

so i guess, a null check before moving the camera will solve the problem

```<code>@Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        if(mGoogleMap != null){
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));  /// error is shown in this line
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

    }
</code>```

Body:
I created a Google Map app to list nearby hotels. I followed the complete tutorial from this tutorial link

Now I'm getting a error like this

     E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.futuro.gplace, PID: 30974
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.futuro.gplace/com.example.futuro.gplace.MainActivity}: java.lang.NullPointerException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:141)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5336)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:873)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
                  at dalvik.system.NativeStart.main(Native Method)
               Caused by: java.lang.NullPointerException
                  at com.example.futuro.gplace.MainActivity.onLocationChanged(MainActivity.java:361)
                  at com.example.futuro.gplace.MainActivity.onCreate(MainActivity.java:123)
                  at android.app.Activity.performCreate(Activity.java:5302)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:141)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5336)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:873)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
                  at dalvik.system.NativeStart.main(Native Method)

my code is

public class MainActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback {

  GoogleMap mGoogleMap;
    Spinner mSprPlaceType;

    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;

    double mLatitude = 0;
    double mLongitude = 0;

    HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = (Button) findViewById(R.id.btn_find);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            fragment.getMapAsync(this);
            if (ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)                 // Enabling MyLocation in Google Map
                mGoogleMap.setMyLocationEnabled(true);

                // Getting LocationManager object from System Service LOCATION_SERVICE
                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location From GPS
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);

            mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                @Override
                public void onInfoWindowClick(Marker arg0) {
                    Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                    String reference = mMarkerPlaceLink.get(arg0.getId());
                    intent.putExtra("reference", reference);

                    // Starting the Place Details Activity
                    startActivity(intent);
                }
            });

            // Setting click event lister for the find button
            btnFind.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                    String type = mPlaceType[selectedPosition];

                    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                    sb.append("location=" + mLatitude + "," + mLongitude);
                    sb.append("&radius=5000");
                    sb.append("&types=" + type);
                    sb.append("&sensor=true");
                    sb.append("AIzaSyAjd_-MyhsY0-Bbdb_wrYv507oG7D__ZGg");

                    // Creating a new non-ui thread task to download Google place json data
                    PlacesTask placesTask = new PlacesTask();

                    // Invokes the "doInBackground()" method of the class PlaceTask
                    placesTask.execute(sb.toString());
                }
            });
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exceptionl", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

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

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    /**
     * A class, to download Google Places
     */
    private class PlacesTask extends AsyncTask<String, Integer, String> {

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try {
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            // Clears all the existing markers
            mGoogleMap.clear();

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);

                // Linking Marker id and place reference
                mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));  /// error is shown in this line
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

}

I'm new to this forum and android.

What does this is really mean? I solved all error with your help. Now I'm able to open the map and the map is showing my current location (not with the marker). When i click find nothig happens and this is my run window show

    W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/ActivityThread: com.example.futuro.gplace query other app provider, pkg:com.google.android.gms uid:10010, send to pg
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2
I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 29 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0012
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 28 (SUPPORTED_32_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0021
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
W/dalvikvm: VFY: unable to resolve static field 29 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build;
D/dalvikvm: VFY: replacing opcode 0x62 at 0x0008
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001d at 0x17 in Lv;.a
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001c at 0x26 in Lv;.a
D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS
I/dalvikvm: DexOpt: unable to optimize static field ref 0x001d at 0x0d in Lv;.b
I/dalvikvm: Could not find method b.createCredentialProtectedStorageContext, referenced from method c.createCredentialProtectedStorageContext
W/dalvikvm: VFY: unable to resolve virtual method 181: Lb;.createCredentialProtectedStorageContext ()Landroid/content/Context;
D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
I/dalvikvm: Could not find method b.createDeviceProtectedStorageContext, referenced from method c.createDeviceProtectedStorageContext
W/dalvikvm: VFY: unable to resolve virtual method 182: Lb;.createDeviceProtectedStorageContext ()Landroid/content/Context;
D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
I/ActivityThread: com.example.futuro.gplace query other app provider, pkg:com.google.android.gsf uid:10010, send to pg
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
D/dalvikvm: GC_FOR_ALLOC freed 7235K, 59% free 8106K/19316K, paused 77ms, total 78ms

my Gradle file

    apply plugin: 'com.android.application'

    android {
     compileSdkVersion 25
         buildToolsVersion "25.0.2"
               defaultConfig {
                  applicationId "com.example.futuro.gplace"
               minSdkVersion 15
                targetSdkVersion 25
                 versionCode 1
                  versionName "1.0"
                    multiDexEnabled true
                  testInstrumentationRunner                                                "                        "android.support.test.runner.AndroidJUnitRunner"
                                }

                  buildTypes {
                         release {
                           minifyEnabled false
                                                                                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

               dependencies {
                     compile fileTree(include: ['*.jar'], dir: 'libs')
                            androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
              compile 'com.android.support:appcompat-v7:25.2.0'
                  testCompile 'junit:junit:4.12'

                compile 'com.google.android.gms:play-services-maps:10.2.1'
             compile 'com.google.android.gms:play-services-location:10.2.1'
          compile 'com.google.android.gms:play-services-places:10.2.1'
          compile 'com.google.firebase:firebase-appindexing:10.2.0'

           //  compile 'com.google.android.gms:play-services-appindexing:10.2.1'

           compile 'com.android.support:multidex:1.0.1'
                 }
             android {
                   aaptOptions.cruncherEnabled = false
                   aaptOptions.useNewCruncher = false

                 }

Whenever I click the find button
it comes like this

   Manager: playSoundEffect   effectType: 0
   V/AudioManager: querySoundEffectsEnabled...

is there any issue with this link to show my api enabled.

Body:
Google map is initialized within the method
public void onMapReady(GoogleMap googleMap)

but as onLocationChanged(Location location) is a callback method from LocationListener, which might get called before the map is ready and initialized.

so i guess, a null check before moving the camera will solve the problem

@Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        if(mGoogleMap != null){
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));  /// error is shown in this line
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

    }


来源: stackexchange

问:
Not getting index value of the clicked a href tag
I have following html

```<code>HTML code for testing purposes (do not submit uncommented):
<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>
</code>```

My JS

```<code>$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }
});
</code>```

The alert is not giving me the index of the link clicked. How can i get the index?

答:
use jquery with index() function

$('body').on('click','a[id^=mm]', function () {
console.log($(this).index()/2)

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML code for testing purposes (do not submit uncommented):

<body>
  In my life, I used the following web search engines:<br/>
  Yahoo!<br/>
  AltaVista<br/>
  Google<br/>
</body></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following html

HTML code for testing purposes (do not submit uncommented):

  In my life, I used the following web search engines:

  Yahoo!

  AltaVista

  Google

My JS

$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }
});

The alert is not giving me the index of the link clicked. How can i get the index?

Body:
use jquery with index() function

$('body').on('click','a[id^=mm]', function () {
console.log($(this).index()/2)

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML code for testing purposes (do not submit uncommented):

<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>


问:
how to add yyyy/MM date in drop down list in webforms c#
I'm new in c# webforms. I'm experimenting drop down list. I want to load the current year and  month, and it's two months ago months. I want to display YEAR and MONTH only.
example: date now - 2017 / 03. two months ago are - 2017 / 02 and 2017 / 01.

default.aspx:

```<code> <asp:DropDownList ID="ddlStartPeriod" runat="server"></asp:DropDownList>
</code>```

on my page_load in default.aspx.cs:

ddlStartPeriod.Items.Add(DateTime.Now.ToString("yyyy / MM"));

I don't know what's the next move and I don't how to subtract 2 months from DateTime.Now.ToString("yyyy / MM").

Thank you in advance!

答:
Try below code</p>

```<code> ListItem li = new ListItem(DateTime.Now.ToString("yyyy/MM"), DateTime.Now.ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li);
            ListItem li2 = new ListItem(DateTime.Now.AddMonths(-1).ToString("yyyy/MM"), DateTime.Now.AddMonths(-1).ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li2);
            ListItem li3 = new ListItem(DateTime.Now.AddMonths(-2).ToString("yyyy/MM"), DateTime.Now.AddMonths(-2).ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li3);
</code>```

Body:
I'm new in c# webforms. I'm experimenting drop down list. I want to load the current year and  month, and it's two months ago months. I want to display YEAR and MONTH only.
example: date now - 2017 / 03. two months ago are - 2017 / 02 and 2017 / 01.

default.aspx:

 <asp:DropDownList ID="ddlStartPeriod" runat="server"></asp:DropDownList>

on my page_load in default.aspx.cs:

ddlStartPeriod.Items.Add(DateTime.Now.ToString("yyyy / MM"));

I don't know what's the next move and I don't how to subtract 2 months from DateTime.Now.ToString("yyyy / MM").

Thank you in advance!

Body:
Try below code

 ListItem li = new ListItem(DateTime.Now.ToString("yyyy/MM"), DateTime.Now.ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li);
            ListItem li2 = new ListItem(DateTime.Now.AddMonths(-1).ToString("yyyy/MM"), DateTime.Now.AddMonths(-1).ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li2);
            ListItem li3 = new ListItem(DateTime.Now.AddMonths(-2).ToString("yyyy/MM"), DateTime.Now.AddMonths(-2).ToString("yyyy/MM"));
            ddlStartPeriod.Items.Add(li3);


问:
Open .inf file to add a network adapter driver in Windows 7
Basically I cannot open my inf file to install my driver, look: when I find my file, then OK, nothing happens.

答: I had to set up the file before adding the .inf file.</p>


问:
Firebase Server Side Query and autopopulate on some "database event"
I've been working with Firebase for 1 month, and now I'm starting to understand how it works.

In my App I've got some supermarket products like fruit, vegetable or others.

In real life I've got some NFC tags applied on the products.

In the database, there is a node which contains products, one node which contains NFC Ids, and one node which contains relations between them.

The Product's keys are pushed Ids while the NFC's are their Ids.

With my phone and the embedded NFC reader I can read the tags and tell the system which product I'm scanning.

Now I'd like to create a record each time a phone reads a NFC.

On the record, I'd like to put the data about the phone, the NFC Id's and the Product Push Id.

Is there a Server Side way, maybe with rules, to query the relation between NFC and Products and put it on my new record, the Product Id instead of the relation Id?

In this way I'll cut a lot of Client Side code which is making may app too complicated.

Thanks.

答:
I have also faced this problem. However, Firebase has introduce Cloud Function a month ago. Try to check the official link out. It allow you to put some logics in server side.

https://firebase.google.com/docs/functions/

I myself haven't done much research on this feature but instead of thinking about the communication as Request and Response you need to see it as Database trigger event.

Is this what you looking for ?


问:
What is the function `*shellNoRender`?
I searched the page of Angular.io but I have not been able to see anything, someone can tell me what to do *shellNoRender. For example I saw it used, so in a conference of google I/O:

```<code><md-nav-list *shellNoRender>
</code>```

答:
That's a directive from the app-shell, which is part of the Angular Mobile Toolkit. This is not available in the 'normal' angular.

There are usually components that you'd like to have in your App Shell but not your app at runtime, and vice versa. For example, we might want to have a router outlet in our dynamic application, and a progress indicator in its place in our App Shell. Fortunately, our app component already has a couple of directives available that make this simple, *shellRender and *shellNoRender.

With this you can change which component to use during runtime and during server side compilation using universal

Title: What is the function `*shellNoRender`?

Body:
I searched the page of Angular.io but I have not been able to see anything, someone can tell me what to do *shellNoRender. For example I saw it used, so in a conference of google I/O:

<md-nav-list *shellNoRender>


问:
How is putting the lambda expression after the parameters on a mapTo call legal syntax?
I found a piece of code I do not understand.

I am transforming a JSONArray into a List.

Kotlin provides the function mapTo in it's stdlib(link)

mapTo

```<code>inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(
    destination: C,
    transform: (T) -> R
): C (source)
</code>```

Applies the given transform function to each element of the original collection and appends the results to the given destination.

This functions has 2 parameters and can be used like this (as expected):

```<code>(0..jsonArray.length() - 1).mapTo(targetList, {it -> jsonArray[it].toString()})
</code>```

But apparently this is also valid syntax (not expected):

```<code>(0..jsonArray.length()-1).mapTo(targetList) {it -> jsonArray[it].toString()}
</code>```

As you can see, the function parameters end after outputList and the lambda expression is just put at the end of the function call.

Furthermore this is legal (as expected):

```<code>val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList, transformation)
</code>```

but this is not (???):

```<code>val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList) transformation
</code>```

答:
As stated in the documentation:

In Kotlin, there is a convention that if the last parameter to a
  function is a function, and you're passing a lambda expression as the
  corresponding argument, you can specify it outside of parentheses:

```<code>lock (lock) {
    sharedResource.operation()
}
</code>```

Another example of a higher-order function would be map():

```<code>fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}
</code>```

This function can be called as follows:

```<code>val doubled = ints.map { it -> it * 2 }
</code>```

Note that the parentheses in a call can be omitted entirely if the
  lambda is the only argument to that call.

The documentation states clearly that for the above to work the last argument must be lambda expression and not a variable of matching type.

Body:
I found a piece of code I do not understand.

I am transforming a JSONArray into a List.

Kotlin provides the function mapTo in it's stdlib(link)

mapTo

inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(
    destination: C,
    transform: (T) -> R
): C (source)

Applies the given transform function to each element of the original collection and appends the results to the given destination.

This functions has 2 parameters and can be used like this (as expected):

(0..jsonArray.length() - 1).mapTo(targetList, {it -> jsonArray[it].toString()})

But apparently this is also valid syntax (not expected):

(0..jsonArray.length()-1).mapTo(targetList) {it -> jsonArray[it].toString()}

As you can see, the function parameters end after outputList and the lambda expression is just put at the end of the function call.

Furthermore this is legal (as expected):

val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList, transformation)

but this is not (???):

val transformation = {it : Int -> jsonArray[it].toString()}
(0..jsonArray.length()-1).mapTo(targetList) transformation

Body:
As stated in the documentation:

In Kotlin, there is a convention that if the last parameter to a
  function is a function, and you're passing a lambda expression as the
  corresponding argument, you can specify it outside of parentheses:

lock (lock) {
    sharedResource.operation()
}

Another example of a higher-order function would be map():

fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
    val result = arrayListOf<R>()
    for (item in this)
        result.add(transform(item))
    return result
}

This function can be called as follows:

val doubled = ints.map { it -> it * 2 }

Note that the parentheses in a call can be omitted entirely if the
  lambda is the only argument to that call.

The documentation states clearly that for the above to work the last argument must be lambda expression and not a variable of matching type.


问:
In C why can I pass function name (not a pointer) as parameter to funtion?
I have test the following code:

```<code>#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}
</code>```

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

```<code>void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}
</code>```

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

答:
When used as a function parameter, function name behaves as a pointer to the function itself.

These all are valid prototype

```<code>void f(void (g)());
void f(void (*g)());
void f(void (**g)());
void f(void (*****g)());
</code>```

When you declare a function pointer then you can make a call using that pointer as

```<code>g();
(*g)();
(*****g)();
</code>```

Body:
I have test the following code:

#include <stdio.h>
void f(void g()) {
    g();
}

void g(void) {
    printf("hello, world\n");
}

int main() {
    f(g);
    return 0;
}

It works well. In the code above, why in c we can take the function name g as paramter and take the function prototype as parameter?

In book K&R, it says that we can use the pointer to function:
So I can define the function f like this:

void f(void (*g)()) {
    g();
}
void g(void) {
    printf("hello, world\n");
}

int main() {
    void (*pf)() = g;
    f(pf);
    f(g);   // Here f(g) also works.
    return 0;
}

So in the first f definition form, the parameter prototype is void g(), in the second form the parameter prototype is void (*g)(). Why the two forms of definition of f are the same?

And in the second form, the parameter is a pointer to function, why f(g) also works?

Body:
When used as a function parameter, function name behaves as a pointer to the function itself.

These all are valid prototype

void f(void (g)());
void f(void (*g)());
void f(void (**g)());
void f(void (*****g)());

When you declare a function pointer then you can make a call using that pointer as

g();
(*g)();
(*****g)();


问:
Convert coordinates in a region into a numpy array in Python
I have a rectangular region, where the lower left (min) and upper right (max) coordinates. I want to make a Numpy array that consists of coordinates in the region. For example, the min and max are (3, 8) and  max (0, 6), respectively. The numpy array I want to make is

Additionally, I have a requirement that the grid in the region may be smaller than 1. For example, 0.5 makes X = [[3.0, 0] [3.5, 0] [4.0, 0] [4.5, 0] ...]]

Body:
You could use numpy.mgrid:

>>> numpy.mgrid[3:8, 0:6].T
array([[[3, 0],
        [4, 0],
        [5, 0],
        [6, 0],
        [7, 0]],

       [[3, 1],
        [4, 1],
        [5, 1],
        [6, 1],
        [7, 1]],

        ...

       [[3, 5],
        [4, 5],
        [5, 5],
        [6, 5],
        [7, 5]]])

If you want a "flat" array of tuples, you can reshape it:

>>> numpy.mgrid[3:8, 0:6].T.reshape((-1, 2))
array([[3, 0],
       [4, 0],
       [5, 0],
       [6, 0],
       [7, 0],
       [3, 1],
       ...
       [6, 5],
       [7, 5]])


问:
What is the best way to tell users of my library functions that passed variables are not of the correct type
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

```<code>function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}
</code>```

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

答:
The problem with type checking is that its actually quite hard to do.  For example:-

```<code>var s = new String("Hello World!");
alert(typeof s);
</code>```

What gets alerted?  Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less.  I prefer to attempt conversions where necessary or just do nothing.

Having said that in a Javascript environment in which I have total control (which is not true if you are simply providing a library) I use this set of prototype tweaks:-

```<code>String.prototype.isString = true;
Number.prototype.isNumber = true;
Boolean.prototype.isBoolean = true;
Date.prototype.isDate = true;
Array.prototype.isArray = true;
</code>```

Hence testing for the common types can be as simple as:-

```<code>if (x.isString)
</code>```

although you still need to watch out for null/undefined:-

```<code>if (x != null && x.isString)
</code>```

In addition to avoiding the new String("thing") gotcha, this approach particularly comes into its own on Dates and Arrays.

OwnerDisplayName: Pim Jager

ContentLicense: CC BY-SA 2.5

Body:
I'm currently in the creation of a javascript function library. Mainly for my own use, but you can never be sure if someone else ends up using it in their projects, I'm atleast creating it as if that could happen.

Most methods only work if the variables that are passed are of the correct datatype. Now my question is: What is the best way to alert users that the variable is not of the correct type? Should one throw an error like this?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does internal type conversion, but this can create very weird results (ie '234' + 5 = '2345' but '234' * 1 = 234) and this could make my methods do very weird things.

EDIT

To make things extra clear: I do not wish to do type conversion, the variables passed should be of the correct type. What is the best way to tell the user of my library that the passed variables are not of the correct type?

LastEditorDisplayName: Mitch Wheat

Body:
The problem with type checking is that its actually quite hard to do.  For example:-

var s = new String("Hello World!");
alert(typeof s);

What gets alerted?  Ans: "object". Its true its a daft way to initialise a string but I see it quite often none-the-less.  I prefer to attempt conversions where necessary or just do nothing.

Having said that in a Javascript environment in which I have total control (which is not true if you are simply providing a library) I use this set of prototype tweaks:-

String.prototype.isString = true;
Number.prototype.isNumber = true;
Boolean.prototype.isBoolean = true;
Date.prototype.isDate = true;
Array.prototype.isArray = true;

Hence testing for the common types can be as simple as:-

if (x.isString)

although you still need to watch out for null/undefined:-

if (x != null && x.isString)

In addition to avoiding the new String("thing") gotcha, this approach particularly comes into its own on Dates and Arrays.

OwnerDisplayName: AnthonyWJones


问:
How to add jFreeChart library with the netbeans IDE?
I am having jCommon(jFreeChart) library file. (It contains ant, checkstyle, docfiles, experimental, lib, source, swt, tests, ChangeLog, jfreechart-1.0.13-demo.jar, licence-LGPL.txt, maven-jfreechart-project.xml, NEWS,Readme.txt) I've used NetbeansIDE6.9 to add into the netbeans new library there are three tabs classpath,source,javadoc. javadoc tab need index-all.html file. How to add this and run the application?</p>

答:
Project properties -> Libraries -> Add JAR/Folder -> Browser JAR

To add source, you need to have source downloaded. As I can see in your given list, you are having one. You can select JAR you just added, using a method I have stated above, and click Edit. There you will have another pop-up with the tab "Sources". You can add source JAR in there.

To add Javadocs, you need to download it first. Then just add that zip file, most probably by following similar steps.

P.S.: Learn Maven, you will love it. It will manage all these things for you automagically. You just need to provide the artifacts.


问:
How to convert Moment to another moment depending on timezone
I really bad in JS and I'm struggling with moment.js

My wish is: get a date from a div (UTC) and convert this date depending on the timezone of the user.

So if the UTC date is 30/03/2017 6:34:22 AM
Someone in New York sees 30/03/2017 2:34:22 AM
Someone in Perth sees 30/03/2017 2:34:22 PM

I did something similar in C# with TimeZoneInfo and IsDaylightSavingTime but I don't know how to do this in JS.

Below my code:

```<code>// <div id="utc-time">30/03/2017 6:34:22 AM</div>

var dt = document.getElementById("utc-time").innerHTML;
var m = moment(dt, "DD-MM-YYYY hh:mm:ss a");
var tz = moment.tz.guess();
var user = moment.tz(dt, "DD-MM-YYYY hh:mm:ss a", tz);
var mString = m.toString();

// Console.log
// -----------
dt = 30/03/2017 6:34:22 AM
m = 1490826862000
user = Thu Mar 30 2017 06:34:22 GMT+0800
mString = Wed Mar 29 2017 22:34:22 GMT+0000
</code>```

It looks like the moment created is not UTC but keep the local timezone. A hint would be nice :)

答:
You can use moment local() to convert moment object to user local time, while you can use tz() to convert time between zones.

Use moment.utc to parse date as UTC. Use format() to show values of moment objects.

If you just need to support UTC and user local time, you don't need moment-timezone.

Here a working sample:

var dt = document.getElementById("utc-time").innerHTML;
var m = moment.utc(dt, "DD-MM-YYYY h:mm:ss A"); // parse input as UTC
console.log(m.clone().local().format("DD-MM-YYYY h:mm:ss A")); // local time
var tz = 'America/New_York'; // example value, you can use moment.tz.guess()
console.log(m.clone().tz(tz).format("DD-MM-YYYY h:mm:ss A")); // 30-03-2017 2:34:22 AM
tz = 'Australia/Perth';
console.log(m.clone().tz(tz).format("DD-MM-YYYY h:mm:ss A")); // 30-03-2017 2:34:22 PM```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>

<div id="utc-time">30/03/2017 6:34:22 AM</div></code>```

Body:
I really bad in JS and I'm struggling with moment.js

My wish is: get a date from a div (UTC) and convert this date depending on the timezone of the user.

So if the UTC date is 30/03/2017 6:34:22 AM
Someone in New York sees 30/03/2017 2:34:22 AM
Someone in Perth sees 30/03/2017 2:34:22 PM

I did something similar in C# with TimeZoneInfo and IsDaylightSavingTime but I don't know how to do this in JS.

Below my code:

//
30/03/2017 6:34:22 AM

var dt = document.getElementById("utc-time").innerHTML;
var m = moment(dt, "DD-MM-YYYY hh:mm:ss a");
var tz = moment.tz.guess();
var user = moment.tz(dt, "DD-MM-YYYY hh:mm:ss a", tz);
var mString = m.toString();

// Console.log
// -----------
dt = 30/03/2017 6:34:22 AM
m = 1490826862000
user = Thu Mar 30 2017 06:34:22 GMT+0800
mString = Wed Mar 29 2017 22:34:22 GMT+0000

It looks like the moment created is not UTC but keep the local timezone. A hint would be nice :)

Body:
You can use moment local() to convert moment object to user local time, while you can use tz() to convert time between zones.

Use moment.utc to parse date as UTC. Use format() to show values of moment objects.

If you just need to support UTC and user local time, you don't need moment-timezone.

Here a working sample:

var dt = document.getElementById("utc-time").innerHTML;
var m = moment.utc(dt, "DD-MM-YYYY h:mm:ss A"); // parse input as UTC
console.log(m.clone().local().format("DD-MM-YYYY h:mm:ss A")); // local time
var tz = 'America/New_York'; // example value, you can use moment.tz.guess()
console.log(m.clone().tz(tz).format("DD-MM-YYYY h:mm:ss A")); // 30-03-2017 2:34:22 AM
tz = 'Australia/Perth';
console.log(m.clone().tz(tz).format("DD-MM-YYYY h:mm:ss A")); // 30-03-2017 2:34:22 PM

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>

<div id="utc-time">30/03/2017 6:34:22 AM</div>


问:
Userform to search on two column from data range
At the moment, I am searching on one column. But I am stuck on how to search on two or multiple fields to bring up more of a specific result.

I am trying to narrow my search down from 1 to 2 to bring up more specific data. Can anyone help. Thanks in Advance. Appreciate the help!!!!!

```<code>Public CallDetails As Collection

Public Function Find_CallNumbers(NumberToFind As String) As Collection

Dim rng_to_search As Range
Dim rFound As Range
Dim FirstAddress As String
Dim FoundItem As clsCallDetails

Set CallDetails = New Collection

With ThisWorkbook.Worksheets("Database")
    Set rng_to_search = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

With rng_to_search
    'Look for the first instance.
    Set rFound = .Find(what:=NumberToFind, _
                       after:=.Cells(1, 1), _
                       LookIn:=xlValues, _
                       LookAt:=xlPart, _
                       SearchDirection:=xlNext)
    If Not rFound Is Nothing Then
        FirstAddress = rFound.Address
        Do
            Set FoundItem = New clsCallDetails 'Create a new instance of the class to hold the details.
            With FoundItem
                .Title = rFound.Offset(, 7) 'CORRECT
                .LoggedBy = rFound.Offset(, 2) 'CORRECT .Offset from column A by 1 column, so column B.
                .CallNumber = rFound.Offset(, 3) 'CORRECT
                .DateField = rFound.Offset(, 4) 'CORRECT
                .OwnerField = rFound.Offset(, 6) 'CORRECT
                .Description = rFound.Offset(, 8) 'CORRECT
                .Solution = rFound.Offset(, 9) 'CORRECT
                .URLImage = rFound.Offset(, 10) 'CORRECT
                .DateResolved = rFound.Offset(, 5) 'CORRECT
                .Reference = rFound.Offset(, 1) 'CORRECT

            End With
            CallDetails.Add FoundItem 'Add the class instance to our collection.
            Set rFound = .FindNext(rFound) 'Look for the next value.

        'Continue searching until we reach the top again.
        Loop While Not rFound Is Nothing And rFound.Address <> FirstAddress
    End If
End With

End Function
</code>```

```<code>Private Sub PlaceValues(Index As Long)
With Me
    .txtLoggedBy.Value = CallDetails(Index).LoggedBy
    .txtCallNumber.Value = CallDetails(Index).CallNumber
    .txtDateField.Value = CallDetails(Index).DateField
    .txtTitle.Value = CallDetails(Index).Title
    .cmbOwnerField.Value = CallDetails(Index).OwnerField
    .txtDescription.Value = CallDetails(Index).Description
    .txtSolution.Value = CallDetails(Index).Solution
    .txtURLImage.Value = CallDetails(Index).URLImage
    .txtDateResolved.Value = CallDetails(Index).DateResolved
    .txtReference.Value = CallDetails(Index).reference
End With
End Sub
</code>```

答:
This should give you a very basic idea of doing this. The function allows each variable to be passed to the function. These are optional so they don't have to be provided. It then tests the ones which are provided against the values that have been found and if they match gives them increases the Score by 1. If the final score then exceeds or is equal to a Tolerance it adds it to your custom collection. You'll have to modify this slightly for the correct data types and comparitive methods.

```<code>Public CallDetails As Collection

Public Function Find_CallNumbers(NumberToFind As String, Optional Title As String, Optional LoggedBy As String, _
    Optional CallNumber As Long, Optional DateField As Long, Optional OwnerField As String, Optional Description As String, _
    Optional Solution As String, Optional URLImage As String, Optional DateResolved As Long, Optional reference As String) As Collection

    Dim rng_to_search As Range
    Dim rFound As Range
    Dim FirstAddress As String
    Dim FoundItem As clsCallDetails
    Dim Score As Long
    Dim Tolerance As Long

    Set CallDetails = New Collection

    With ThisWorkbook.Worksheets("Database")
        Set rng_to_search = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    Tolerance = 8

    With rng_to_search
        'Look for the first instance.
        Set rFound = .Find(what:=NumberToFind, _
                           after:=.Cells(1, 1), _
                           LookIn:=xlValues, _
                           LookAt:=xlPart, _
                           SearchDirection:=xlNext)
        If Not rFound Is Nothing Then
            FirstAddress = rFound.Address
            Do
                With rFound
                    If Title = rFound.Offset(, 7) Then Score = Score + 1
                    If LoggedBy = rFound.Offset(, 2) Then Score = Score + 1
                    If CallNumber = rFound.Offset(, 3) Then Score = Score + 1
                    If DateField = rFound.Offset(, 4) Then Score = Score + 1
                    If OwnerField = rFound.Offset(, 6) Then Score = Score + 1
                    If Description = rFound.Offset(, 8) Then Score = Score + 1
                    If Solution = rFound.Offset(, 9) Then Score = Score + 1
                    If URLImage = rFound.Offset(, 10) Then Score = Score + 1
                    If DateResolved = rFound.Offset(, 5) Then Score = Score + 1
                    If reference = rFound.Offset(, 1) Then Score = Score + 1
                End With

                If Score >= Tolerance Then
                    Set FoundItem = New clsCallDetails 'Create a new instance of the class to hold the details.
                    With FoundItem
                        .Title = rFound.Offset(, 7) 'CORRECT
                        .LoggedBy = rFound.Offset(, 2) 'CORRECT .Offset from column A by 1 column, so column B.
                        .CallNumber = rFound.Offset(, 3) 'CORRECT
                        .DateField = rFound.Offset(, 4) 'CORRECT
                        .OwnerField = rFound.Offset(, 6) 'CORRECT
                        .Description = rFound.Offset(, 8) 'CORRECT
                        .Solution = rFound.Offset(, 9) 'CORRECT
                        .URLImage = rFound.Offset(, 10) 'CORRECT
                        .DateResolved = rFound.Offset(, 5) 'CORRECT
                        .reference = rFound.Offset(, 1) 'CORRECT
                    End With
                    CallDetails.Add FoundItem 'Add the class instance to our collection.
                    Set rFound = .FindNext(rFound) 'Look for the next value.
                End If
                Score = 0

            'Continue searching until we reach the top again.
            Loop While Not rFound Is Nothing And rFound.Address <> FirstAddress
        End If
    End With

End Function
</code>```

For your class to hold a Score value as well you should just need to add

```<code>Private pScore As Long
Public Property Get Score() As Long
    Score = pScore
End Property
Public Property Let Score(value As Long)
    pScore = value
End Property
</code>```

to clsCallDetails

Body:
At the moment, I am searching on one column. But I am stuck on how to search on two or multiple fields to bring up more of a specific result.

I am trying to narrow my search down from 1 to 2 to bring up more specific data. Can anyone help. Thanks in Advance. Appreciate the help!!!!!

Public CallDetails As Collection

Public Function Find_CallNumbers(NumberToFind As String) As Collection

Dim rng_to_search As Range
Dim rFound As Range
Dim FirstAddress As String
Dim FoundItem As clsCallDetails

Set CallDetails = New Collection

With ThisWorkbook.Worksheets("Database")
    Set rng_to_search = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

With rng_to_search
    'Look for the first instance.
    Set rFound = .Find(what:=NumberToFind, _
                       after:=.Cells(1, 1), _
                       LookIn:=xlValues, _
                       LookAt:=xlPart, _
                       SearchDirection:=xlNext)
    If Not rFound Is Nothing Then
        FirstAddress = rFound.Address
        Do
            Set FoundItem = New clsCallDetails 'Create a new instance of the class to hold the details.
            With FoundItem
                .Title = rFound.Offset(, 7) 'CORRECT
                .LoggedBy = rFound.Offset(, 2) 'CORRECT .Offset from column A by 1 column, so column B.
                .CallNumber = rFound.Offset(, 3) 'CORRECT
                .DateField = rFound.Offset(, 4) 'CORRECT
                .OwnerField = rFound.Offset(, 6) 'CORRECT
                .Description = rFound.Offset(, 8) 'CORRECT
                .Solution = rFound.Offset(, 9) 'CORRECT
                .URLImage = rFound.Offset(, 10) 'CORRECT
                .DateResolved = rFound.Offset(, 5) 'CORRECT
                .Reference = rFound.Offset(, 1) 'CORRECT

            End With
            CallDetails.Add FoundItem 'Add the class instance to our collection.
            Set rFound = .FindNext(rFound) 'Look for the next value.

        'Continue searching until we reach the top again.
        Loop While Not rFound Is Nothing And rFound.Address <> FirstAddress
    End If
End With

End Function

Private Sub PlaceValues(Index As Long)
With Me
    .txtLoggedBy.Value = CallDetails(Index).LoggedBy
    .txtCallNumber.Value = CallDetails(Index).CallNumber
    .txtDateField.Value = CallDetails(Index).DateField
    .txtTitle.Value = CallDetails(Index).Title
    .cmbOwnerField.Value = CallDetails(Index).OwnerField
    .txtDescription.Value = CallDetails(Index).Description
    .txtSolution.Value = CallDetails(Index).Solution
    .txtURLImage.Value = CallDetails(Index).URLImage
    .txtDateResolved.Value = CallDetails(Index).DateResolved
    .txtReference.Value = CallDetails(Index).reference
End With
End Sub

Body:
This should give you a very basic idea of doing this. The function allows each variable to be passed to the function. These are optional so they don't have to be provided. It then tests the ones which are provided against the values that have been found and if they match gives them increases the Score by 1. If the final score then exceeds or is equal to a Tolerance it adds it to your custom collection. You'll have to modify this slightly for the correct data types and comparitive methods.

Public CallDetails As Collection

Public Function Find_CallNumbers(NumberToFind As String, Optional Title As String, Optional LoggedBy As String, _
    Optional CallNumber As Long, Optional DateField As Long, Optional OwnerField As String, Optional Description As String, _
    Optional Solution As String, Optional URLImage As String, Optional DateResolved As Long, Optional reference As String) As Collection

    Dim rng_to_search As Range
    Dim rFound As Range
    Dim FirstAddress As String
    Dim FoundItem As clsCallDetails
    Dim Score As Long
    Dim Tolerance As Long

    Set CallDetails = New Collection

    With ThisWorkbook.Worksheets("Database")
        Set rng_to_search = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    Tolerance = 8

    With rng_to_search
        'Look for the first instance.
        Set rFound = .Find(what:=NumberToFind, _
                           after:=.Cells(1, 1), _
                           LookIn:=xlValues, _
                           LookAt:=xlPart, _
                           SearchDirection:=xlNext)
        If Not rFound Is Nothing Then
            FirstAddress = rFound.Address
            Do
                With rFound
                    If Title = rFound.Offset(, 7) Then Score = Score + 1
                    If LoggedBy = rFound.Offset(, 2) Then Score = Score + 1
                    If CallNumber = rFound.Offset(, 3) Then Score = Score + 1
                    If DateField = rFound.Offset(, 4) Then Score = Score + 1
                    If OwnerField = rFound.Offset(, 6) Then Score = Score + 1
                    If Description = rFound.Offset(, 8) Then Score = Score + 1
                    If Solution = rFound.Offset(, 9) Then Score = Score + 1
                    If URLImage = rFound.Offset(, 10) Then Score = Score + 1
                    If DateResolved = rFound.Offset(, 5) Then Score = Score + 1
                    If reference = rFound.Offset(, 1) Then Score = Score + 1
                End With

                If Score >= Tolerance Then
                    Set FoundItem = New clsCallDetails 'Create a new instance of the class to hold the details.
                    With FoundItem
                        .Title = rFound.Offset(, 7) 'CORRECT
                        .LoggedBy = rFound.Offset(, 2) 'CORRECT .Offset from column A by 1 column, so column B.
                        .CallNumber = rFound.Offset(, 3) 'CORRECT
                        .DateField = rFound.Offset(, 4) 'CORRECT
                        .OwnerField = rFound.Offset(, 6) 'CORRECT
                        .Description = rFound.Offset(, 8) 'CORRECT
                        .Solution = rFound.Offset(, 9) 'CORRECT
                        .URLImage = rFound.Offset(, 10) 'CORRECT
                        .DateResolved = rFound.Offset(, 5) 'CORRECT
                        .reference = rFound.Offset(, 1) 'CORRECT
                    End With
                    CallDetails.Add FoundItem 'Add the class instance to our collection.
                    Set rFound = .FindNext(rFound) 'Look for the next value.
                End If
                Score = 0

            'Continue searching until we reach the top again.
            Loop While Not rFound Is Nothing And rFound.Address <> FirstAddress
        End If
    End With

End Function

For your class to hold a Score value as well you should just need to add

Private pScore As Long
Public Property Get Score() As Long
    Score = pScore
End Property
Public Property Let Score(value As Long)
    pScore = value
End Property

to clsCallDetails


问:
How to add Firebase into android
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Manifest :

```<code><application>
...
        <!--Firebase service-->
        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>
</code>```

MyFirebaseInctanceIdService :

```<code>public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}
</code>```

Logs:

```<code>03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s
</code>```

How can I fix this issue and show Firebase token in logs?

答:
why you not tried integrated android studio with firebase directly using Tools menu-->firebase

add this line Gradle :-Module(app)

```<code>compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
</code>```

Title: How to add Firebase into android

Body:
I want added Firebase into my application. I write below codes, but when running application I can't see TOKEN in log!

My dependencies :

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

Manifest :

<application>
...

        <service android:name=".CloudMSG.MyFirebaseInctanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

MyFirebaseInctanceIdService :

public class MyFirebaseInctanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInctance";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d("MyFirebaseInctance", "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        //sendRegistrationToServer(refreshedToken);
    }
}

Logs:

03-30 13:36:42.943 9487-9487/? I/art: Late-enabling -Xcheck:jni
03-30 13:36:43.218 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
03-30 13:36:43.269 9487-9487/com.example.mohammad.a1_firebase W/InstanceID/Rpc: Found 10004
03-30 13:36:43.298 9487-9487/com.example.mohammad.a1_firebase D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: App measurement is starting up, version: 10084
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: Debug-level message logging enabled
03-30 13:36:43.364 9487-9487/com.example.mohammad.a1_firebase D/FA: AppMeasurement singleton hash: 720240273
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: Collection enabled
03-30 13:36:43.404 9487-9487/com.example.mohammad.a1_firebase V/FA: App package, google app id: com.example.mohammad.a1_firebase, 1:685652680518:android:0280a3bc1c6da8cb
03-30 13:36:43.405 9487-9487/com.example.mohammad.a1_firebase I/FA: To enable faster debug mode event logging run:
                                                                      adb shell setprop debug.firebase.analytics.app com.example.mohammad.a1_firebase
03-30 13:36:43.463 9487-9487/com.example.mohammad.a1_firebase V/FA: Registered activity lifecycle callback
03-30 13:36:43.465 9487-9487/com.example.mohammad.a1_firebase I/FirebaseInitProvider: FirebaseApp initialization successful
03-30 13:36:43.467 9487-9487/com.example.mohammad.a1_firebase I/InstantRun: Starting Instant Run Server for com.example.mohammad.a1_firebase
03-30 13:36:43.471 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.489 9487-9587/com.example.mohammad.a1_firebase V/FA: Connecting to remote service
03-30 13:36:43.528 9487-9587/com.example.mohammad.a1_firebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 13:36:43.612 9487-9487/com.example.mohammad.a1_firebase D/ContextHelper: convertTheme. context->name=com.example.mohammad.a1_firebase themeResourceId=2131230883
03-30 13:36:43.656 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-30 13:36:43.690 9487-9487/com.example.mohammad.a1_firebase V/FA: onActivityCreated
03-30 13:36:43.696 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5
03-30 13:36:43.718 9487-9487/com.example.mohammad.a1_firebase I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Using measurement service
03-30 13:36:43.859 9487-9587/com.example.mohammad.a1_firebase V/FA: Connection attempt already in progress
03-30 13:36:43.864 9487-9587/com.example.mohammad.a1_firebase V/FA: Activity resumed, time: 1436094125
03-30 13:36:43.879 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Render dirty regions requested: true
03-30 13:36:43.881 9487-9612/com.example.mohammad.a1_firebase I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013_msm8974_LA.BF.1.1.1_RB1__release_AU ()
                                                                            OpenGL ES Shader Compiler Version: E031.25.03.00
                                                                            Build Date: 01/21/15 Wed
                                                                            Local Branch: mybranch7061829
                                                                            Remote Branch: quic/LA.BF.1.1.1_rb1.7
                                                                            Local Patches: NONE
                                                                            Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.013 +  NOTHING
03-30 13:36:43.882 9487-9612/com.example.mohammad.a1_firebase I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 13:36:43.910 9487-9612/com.example.mohammad.a1_firebase D/OpenGLRenderer: Enabling debug mode 0
03-30 13:36:43.916 9487-9487/com.example.mohammad.a1_firebase D/Atlas: Validating map...
03-30 13:36:43.927 9487-9487/com.example.mohammad.a1_firebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 13:36:43.936 9487-9592/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 30s
03-30 13:36:44.008 9487-9502/com.example.mohammad.a1_firebase W/art: Suspending all threads took: 5.068ms
03-30 13:36:44.047 9487-9487/com.example.mohammad.a1_firebase W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-30 13:36:44.183 9487-9487/com.example.mohammad.a1_firebase I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@755dbad time:128236912
03-30 13:37:14.017 9487-10051/com.example.mohammad.a1_firebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s

How can I fix this issue and show Firebase token in logs?

Body:
why you not tried integrated android studio with firebase directly using Tools menu-->firebase

add this line Gradle :-Module(app)

compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'


问:
android - dynamically changing the position of an imageview
i'm currently using the matrix method to implement drag and pinch zoom for an image (image A)

Now i want a part of image A to be clickable so i put another imageview (image B) over image A and set the layout_margins for it in the xml file.

My question is...is there a way to dynamically change my layout_margins as i'm scaling my image for drag and pinch zoom?

I guess the simpler question is...how do i dynamically set the layout_margins for an imageview?

```<code><RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

   <ImageView android:id="@+id/imageView"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:src="@drawable/map"
     android:scaleType="matrix" />

    <ImageView
       android:id="@+id/dundas_station"
       android:layout_width="75px"
       android:layout_height="75px"
       android:layout_marginTop="337px"
   android:layout_marginLeft="373px"
       android:clickable="true"
       android:src="@drawable/google_maps_icon"
       android:scaleType="matrix"
       />
</RelativeLayout>
</code>```

thanks!

答: You use setMargins</p>

Body:
i'm currently using the matrix method to implement drag and pinch zoom for an image (image A)

Now i want a part of image A to be clickable so i put another imageview (image B) over image A and set the layout_margins for it in the xml file.

My question is...is there a way to dynamically change my layout_margins as i'm scaling my image for drag and pinch zoom?

I guess the simpler question is...how do i dynamically set the layout_margins for an imageview?

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

   <ImageView android:id="@+id/imageView"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:src="@drawable/map"
     android:scaleType="matrix" />

    <ImageView
       android:id="@+id/dundas_station"
       android:layout_width="75px"
       android:layout_height="75px"
       android:layout_marginTop="337px"
   android:layout_marginLeft="373px"
       android:clickable="true"
       android:src="@drawable/google_maps_icon"
       android:scaleType="matrix"
       />
</RelativeLayout>

thanks!

Body: You use setMargins