问:
sql subqueries explained
```<code>SELECT sub.*
FROM (
     SELECT *
     FROM tutorial.sf_crime_incidents_2014_01
     WHERE day_of_week = 'Friday'
     ) sub
WHERE sub.resolution = 'NONE'
</code>```

This subquery is not mine, it is from a tutorial website. I just want to clear the idea of the subquery, so first, the inner query is done and then the answer becomes in the alias name sub. Then the outer query takes the answer and selects all columns matching this answer with a where condition.Is this how it works?

Thank you for the help.

答:
Conceptually, this is how it works.

However, you need to be aware that you can not use subqueries to force the RDBMS (MySQL, PostgreSQL or any other) to perform the operations in the order you described. The RDBMS will chose itself how it will execute the query through what is called a query plan.

For example, the following query expresses exactly the same as your query :

```<code>SELECT *
FROM tutorial.sf_crime_incidents_2014_01
WHERE day_of_week = 'Friday' AND sub.resolution = 'NONE';
</code>```

And the optimizer is typically able to determine that your query can be simplified (I guess you'll agree that the above query is simpler than yours).

Note that it is more readable to pad the subqueries to distinguish easily what is the subquery and what is the main query :

```<code>SELECT sub.*
FROM (
  SELECT *
  FROM tutorial.sf_crime_incidents_2014_01
  WHERE day_of_week = 'Friday'
) AS sub
WHERE sub.resolution = 'NONE';
</code>```

Title: sql subqueries explained

Body:
SELECT sub.*
FROM (
     SELECT *
     FROM tutorial.sf_crime_incidents_2014_01
     WHERE day_of_week = 'Friday'
     ) sub
WHERE sub.resolution = 'NONE'

This subquery is not mine, it is from a tutorial website. I just want to clear the idea of the subquery, so first, the inner query is done and then the answer becomes in the alias name sub. Then the outer query takes the answer and selects all columns matching this answer with a where condition.Is this how it works?

Thank you for the help.

Body:
Conceptually, this is how it works.

However, you need to be aware that you can not use subqueries to force the RDBMS (MySQL, PostgreSQL or any other) to perform the operations in the order you described. The RDBMS will chose itself how it will execute the query through what is called a query plan.

For example, the following query expresses exactly the same as your query :

SELECT *
FROM tutorial.sf_crime_incidents_2014_01
WHERE day_of_week = 'Friday' AND sub.resolution = 'NONE';

And the optimizer is typically able to determine that your query can be simplified (I guess you'll agree that the above query is simpler than yours).

Note that it is more readable to pad the subqueries to distinguish easily what is the subquery and what is the main query :

SELECT sub.*
FROM (
  SELECT *
  FROM tutorial.sf_crime_incidents_2014_01
  WHERE day_of_week = 'Friday'
) AS sub
WHERE sub.resolution = 'NONE';


来源: stackexchange

问:
How to display javascript alert without reset form
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

```<code>if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
</code>```

I also tried the one below but still the same thing happened:

```<code>if($pwd != $pwd2) {
    ?>
    <script type="text/javascript">
        alert("Password does not match!");
    </script>
    <?php
}
</code>```

答:
Your validation is on server side, once you hit the server the form gets reset everytime, for showing validation error from server you need to pass the values to the form again with errors.
If you want to show the alert on validation error, use client side validation with jQuery or simple JS. In this way your form's values remain the same and the alert will be popped up.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

if($pwd != $pwd2) {
    echo("");
}

I also tried the one below but still the same thing happened:

if($pwd != $pwd2) {
    ?>

    <?php
}


问:
How to draw path as I move starting from my current location using Google Maps
I am trying to draw route as I move from my current location. I am facing a big problem in drawing route dynamically please help me to solve it. I am having marker at my current location in my map. As soon as I start moving I want the map to start drawing lines in the path I move. I do not have two fixed points. Can any one please provide me a solution to over come this. I have seen lot of answers in SO which draws path between two fixed points. But here only my initial point is fixed. I am able to get my current location in my app currently. I tried with the following code but getLocationManager() is resulting in error. i am using Android Studio.

Updated Code:

My Activity:

```<code>import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;
import android.widget.Toast;

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

import org.xmlpull.v1.XmlSerializer;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends FragmentActivity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "MainActivity";
    private static final long INTERVAL = 1000 * 60 * 1; //1 minute
    private static final long FASTEST_INTERVAL = 1000 * 60 * 1; // 1 minute
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private String mLastUpdateTime;
    private String city = "";
    private String country = "";
    private String area = "";
    private String title;
    private String requiredArea = "";
    private GoogleMap googleMap;
    private List<Address> addresses;

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {

            Toast.makeText(this, "Google Play Services is not available", Toast.LENGTH_LONG).show();

            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_main);
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        googleMap = fm.getMap();
        googleMap.setMyLocationEnabled(true);
        googleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {

                Toast.makeText(getApplicationContext(), "Location button has been clicked", Toast.LENGTH_LONG).show();
                return true;
            }
        });
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setAllGesturesEnabled(true);

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart fired ..............");
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            Toast.makeText(getApplicationContext(), "Google Play Services is not Available", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        addMarker();
        float accuracy = location.getAccuracy();
        Log.d("iFocus", "The amount of accuracy is " + accuracy);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Bundle extras = location.getExtras();
        Boolean has = location.hasAccuracy();
        String provider = location.getProvider();
        Long time = location.getTime();

//        Location locationB = new Location("Begur");
//        double lati = 12.8723;
//        double longi =  77.6329;
//        locationB.setLatitude(lati);
//        locationB.setLongitude(longi);
//        Float distance = location.distanceTo(locationB);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);

        int mYear = calendar.get(Calendar.YEAR);
        int mMonth = calendar.get(Calendar.MONTH) + 1;
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);

        String formattedTime = mDay + ":" + mMonth + ":" + mYear;
        Log.d("iFocus", "The name of provider is " + provider);
        Log.d("iFocus", "The value of has is " + has);
        Log.d("iFocus", "The value of extras is " + extras);
        Log.d("iFocus", "The value of Month is " + mMonth);
        Log.d("iFocus", "The value of Day is " + mDay);
        Log.d("iFocus", "The value of Year is " + mYear);
        Log.d("iFocus", "The value of Time is " + formattedTime);
        //Log.d("iFocus", "The value of distance is "+distance);

        LatLng latLng = new LatLng(latitude, longitude);

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String cityName = addresses.get(0).getAddressLine(0);
        String stateName = addresses.get(0).getAddressLine(1);
        String countryName = addresses.get(0).getAddressLine(2);

        String[] splittedStateName = stateName.split(",");
        requiredArea = splittedStateName[2];
        Log.d("iFocus", "The value of required area is " + requiredArea);

        city = addresses.get(0).getLocality();
        area = addresses.get(0).getSubLocality();
        String adminArea = addresses.get(0).getAdminArea();
        String premises = addresses.get(0).getPremises();
        String subAdminArea = addresses.get(0).getSubAdminArea();
        String featureName = addresses.get(0).getFeatureName();
        String phone = addresses.get(0).getPhone();
        country = addresses.get(0).getCountryName();
        Log.d("iFocus", "The name of city is " + city);
        Log.d("iFocus", "The name of area is " + area);
        Log.d("iFocus", "The name of country is " + country);
        Log.d("iFocus", "The value of cityName is " + cityName);
        Log.d("iFocus", "The value of StateName is " + stateName);
        Log.d("iFocus", "The value of CountryName is " + countryName);

        Toast.makeText(this, cityName + " " + stateName + " " + countryName, Toast.LENGTH_LONG).show();

        SharedPreferences sharedPreferences = getSharedPreferences("MyValues", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("CITY", cityName);
        editor.putString("STATE", stateName);
        editor.putString("COUNTRY", countryName);
        editor.commit();

        TextView mapTitle = (TextView) findViewById(R.id.textViewTitle);

        if (requiredArea != "" && city != "" && country != "") {
            title = mLastUpdateTime.concat(", " + requiredArea).concat(", " + city).concat(", " + country);
        }
        else {
            title = mLastUpdateTime.concat(", " + area).concat(", " + city).concat(", " + country);
        }
        mapTitle.setText(title);
        addMarker();// newly added

        final String xmlFile = "userData.xml";

        try {
            // FileOutputStream fos = new  FileOutputStream("userData.xml");
            FileOutputStream fos = openFileOutput(xmlFile, Context.MODE_PRIVATE);
            XmlSerializer xmlSerializer = Xml.newSerializer();
            StringWriter writer = new StringWriter();
            xmlSerializer.setOutput(writer);
            xmlSerializer.startDocument("UTF-8", true);
            xmlSerializer.startTag(null, "userData");
            xmlSerializer.startTag(null, "Time");
            xmlSerializer.text(mLastUpdateTime);
            xmlSerializer.endTag(null, "Time");
            xmlSerializer.startTag(null, "Area");
            if (requiredArea != "") {
                xmlSerializer.text(requiredArea);
            }
            else {
                xmlSerializer.text(area);
            }
            xmlSerializer.endTag(null, "Area");
            xmlSerializer.startTag(null, "City");
            xmlSerializer.text(city);
            xmlSerializer.endTag(null, "City");
            xmlSerializer.endTag(null, "userData");
            xmlSerializer.endDocument();
            xmlSerializer.flush();
            String dataWrite = writer.toString();
            fos.write(dataWrite.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String dir = getFilesDir().getAbsolutePath();
        Log.d("Pana", "The value of Dir is "+dir);

    }

    private void addMarker() {
        MarkerOptions options = new MarkerOptions();

        // following four lines requires 'Google Maps Android API Utility Library'
        // https://developers.google.com/maps/documentation/android/utility/
        // I have used this to display the time as title for location markers
        // you can safely comment the following four lines but for this info
        IconGenerator iconFactory = new IconGenerator(this);
        iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
        // options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(mLastUpdateTime + requiredArea + city)));
        options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(requiredArea + ", " + city)));
        options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
        LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
        options.position(currentLatLng);
        Marker mapMarker = googleMap.addMarker(options);
        long atTime = mCurrentLocation.getTime();
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
        String title = mLastUpdateTime.concat(", " + requiredArea).concat(", " + city).concat(", " + country);
        mapMarker.setTitle(title);

        TextView mapTitle = (TextView) findViewById(R.id.textViewTitle);
        mapTitle.setText(title);

        Log.d(TAG, "Marker added.............................");
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
                13));
        Log.d(TAG, "Zoom done.............................");
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
}
</code>```

I am trying to add this method in my code to draw line but its giving error in getLocationManager();

```<code>private void addLocationListener(LocationListener locationListener) {
    LocationProvider locationProvider = getLocationManager().getProvider(LocationManager.GPS_PROVIDER);
    getLocationManager().requestLocationUpdates(locationProvider.getName(), LOCATION_UPDATE_INTERVAL,
                LOCATION_UPDATE_MIN_DISTANCE, locationListener);
}

private LocationManager getLocationManager() {
    return (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}

private void startGpsListening(Location start) {
    this.startLocation = start;
    addLocationListener(new MyLocationListener());
}

private Location startLocation = new Location("");

private class MyLocationListener extends LocationListener {

    public void onLocationChanged(Location location) {

    }
    ...
}
</code>```

答:
I know it's pretty late for an answer, but I'll post this here for those still have the same problem.

If you want to move a marker or/and a Polyline, you don't need to remove/clear and draw again, instead you have to add PolylineOptions once and than set the new points afterwards.

Example Code:

```<code>boolean isPolyAdded = false;
</code>```

Add this line of the code:

```<code>if (isPolyLoaded == false){
        polyline = map.addPolyline(lineOptions);
        isPolyLoaded = true;
    }else{
        polyline.setPoints(points);
    }
</code>```

to the and of onPostExecute method

Final Code:

```<code> @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(7);
            lineOptions.color(Color.BLACK);
        }

        // Drawing polyline in the Google Map for the i-th route

        if (isPolyLoaded == false){
            polyline = map.addPolyline(lineOptions);
            isPolyLoaded = true;
        }else{
            polyline.setPoints(points);
        }

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to draw route as I move from my current location. I am facing a big problem in drawing route dynamically please help me to solve it. I am having marker at my current location in my map. As soon as I start moving I want the map to start drawing lines in the path I move. I do not have two fixed points. Can any one please provide me a solution to over come this. I have seen lot of answers in SO which draws path between two fixed points. But here only my initial point is fixed. I am able to get my current location in my app currently. I tried with the following code but getLocationManager() is resulting in error. i am using Android Studio.

Updated Code:

My Activity:

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.Xml;
import android.widget.TextView;
import android.widget.Toast;

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

import org.xmlpull.v1.XmlSerializer;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends FragmentActivity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "MainActivity";
    private static final long INTERVAL = 1000 * 60 * 1; //1 minute
    private static final long FASTEST_INTERVAL = 1000 * 60 * 1; // 1 minute
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private String mLastUpdateTime;
    private String city = "";
    private String country = "";
    private String area = "";
    private String title;
    private String requiredArea = "";
    private GoogleMap googleMap;
    private List<Address> addresses;

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {

            Toast.makeText(this, "Google Play Services is not available", Toast.LENGTH_LONG).show();

            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_main);
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        googleMap = fm.getMap();
        googleMap.setMyLocationEnabled(true);
        googleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {

                Toast.makeText(getApplicationContext(), "Location button has been clicked", Toast.LENGTH_LONG).show();
                return true;
            }
        });
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setAllGesturesEnabled(true);

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart fired ..............");
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            Toast.makeText(getApplicationContext(), "Google Play Services is not Available", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        addMarker();
        float accuracy = location.getAccuracy();
        Log.d("iFocus", "The amount of accuracy is " + accuracy);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Bundle extras = location.getExtras();
        Boolean has = location.hasAccuracy();
        String provider = location.getProvider();
        Long time = location.getTime();

//        Location locationB = new Location("Begur");
//        double lati = 12.8723;
//        double longi =  77.6329;
//        locationB.setLatitude(lati);
//        locationB.setLongitude(longi);
//        Float distance = location.distanceTo(locationB);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);

        int mYear = calendar.get(Calendar.YEAR);
        int mMonth = calendar.get(Calendar.MONTH) + 1;
        int mDay = calendar.get(Calendar.DAY_OF_MONTH);

        String formattedTime = mDay + ":" + mMonth + ":" + mYear;
        Log.d("iFocus", "The name of provider is " + provider);
        Log.d("iFocus", "The value of has is " + has);
        Log.d("iFocus", "The value of extras is " + extras);
        Log.d("iFocus", "The value of Month is " + mMonth);
        Log.d("iFocus", "The value of Day is " + mDay);
        Log.d("iFocus", "The value of Year is " + mYear);
        Log.d("iFocus", "The value of Time is " + formattedTime);
        //Log.d("iFocus", "The value of distance is "+distance);

        LatLng latLng = new LatLng(latitude, longitude);

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String cityName = addresses.get(0).getAddressLine(0);
        String stateName = addresses.get(0).getAddressLine(1);
        String countryName = addresses.get(0).getAddressLine(2);

        String[] splittedStateName = stateName.split(",");
        requiredArea = splittedStateName[2];
        Log.d("iFocus", "The value of required area is " + requiredArea);

        city = addresses.get(0).getLocality();
        area = addresses.get(0).getSubLocality();
        String adminArea = addresses.get(0).getAdminArea();
        String premises = addresses.get(0).getPremises();
        String subAdminArea = addresses.get(0).getSubAdminArea();
        String featureName = addresses.get(0).getFeatureName();
        String phone = addresses.get(0).getPhone();
        country = addresses.get(0).getCountryName();
        Log.d("iFocus", "The name of city is " + city);
        Log.d("iFocus", "The name of area is " + area);
        Log.d("iFocus", "The name of country is " + country);
        Log.d("iFocus", "The value of cityName is " + cityName);
        Log.d("iFocus", "The value of StateName is " + stateName);
        Log.d("iFocus", "The value of CountryName is " + countryName);

        Toast.makeText(this, cityName + " " + stateName + " " + countryName, Toast.LENGTH_LONG).show();

        SharedPreferences sharedPreferences = getSharedPreferences("MyValues", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("CITY", cityName);
        editor.putString("STATE", stateName);
        editor.putString("COUNTRY", countryName);
        editor.commit();

        TextView mapTitle = (TextView) findViewById(R.id.textViewTitle);

        if (requiredArea != "" && city != "" && country != "") {
            title = mLastUpdateTime.concat(", " + requiredArea).concat(", " + city).concat(", " + country);
        }
        else {
            title = mLastUpdateTime.concat(", " + area).concat(", " + city).concat(", " + country);
        }
        mapTitle.setText(title);
        addMarker();// newly added

        final String xmlFile = "userData.xml";

        try {
            // FileOutputStream fos = new  FileOutputStream("userData.xml");
            FileOutputStream fos = openFileOutput(xmlFile, Context.MODE_PRIVATE);
            XmlSerializer xmlSerializer = Xml.newSerializer();
            StringWriter writer = new StringWriter();
            xmlSerializer.setOutput(writer);
            xmlSerializer.startDocument("UTF-8", true);
            xmlSerializer.startTag(null, "userData");
            xmlSerializer.startTag(null, "Time");
            xmlSerializer.text(mLastUpdateTime);
            xmlSerializer.endTag(null, "Time");
            xmlSerializer.startTag(null, "Area");
            if (requiredArea != "") {
                xmlSerializer.text(requiredArea);
            }
            else {
                xmlSerializer.text(area);
            }
            xmlSerializer.endTag(null, "Area");
            xmlSerializer.startTag(null, "City");
            xmlSerializer.text(city);
            xmlSerializer.endTag(null, "City");
            xmlSerializer.endTag(null, "userData");
            xmlSerializer.endDocument();
            xmlSerializer.flush();
            String dataWrite = writer.toString();
            fos.write(dataWrite.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String dir = getFilesDir().getAbsolutePath();
        Log.d("Pana", "The value of Dir is "+dir);

    }

    private void addMarker() {
        MarkerOptions options = new MarkerOptions();

        // following four lines requires 'Google Maps Android API Utility Library'
        // https://developers.google.com/maps/documentation/android/utility/
        // I have used this to display the time as title for location markers
        // you can safely comment the following four lines but for this info
        IconGenerator iconFactory = new IconGenerator(this);
        iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
        // options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(mLastUpdateTime + requiredArea + city)));
        options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(requiredArea + ", " + city)));
        options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
        LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
        options.position(currentLatLng);
        Marker mapMarker = googleMap.addMarker(options);
        long atTime = mCurrentLocation.getTime();
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
        String title = mLastUpdateTime.concat(", " + requiredArea).concat(", " + city).concat(", " + country);
        mapMarker.setTitle(title);

        TextView mapTitle = (TextView) findViewById(R.id.textViewTitle);
        mapTitle.setText(title);

        Log.d(TAG, "Marker added.............................");
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
                13));
        Log.d(TAG, "Zoom done.............................");
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
}

I am trying to add this method in my code to draw line but its giving error in getLocationManager();

private void addLocationListener(LocationListener locationListener) {
    LocationProvider locationProvider = getLocationManager().getProvider(LocationManager.GPS_PROVIDER);
    getLocationManager().requestLocationUpdates(locationProvider.getName(), LOCATION_UPDATE_INTERVAL,
                LOCATION_UPDATE_MIN_DISTANCE, locationListener);
}

private LocationManager getLocationManager() {
    return (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}

private void startGpsListening(Location start) {
    this.startLocation = start;
    addLocationListener(new MyLocationListener());
}

private Location startLocation = new Location("");

private class MyLocationListener extends LocationListener {

    public void onLocationChanged(Location location) {

    }
    ...
}

Body:
I know it's pretty late for an answer, but I'll post this here for those still have the same problem.

If you want to move a marker or/and a Polyline, you don't need to remove/clear and draw again, instead you have to add PolylineOptions once and than set the new points afterwards.

Example Code:

boolean isPolyAdded = false;

Add this line of the code:

if (isPolyLoaded == false){
        polyline = map.addPolyline(lineOptions);
        isPolyLoaded = true;
    }else{
        polyline.setPoints(points);
    }

to the and of onPostExecute method

Final Code:

 @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {

        // Traversing through all the routes
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(7);
            lineOptions.color(Color.BLACK);
        }

        // Drawing polyline in the Google Map for the i-th route

        if (isPolyLoaded == false){
            polyline = map.addPolyline(lineOptions);
            isPolyLoaded = true;
        }else{
            polyline.setPoints(points);
        }

    }
}


问:
Property 'auth' does not exist on type 'AngularFireModule'
Im Using Angular 4 and Firebase to authentication. I'm getting the error " Property 'auth' does not exist on type 'AngularFireModule'."

The Code is as follows

```<code>import { AngularFireModule} from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css'],
 animations: [moveIn()],
 host: {'[@moveIn]': ''}
})

export class LoginComponent implements OnInit {
error: any;
constructor(public af: AngularFireModule,private router: Router) {
  this.af.auth.subscribe(auth => {
  if(auth) {
    this.router.navigateByUrl('/members');
  }
});

loginFb() {
this.af.auth.login({
  provider: AuthProviders.Facebook,
  method: AuthMethods.Popup,
}).then(
    (success) => {
    this.router.navigate(['/members']);
  }).catch(
    (err) => {
    this.error = err;
  })
  }
   }
</code>```

The version information :
    "@angular/router": "^4.0.0",

```<code>"angularfire2": "^4.0.0-rc.1",

"core-js": "^2.4.1",

"firebase": "^4.1.3",

"rxjs": "^5.1.0",

"zone.js": "^0.8.4"
</code>```

UPDATE:

This worked

```<code>constructor(public af: AngularFireAuth,private router: Router) {
      this.af.authState.subscribe(auth => {
      if(auth) {
        this.router.navigateByUrl('/members');
      }
</code>```

答:
The database and auth are now separated modules, AngularFireAuth and AngularFireDatabase

So in your constructor, you should do this

```<code> constructor(private router: Router, public af: AngularFireAuth
  ) { ...    }
</code>```

Another is if you are just using the FireAuthModule, you can remove the 2 other imports (  AngularFireModule and AngularFireDatabaseModule )

Body:
Im Using Angular 4 and Firebase to authentication. I'm getting the error " Property 'auth' does not exist on type 'AngularFireModule'."

The Code is as follows

import { AngularFireModule} from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule } from 'angularfire2/database';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css'],
 animations: [moveIn()],
 host: {'[@moveIn]': ''}
})

export class LoginComponent implements OnInit {
error: any;
constructor(public af: AngularFireModule,private router: Router) {
  this.af.auth.subscribe(auth => {
  if(auth) {
    this.router.navigateByUrl('/members');
  }
});

loginFb() {
this.af.auth.login({
  provider: AuthProviders.Facebook,
  method: AuthMethods.Popup,
}).then(
    (success) => {
    this.router.navigate(['/members']);
  }).catch(
    (err) => {
    this.error = err;
  })
  }
   }

The version information :
    "@angular/router": "^4.0.0",

"angularfire2": "^4.0.0-rc.1",

"core-js": "^2.4.1",

"firebase": "^4.1.3",

"rxjs": "^5.1.0",

"zone.js": "^0.8.4"

UPDATE:

This worked

constructor(public af: AngularFireAuth,private router: Router) {
      this.af.authState.subscribe(auth => {
      if(auth) {
        this.router.navigateByUrl('/members');
      }

Body:
The database and auth are now separated modules, AngularFireAuth and AngularFireDatabase

So in your constructor, you should do this

 constructor(private router: Router, public af: AngularFireAuth
  ) { ...    }

Another is if you are just using the FireAuthModule, you can remove the 2 other imports (  AngularFireModule and AngularFireDatabaseModule )


问:
How to increase 2MB limit on AJAX JSON response w/ ASP.NET MVC
I am having problems making an AJAX call when the response is over 2MB.  Anything with a response under 2MB works fine.  When the response is over 2MB, my "success" method never gets called.

My application is ASP.NET MVC2.  I am making the call using the jQuery AJAX call:

```<code>$.ajax({
    type: "post",
    data: ajaxData,
    url: ajaxUrl,
    success: updateItems,
    cache: false
});
</code>```

In my controller, I am using the Json() action result method:

```<code>public ActionResult GetItems(....)
{
    ...
    return Json(packet);
}
</code>```

When I watch the call in Fiddler it comes back with a HTTP 500 response.

I tried setting the maxJsonLength in the Web.config file as shown here, but that doesn't seem to make any difference.

Any suggestions on how to allow a response over 2MB?

Thanks in advance,

Skip

答:
I am not sure if you are running your own server or if you are on a hosted solution, however, we recently ran into this but with a 30MB limit. Anything greater would not fire success methods. So if you are on a shared host this setting might have been set to 2MB for you.

We fixed this by changing the maxAllowedContentLength as described here:
http://www.webtrenches.com/post.cfm/iis7-file-upload-size-limits

ContentLicense: CC BY-SA 2.5

Body:
I am having problems making an AJAX call when the response is over 2MB.  Anything with a response under 2MB works fine.  When the response is over 2MB, my "success" method never gets called.

My application is ASP.NET MVC2.  I am making the call using the jQuery AJAX call:

$.ajax({
    type: "post",
    data: ajaxData,
    url: ajaxUrl,
    success: updateItems,
    cache: false
});

In my controller, I am using the Json() action result method:

public ActionResult GetItems(....)
{
    ...
    return Json(packet);
}

When I watch the call in Fiddler it comes back with a HTTP 500 response.

I tried setting the maxJsonLength in the Web.config file as shown here, but that doesn't seem to make any difference.

Any suggestions on how to allow a response over 2MB?

Thanks in advance,

Skip


问:
jquery validation number error
i want to validate a input using jQuery it must accept only alphabets the code is working numbers in keyboard are not allowed but numpad numbers are typing what can do with this

```<code>$("#fname").keydown(function(event) {
   var keyentered = event.keyCode || event.which;
   keyentered = String.fromCharCode(keyentered);
   var pattern = /[a-zA-Z]+|[\b]+$/;
   if(!pattern.test(keyentered)){
     event.returnValue = false;
     if(event.preventDefault) event.preventDefault();
   }
});
</code>```

this is my code it must not accept any special char and numbers but it is accepting numbers from numpad and not accept number which is in keyboard above alphabets i want know why and how to resolve this.

Need Help!

答:
This should work fine. below code will only allow alphabet to enter in textbox using jQuery.</p>

```<code>$("#fname").keydown(function (e) {
    // Allow backspace, delete,
    // Allow select all the alphabet entered in textbox using Ctrl+A or Command+A
    // Allow: home, end, left, right, down and up to navigate in textbox if any changes want to do
    if ($.inArray(e.keyCode, [8, 46]) !== -1 ||
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
            (e.keyCode >= 35 && e.keyCode <= 40)) {
        return;
    }
    // Below code is to only allow alphabet and stop propogation on entering other char
    if ((e.shiftKey || (e.keyCode < 65 || e.keyCode > 90)) && (e.keyCode < 65 || e.keyCode > 90)) {
        e.preventDefault();
    }
});
</code>```

Title: jquery validation number error

Body:
i want to validate a input using jQuery it must accept only alphabets the code is working numbers in keyboard are not allowed but numpad numbers are typing what can do with this

$("#fname").keydown(function(event) {
   var keyentered = event.keyCode || event.which;
   keyentered = String.fromCharCode(keyentered);
   var pattern = /[a-zA-Z]+|[\b]+$/;
   if(!pattern.test(keyentered)){
     event.returnValue = false;
     if(event.preventDefault) event.preventDefault();
   }
});

this is my code it must not accept any special char and numbers but it is accepting numbers from numpad and not accept number which is in keyboard above alphabets i want know why and how to resolve this.

Need Help!

Body:
This should work fine. below code will only allow alphabet to enter in textbox using jQuery.

$("#fname").keydown(function (e) {
    // Allow backspace, delete,
    // Allow select all the alphabet entered in textbox using Ctrl+A or Command+A
    // Allow: home, end, left, right, down and up to navigate in textbox if any changes want to do
    if ($.inArray(e.keyCode, [8, 46]) !== -1 ||
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
            (e.keyCode >= 35 && e.keyCode <= 40)) {
        return;
    }
    // Below code is to only allow alphabet and stop propogation on entering other char
    if ((e.shiftKey || (e.keyCode < 65 || e.keyCode > 90)) && (e.keyCode < 65 || e.keyCode > 90)) {
        e.preventDefault();
    }
});


问:
ember filter on promised inside a model
i have two models:
User:

```<code>export default DS.Model.extend({
  books: hasMany('book', { async: true }),
});
</code>```

book:

```<code>export default DS.Model.extend({
  title: DS.attr('string'),
  state: DS.attr('number'),
});
</code>```

in my of my controller i am getting one user as my model and i want to create a computed property like this

```<code>  activeBooks: Ember.computed('model.books', function() {
    var books = this.get('model.books').filter(function (book, index, array) {
      // debugger;
      return (this.get('book.state') === 1);
    }.bind(this));
    return books;
  }),
</code>```

but the filter is not working and basically return a empty array.
P.S 1. i am side loading books alone with user. and at the debugger line i query for this.get('user.books.length')  i get the correct number of books for each user. could someone point out what i am doing wrong here?
thanks a lot!

答:
You can use filterBy and return the result.

```<code>activeBooks:Ember.computed('model.books', function() {
 return this.get('model.books').filterBy('state',1);
})
</code>```

You don't need to use bind(this) inside filter function.

Title: ember filter on promised inside a model

Body:
i have two models:
User:

export default DS.Model.extend({
  books: hasMany('book', { async: true }),
});

book:

export default DS.Model.extend({
  title: DS.attr('string'),
  state: DS.attr('number'),
});

in my of my controller i am getting one user as my model and i want to create a computed property like this

  activeBooks: Ember.computed('model.books', function() {
    var books = this.get('model.books').filter(function (book, index, array) {
      // debugger;
      return (this.get('book.state') === 1);
    }.bind(this));
    return books;
  }),

but the filter is not working and basically return a empty array.
P.S 1. i am side loading books alone with user. and at the debugger line i query for this.get('user.books.length')  i get the correct number of books for each user. could someone point out what i am doing wrong here?
thanks a lot!

Body:
You can use filterBy and return the result.

activeBooks:Ember.computed('model.books', function() {
 return this.get('model.books').filterBy('state',1);
})

You don't need to use bind(this) inside filter function.


问:
How to get the accurate time position of a live streaming in avplayer
I'm using AVPlayer to play a live streaming. This stream supports one hour catch-up which means user can seek to one hour ago and play. But I have one question how do I know the accurate position that the player is playing. I need to display current position on the player view. For example,if user is playing half an hour ago then display -30:00; if user is playing the latest content, the player will show 00:00 or live. Thanks</p>

答:
Swift solution :</p>

```<code>   override func getLiveDuration() -> Float {
    var result : Float = 0.0;

    if let items = player.currentItem?.seekableTimeRanges {

        if(!items.isEmpty) {
            let range = items[items.count - 1]
            let timeRange = range.timeRangeValue
            let startSeconds = CMTimeGetSeconds(timeRange.start)
            let durationSeconds = CMTimeGetSeconds(timeRange.duration)

            result = Float(startSeconds + durationSeconds)
        }

    }
    return result;
}
</code>```

Body:
Swift solution :

   override func getLiveDuration() -> Float {
    var result : Float = 0.0;

    if let items = player.currentItem?.seekableTimeRanges {

        if(!items.isEmpty) {
            let range = items[items.count - 1]
            let timeRange = range.timeRangeValue
            let startSeconds = CMTimeGetSeconds(timeRange.start)
            let durationSeconds = CMTimeGetSeconds(timeRange.duration)

            result = Float(startSeconds + durationSeconds)
        }

    }
    return result;
}


问:
How to load multiple textures into the fragment shader
So I'm trying to texture an object in OpenGL and I have two textures that I want to mix together in the fragment shader (rock.tga and grass.tga). My fragment shader:

```<code>out vec3 color;

in vec2 uv;

uniform sampler2D grasstexture;
uniform sampler2D rocktexture;
</code>```

To load a sampler2D texture here's what I did in my header file in C++:

```<code>OpenGP::EigenImage<vec3> image;
OpenGP::imread("grass.tga", image);

glGenTextures(0, &_tex);
glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "grasstexture");
glUniform1i(tex_id, 0);
</code>```

Which loads the grass texture into my fragment shader. Now what I want to know is how do I load in multiple textures. I can't copy the above code twice because one texture is always over-written by the other. So how can I load in multiple textures into the fragment shader?

EDIT: Here's where my _tex is declared:

```<code>    class Mesh{
    protected:
        GLuint _tex;

        GLuint _vpoint;    ///< memory buffer
        GLuint _vnormal;   ///< memory buffer

    public:
        GLuint getProgramID(){ return _pid; }

        void init(){
//code for the textures goes in here
</code>```

Here's my updated code:

```<code>OpenGP::EigenImage<vec3> image;
glActiveTexture(GL_TEXTURE0);
OpenGP::imread("grass.tga", image);

//glGenTextures(1, &_tex);
glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "grasstexture");
glUniform1i(tex_id, 0);

glActiveTexture(GL_TEXTURE1);
OpenGP::imread("rock.tga", image);

//glGenTextures(0, &_tex);

glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "rocktexture");
glUniform1i(tex_id, 1);
</code>```

答:
Opengl hides a lot of its context so you need to keep it in mind. You have three parts of the texture:

Texture name - just an integer, pass it around.

Active texture unit - context thing, set with GL_TEXTURE0...

Texture target - for starters GL_TEXTURE_2D is all you need.

Here is what you need to do in order to get a 2d texture working:

Create opengl texture name with glGenTextures

Set up the texture with following set of actions:

2.1 Set active texture unit with glActiveTexture

2.2 Specify the target of the active texture unit to which the named texture is bound glBindTexture. For this all three texture parts should be "under control".

2.3 Specify a two-dimensional texture image for the active texture unit with glTexImage2D

2.4 Set parameters for the active texture unit with glTexParameteri

In order to simultaneously use multiple textures make sure that they have unique name and texture unit:

3.1 Set active texture unit to 0

3.2 Bind one named texture to active texture unit

3.3 Pass texture unit (0) to shader

3.4 Set active texture unit to 1

3.5 Bind another named texture to active texture unit

3.6 Pass texture unit (1) to shader

...

And when you're done don't forget to delete all named textures with glDeleteTextures

The order of commands is not the only one possible and the set of commands is not minimal - it is just typical.

Original answer:

You need to set next active texture like this:

```<code> glActiveTexture(GL_TEXTURE1);
</code>```

before you bind bind the next texture.
It will also work like:

```<code>std::vector<std::string> textures = {"grass.tga", "rock.tga"};
for(int i = 0; i < textures.size(); i++) {
    glActiveTexture(GL_TEXTURE0 + i);
    // create the texture
}
</code>```

Body:
So I'm trying to texture an object in OpenGL and I have two textures that I want to mix together in the fragment shader (rock.tga and grass.tga). My fragment shader:

out vec3 color;

in vec2 uv;

uniform sampler2D grasstexture;
uniform sampler2D rocktexture;

To load a sampler2D texture here's what I did in my header file in C++:

OpenGP::EigenImage<vec3> image;
OpenGP::imread("grass.tga", image);

glGenTextures(0, &_tex);
glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "grasstexture");
glUniform1i(tex_id, 0);

Which loads the grass texture into my fragment shader. Now what I want to know is how do I load in multiple textures. I can't copy the above code twice because one texture is always over-written by the other. So how can I load in multiple textures into the fragment shader?

EDIT: Here's where my _tex is declared:

    class Mesh{
    protected:
        GLuint _tex;

        GLuint _vpoint;    ///< memory buffer
        GLuint _vnormal;   ///< memory buffer

    public:
        GLuint getProgramID(){ return _pid; }

        void init(){
//code for the textures goes in here

Here's my updated code:

OpenGP::EigenImage<vec3> image;
glActiveTexture(GL_TEXTURE0);
OpenGP::imread("grass.tga", image);

//glGenTextures(1, &_tex);
glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "grasstexture");
glUniform1i(tex_id, 0);

glActiveTexture(GL_TEXTURE1);
OpenGP::imread("rock.tga", image);

//glGenTextures(0, &_tex);

glBindTexture(GL_TEXTURE_2D, _tex);

check_error_gl();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error_gl();
glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB32F,
             image.cols(), image.rows(), 0,
             GL_RGB, GL_FLOAT, image.data());
check_error_gl();
tex_id = glGetUniformLocation(_pid, "rocktexture");
glUniform1i(tex_id, 1);

Body:
Opengl hides a lot of its context so you need to keep it in mind. You have three parts of the texture:

Texture name - just an integer, pass it around.

Active texture unit - context thing, set with GL_TEXTURE0...

Texture target - for starters GL_TEXTURE_2D is all you need.

Here is what you need to do in order to get a 2d texture working:

Create opengl texture name with glGenTextures

Set up the texture with following set of actions:

2.1 Set active texture unit with glActiveTexture

2.2 Specify the target of the active texture unit to which the named texture is bound glBindTexture. For this all three texture parts should be "under control".

2.3 Specify a two-dimensional texture image for the active texture unit with glTexImage2D

2.4 Set parameters for the active texture unit with glTexParameteri

In order to simultaneously use multiple textures make sure that they have unique name and texture unit:

3.1 Set active texture unit to 0

3.2 Bind one named texture to active texture unit

3.3 Pass texture unit (0) to shader

3.4 Set active texture unit to 1

3.5 Bind another named texture to active texture unit

3.6 Pass texture unit (1) to shader

...

And when you're done don't forget to delete all named textures with glDeleteTextures

The order of commands is not the only one possible and the set of commands is not minimal - it is just typical.

Original answer:

You need to set next active texture like this:

 glActiveTexture(GL_TEXTURE1);

before you bind bind the next texture.
It will also work like:

std::vector<std::string> textures = {"grass.tga", "rock.tga"};
for(int i = 0; i < textures.size(); i++) {
    glActiveTexture(GL_TEXTURE0 + i);
    // create the texture
}


问:
CentOs - Tomcat - Angular2 - Encoding UTF-8
I have a SpringBoot Angular app deployed in a Tomcat which is in a CentOs server.

CentOs locale :

```<code>LANG=fr_FR.UTF-8
LC_CTYPE="fr_FR.UTF-8"
LC_NUMERIC="fr_FR.UTF-8"
LC_TIME="fr_FR.UTF-8"
LC_COLLATE="fr_FR.UTF-8"
LC_MONETARY="fr_FR.UTF-8"
LC_MESSAGES="fr_FR.UTF-8"
LC_PAPER="fr_FR.UTF-8"
LC_NAME="fr_FR.UTF-8"
LC_ADDRESS="fr_FR.UTF-8"
LC_TELEPHONE="fr_FR.UTF-8"
LC_MEASUREMENT="fr_FR.UTF-8"
LC_IDENTIFICATION="fr_FR.UTF-8"
LC_ALL=
</code>```

In the Tomcat's catalina.sh sript, I have the following config :

```<code>CATALINA_OPTS="$CATALINA_OPTS -Dfile.encoding='UTF-8'"
</code>```

In the index.html of the Angular app :

```<code><meta charset="utf-8">
</code>```

In the pom.xml of the parent project :

```<code><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</code>```

All files are encoded in UTF-8

With all that some characters are not well displayed :

```<code>é -> Ã©
à -> Ã¨
° -> Â°
...
</code>```

However, the characters from the database are well displayed (the database is encoded in ANSI)

Does anyone have an idea where is my mistake ?

答:
Problem was resolved adding the charset to the js and html mime types into the tomcat's web.xml :</p>

```<code><mime-mapping>
    <extension>html</extension>
    <mime-type>text/html;charset=UTF-8</mime-type>
</mime-mapping>

<mime-mapping>
    <extension>js</extension>
    <mime-type>text/javascript;charset=utf-8</mime-type>
</mime-mapping>
</code>```

Body:
I have a SpringBoot Angular app deployed in a Tomcat which is in a CentOs server.

CentOs locale :

LANG=fr_FR.UTF-8
LC_CTYPE="fr_FR.UTF-8"
LC_NUMERIC="fr_FR.UTF-8"
LC_TIME="fr_FR.UTF-8"
LC_COLLATE="fr_FR.UTF-8"
LC_MONETARY="fr_FR.UTF-8"
LC_MESSAGES="fr_FR.UTF-8"
LC_PAPER="fr_FR.UTF-8"
LC_NAME="fr_FR.UTF-8"
LC_ADDRESS="fr_FR.UTF-8"
LC_TELEPHONE="fr_FR.UTF-8"
LC_MEASUREMENT="fr_FR.UTF-8"
LC_IDENTIFICATION="fr_FR.UTF-8"
LC_ALL=

In the Tomcat's catalina.sh sript, I have the following config :

CATALINA_OPTS="$CATALINA_OPTS -Dfile.encoding='UTF-8'"

In the index.html of the Angular app :

<meta charset="utf-8">

In the pom.xml of the parent project :

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

All files are encoded in UTF-8

With all that some characters are not well displayed :

é -> Ã©
à -> Ã¨
° -> Â°
...

However, the characters from the database are well displayed (the database is encoded in ANSI)

Does anyone have an idea where is my mistake ?

Body:
Problem was resolved adding the charset to the js and html mime types into the tomcat's web.xml :

<mime-mapping>
    <extension>html</extension>
    <mime-type>text/html;charset=UTF-8</mime-type>
</mime-mapping>

<mime-mapping>
    <extension>js</extension>
    <mime-type>text/javascript;charset=utf-8</mime-type>
</mime-mapping>


问:
How to set UICollectionViewCell Width and Height programmatically
I am trying to implement a CollectionView.
When I am using Autolayout, my cells won't change the size, but their alignment.

Now I would rather want to change their sizes to e.g.

```<code>var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)
</code>```

I tried setting in my CellForItemAtIndexPath

```<code>collectionCell.size = size
</code>```

it didn't work though.

Is there a way to achieve this?

edit:

It seems, that the answers will only change my CollectionView width and height itself. Is there are conflict in Constraints possible? Any ideas on that ?

答:
This is my version, find your suitable ratio to get the cell size as per your requirement.</p>

```<code>- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4);
}
</code>```

Body:
I am trying to implement a CollectionView.
When I am using Autolayout, my cells won't change the size, but their alignment.

Now I would rather want to change their sizes to e.g.

var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)

I tried setting in my CellForItemAtIndexPath

collectionCell.size = size

it didn't work though.

Is there a way to achieve this?

edit:

It seems, that the answers will only change my CollectionView width and height itself. Is there are conflict in Constraints possible? Any ideas on that ?

Body:
This is my version, find your suitable ratio to get the cell size as per your requirement.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4);
}


答: Yes. It will work if sub.resolution column exists in tutorial.sf_crime_incidents_2014_01  table

Title: sql subqueries explained

Body:
SELECT sub.*
FROM (
     SELECT *
     FROM tutorial.sf_crime_incidents_2014_01
     WHERE day_of_week = 'Friday'
     ) sub
WHERE sub.resolution = 'NONE'

This subquery is not mine, it is from a tutorial website. I just want to clear the idea of the subquery, so first, the inner query is done and then the answer becomes in the alias name sub. Then the outer query takes the answer and selects all columns matching this answer with a where condition.Is this how it works?

Thank you for the help.


问:
C++ Solving Diamond Inheritance Without Virtual Inheritance
I have the following diamond class structure that does not compile:

```<code>class Base{
  int a;
public:
  virtual void doSomething();
};

class NotMineToTouch : public Base {};

class MyParentClass : public Base {};

class EvilDiamond : public NotMineToTouch, public MyParentClass {};

// I need these methods (that I cannot necessarily edit) to work for an EvilDiamond
void processBase (Base* b) { b->doSomething; /*...*/} // Cannot edit

void processParent (MyParentClass* p) { p->doSomething; /*...*/} // Can edit

void processNotMine (NotMineToTouch* n) { n->doSomething; /*...*/} // Cannot edit
</code>```

I know the normal solution is to inherit virtually from Base; however, I am not allowed to change NotMineToTouch (or Base).  Is there another solution?  I am allowed to change MyParentClass and EvilDiamond at my pleasure; however, EvilDiamond must inherit from MyParentClass and NotMineToTouch, and MyParentClass must inherit from Base and may not inherit from EvilDiamond.

答:
I challenge the following assertion:

EvilDiamond must inherit from MyParentClass and NotMineToTouch

You can probably do something along these lines (depending on your architecture):

```<code>class EvilDiamond;

class NotMineToTouchImpl : public NotMineToTouch {
  EvilDiamond* tgt_;
public:
  NotMineToTouchImpl(EvilDiamond* tgt) : tgt_(tgt) {}

  ... implement NotMineToTouch here, using tgt_ where you would have used this
};

class MyParentClassImpl : public MyParentClass {
  EvilDiamond* tgt_;
public:
  MyParentClassImpl(EvilDiamond* tgt) : tgt_(tgt) {}

  ... implement Base here, using tgt_ where you would have used this
};

class EvilDiamond {
  friend class NotMineToTouchImpl;
  friend class MyParentClassImpl;

  // Creating permanent instances of the API classes
  // may or may not be appropriate in your case.
  NotMineToTouchImpl nmti_;
  MyParentClassImpl pci_;
public:
  EvilDiamond () : nmti_(this), pci_(this) {}

  NotMineToTouchImpl* getAsNotMineToTOuch() {return &nmti_;}
  MyParentClassImpl * getAsParentClass() {return &pci_;}
};
</code>```

Body:
I have the following diamond class structure that does not compile:

class Base{
  int a;
public:
  virtual void doSomething();
};

class NotMineToTouch : public Base {};

class MyParentClass : public Base {};

class EvilDiamond : public NotMineToTouch, public MyParentClass {};

// I need these methods (that I cannot necessarily edit) to work for an EvilDiamond
void processBase (Base* b) { b->doSomething; /*...*/} // Cannot edit

void processParent (MyParentClass* p) { p->doSomething; /*...*/} // Can edit

void processNotMine (NotMineToTouch* n) { n->doSomething; /*...*/} // Cannot edit

I know the normal solution is to inherit virtually from Base; however, I am not allowed to change NotMineToTouch (or Base).  Is there another solution?  I am allowed to change MyParentClass and EvilDiamond at my pleasure; however, EvilDiamond must inherit from MyParentClass and NotMineToTouch, and MyParentClass must inherit from Base and may not inherit from EvilDiamond.

Body:
I challenge the following assertion:

EvilDiamond must inherit from MyParentClass and NotMineToTouch

You can probably do something along these lines (depending on your architecture):

class EvilDiamond;

class NotMineToTouchImpl : public NotMineToTouch {
  EvilDiamond* tgt_;
public:
  NotMineToTouchImpl(EvilDiamond* tgt) : tgt_(tgt) {}

  ... implement NotMineToTouch here, using tgt_ where you would have used this
};

class MyParentClassImpl : public MyParentClass {
  EvilDiamond* tgt_;
public:
  MyParentClassImpl(EvilDiamond* tgt) : tgt_(tgt) {}

  ... implement Base here, using tgt_ where you would have used this
};

class EvilDiamond {
  friend class NotMineToTouchImpl;
  friend class MyParentClassImpl;

  // Creating permanent instances of the API classes
  // may or may not be appropriate in your case.
  NotMineToTouchImpl nmti_;
  MyParentClassImpl pci_;
public:
  EvilDiamond () : nmti_(this), pci_(this) {}

  NotMineToTouchImpl* getAsNotMineToTOuch() {return &nmti_;}
  MyParentClassImpl * getAsParentClass() {return &pci_;}
};


问:
Adding menu options to webview in android
I have scoured the net for this solution but am thus far unsuccessful. Hopefully someone can help me. I am new and don't know java programming. From tutorials over the web, i have created a "webview" app that loads local html files. This works fine. What i'm trying to do is add the options menu by clicking the "menu" button on the phone so i can quit(exit) the app. There are many tutorials out there for this but when i try to add the code my java file, my existing code in the file start coming up with errors & then everything goes haywire. I am hoping someone can add the appropriate code to my existing code below or correct my code if it is wrong with the menu options included to quit the app. Thank you in advance.

Su

```<code>package com.xrefguide;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class XRefGuide extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView web = (WebView) findViewById(R.id.webView);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("file:///android_asset/index.html");
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        web.getSettings().setPluginsEnabled(true);
        web.getSettings().setSupportMultipleWindows(false);
        web.getSettings().setSupportZoom(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setUseWideViewPort(true);

        //Our application's main page will be loaded
        //web.loadUrl("http://mapa.org.my");

        web.setWebViewClient(new WebViewClient() {
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
    }
}
</code>```

答: There is nothing in your code that has anything whatsoever to do with an options menu. Here are two sample projects demonstrating the use of options menus and context menus, one using menu XML files, and one defining the menus purely in Java.</p>

Body:
I have scoured the net for this solution but am thus far unsuccessful. Hopefully someone can help me. I am new and don't know java programming. From tutorials over the web, i have created a "webview" app that loads local html files. This works fine. What i'm trying to do is add the options menu by clicking the "menu" button on the phone so i can quit(exit) the app. There are many tutorials out there for this but when i try to add the code my java file, my existing code in the file start coming up with errors & then everything goes haywire. I am hoping someone can add the appropriate code to my existing code below or correct my code if it is wrong with the menu options included to quit the app. Thank you in advance.

Su

package com.xrefguide;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class XRefGuide extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView web = (WebView) findViewById(R.id.webView);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("file:///android_asset/index.html");
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        web.getSettings().setPluginsEnabled(true);
        web.getSettings().setSupportMultipleWindows(false);
        web.getSettings().setSupportZoom(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setUseWideViewPort(true);

        //Our application's main page will be loaded
        //web.loadUrl("http://mapa.org.my");

        web.setWebViewClient(new WebViewClient() {
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
    }
}


问:
If isset ID inside array, get values from defined ID in same array?
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

```<code>$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.
</code>```

It's only a base, I know it don't works, any help with the code? thanks in advance.

答:
You can filter the array for what you need:

```<code>$userinfo = [
    ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
    ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
    ['id' => 1, 'name' => 'username1', 'phone' => '1111']
];

$user = null;
if (isset($_GET["id"])) {
    $found = array_filter($userinfo, function ($user) {
           return isset($user["id"]) && $user["id"] == $_GET["id"];
    }); // This will find all users with that id, in case there's more.
    $user = !empty($found)?current($found):null; //current() at this point gets the first entry in $found
}
if ($user != null) {
   echo $user["name"];
   echo $user["phone"];
}
</code>```

Check out array_filter for more detail.

Body:
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.

It's only a base, I know it don't works, any help with the code? thanks in advance.

Body:
You can filter the array for what you need:

$userinfo = [
    ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
    ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
    ['id' => 1, 'name' => 'username1', 'phone' => '1111']
];

$user = null;
if (isset($_GET["id"])) {
    $found = array_filter($userinfo, function ($user) {
           return isset($user["id"]) && $user["id"] == $_GET["id"];
    }); // This will find all users with that id, in case there's more.
    $user = !empty($found)?current($found):null; //current() at this point gets the first entry in $found
}
if ($user != null) {
   echo $user["name"];
   echo $user["phone"];
}

Check out array_filter for more detail.


问:
No 'seek_preroll' and 'codec_delay' in audio header
When SB_API_VERSION is not less than SB_AUDIO_SPECIFIC_CONFIG_AS_POINTER, 'codec private' for Opus has been passed to starboard.

But I am not very sure whether the audio sample was preprocessed with 'codec delay' and 'seek preroll', is it unnecessary for audio decoder to use those?

Thanks!

答: The Linux reference implementation supports Opus without use of the API changes for audio_specific_config. I believe it is possible to extract all the necessary metadata from the stream itself.</p>


问:
Unable to Update ProgressBar from Firebase Storage UploadTask
I'm using Angular2 and Firbase Storage. I'm trying to get the 'uploadProgress' value to update the  (specified in the HTML file) but somehow the 'uploadProgress' variable in the uploadTask.on function just can  be updated. Is it because it is running on another thread? any workaround to this problem? HOpe someone can help me. Thanks

```<code>=======================================================================
import { Component } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import * as firebase from 'firebase';

@Component({
  selector: 'app-create-folder',
  templateUrl: './create-folder.component.html'
})

 export class CreateFolderComponent {

 public fItem: FolderItem;
 public f: File;
 public storageRef: Storage;
 public uploadProgress = 0;

constructor(public af: AngularFire) {}
</code>```

onSubmit() {

```<code>const storageRef = firebase.storage().ref().child('myclient/' +
this.fItem.file_name);
var uploadTask = storageRef.put(this.f);

  uploadTask.on('state_changed', function(snapshot){
  this.uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) *
  100;

  });

 }

 }
</code>```

答:
Is it because it is running on another thread?

Because it runs in another context.

To solve problem assign this to some variable outside 'state_changed' callback function. After that you can use this variable as reference to initial this instance.

```<code>public uploadFile() {
        let self = this;
        ...
        firebaseUploadTask.on('state_changed',
            function progress(snapshot) {
                self.percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            },
            function error(error) {},
            function complete() {}
        );
    }
</code>```

Body:
I'm using Angular2 and Firbase Storage. I'm trying to get the 'uploadProgress' value to update the  (specified in the HTML file) but somehow the 'uploadProgress' variable in the uploadTask.on function just can  be updated. Is it because it is running on another thread? any workaround to this problem? HOpe someone can help me. Thanks

=======================================================================
import { Component } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import * as firebase from 'firebase';

@Component({
  selector: 'app-create-folder',
  templateUrl: './create-folder.component.html'
})

 export class CreateFolderComponent {

 public fItem: FolderItem;
 public f: File;
 public storageRef: Storage;
 public uploadProgress = 0;

constructor(public af: AngularFire) {}

onSubmit() {

const storageRef = firebase.storage().ref().child('myclient/' +
this.fItem.file_name);
var uploadTask = storageRef.put(this.f);

  uploadTask.on('state_changed', function(snapshot){
  this.uploadProgress = (snapshot.bytesTransferred / snapshot.totalBytes) *
  100;

  });

 }

 }

Body:
Is it because it is running on another thread?

Because it runs in another context.

To solve problem assign this to some variable outside 'state_changed' callback function. After that you can use this variable as reference to initial this instance.

public uploadFile() {
        let self = this;
        ...
        firebaseUploadTask.on('state_changed',
            function progress(snapshot) {
                self.percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            },
            function error(error) {},
            function complete() {}
        );
    }


问:
How to Apply Gradient to background view of iOS Swift App
I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift.

Here's the code:

```<code>class Colors {
  let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
  let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)

  let gl: CAGradientLayer

  init() {
    gl = CAGradientLayer()
    gl.colors = [ colorTop, colorBottom]
    gl.locations = [ 0.0, 1.0]
  }
}
</code>```

then in the view controller:

```<code>  let colors = Colors()

  func refresh() {
        view.backgroundColor = UIColor.clearColor()
        var backgroundLayer = colors.gl
        backgroundLayer.frame = view.frame
        view.layer.insertSublayer(backgroundLayer, atIndex: 0)
      }
    }
  }
</code>```

答:
If you have view Collection (Multiple View) do this </p>

```<code>  func setGradientBackground() {
    let v:UIView
    for v in viewgradian
    //here viewgradian is your view Collection Outlet name
    {
        let layer:CALayer
        var arr = [AnyObject]()
        for layer in v.layer.sublayers!
        {
           arr.append(layer)
        }

        let colorTop = UIColor(red: 216.0/255.0, green: 240.0/255.0, blue: 244.0/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [ colorBottom, colorTop]
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
        gradientLayer.frame = v.bounds
        v.layer.insertSublayer(gradientLayer, at: 0)
    }
}
</code>```

Body:
I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift.

Here's the code:

class Colors {
  let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
  let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)

  let gl: CAGradientLayer

  init() {
    gl = CAGradientLayer()
    gl.colors = [ colorTop, colorBottom]
    gl.locations = [ 0.0, 1.0]
  }
}

then in the view controller:

  let colors = Colors()

  func refresh() {
        view.backgroundColor = UIColor.clearColor()
        var backgroundLayer = colors.gl
        backgroundLayer.frame = view.frame
        view.layer.insertSublayer(backgroundLayer, atIndex: 0)
      }
    }
  }

Body:
If you have view Collection (Multiple View) do this

  func setGradientBackground() {
    let v:UIView
    for v in viewgradian
    //here viewgradian is your view Collection Outlet name
    {
        let layer:CALayer
        var arr = [AnyObject]()
        for layer in v.layer.sublayers!
        {
           arr.append(layer)
        }

        let colorTop = UIColor(red: 216.0/255.0, green: 240.0/255.0, blue: 244.0/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [ colorBottom, colorTop]
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
        gradientLayer.frame = v.bounds
        v.layer.insertSublayer(gradientLayer, at: 0)
    }
}


问:
(Android) If I put an image file only in drawable-xxhdpi folder, is it working in all devices which have various densities
I only have an image made for xxhdpi density. If I put this file only in drawable-xxhdpi folder, would it be working in all devices of various densities? like ldpi, mdpi, xhdpi, xxxhdpi and so on I want to know if Android does this scaling job itself

thank you

答:
Read Supporting Multiple Screens

Android runs on a variety of devices that offer different screen sizes
  and densities. For applications, the Android system provides a
  consistent development environment across devices and handles most of
  the work to adjust each application's user interface to the screen on
  which it is displayed. At the same time, the system provides APIs that
  allow you to control your application's UI for specific screen sizes
  and densities, in order to optimize your UI design for different
  screen configurations. For example, you might want a UI for tablets
  that's different from the UI for handsets.

So, For good practice you should create different drawables for different screen densities .


问:
jQuery add attribute to span and alert when added
I have html table like below:

```<code><table id="list" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class='thread selected'>
    <td class='subject'>Jill</td>
    <td>Smith</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    <span class='flag'></span>
    </span>
    </td>
  </tr>
  <tr class='thread'>
    <td class='subject'>Eve</td>
    <td>Jackson</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    </span>
  </td>
  </tr>
</table>
</code>```

If a user select a row I want to add dynamically title='With flag'in last span like

```<code><span class='flag' title='With flag'></span>
</span>
</code>```

and want to alert('title added'); using if statement.

How can I achive this using jQuery

答:
You can find last td using last-child and span with class flag and add your attribute.

$(".thread").click(function() {
   $(this).find('td:last-child span.flag').attr("title","With flag");
   alert("title added");
});```
<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>
<table id="list" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class='thread selected'>
    <td class='subject'>Jill</td>
    <td>Smith</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    <span class='flag'></span>
    </span>
    </td>
  </tr>
  <tr class='thread'>
    <td class='subject'>Eve</td>
    <td>Jackson</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    </span>
  </td>
  </tr>
</table></code>```

Body:
I have html table like below:

    Firstname
    Lastname
    Age

    Jill
    Smith

    Eve
    Jackson

If a user select a row I want to add dynamically title='With flag'in last span like

and want to alert('title added'); using if statement.

How can I achive this using jQuery

Body:
You can find last td using last-child and span with class flag and add your attribute.

$(".thread").click(function() {
   $(this).find('td:last-child span.flag').attr("title","With flag");
   alert("title added");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class='thread selected'>
    <td class='subject'>Jill</td>
    <td>Smith</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    <span class='flag'></span>
    </span>
    </td>
  </tr>
  <tr class='thread'>
    <td class='subject'>Eve</td>
    <td>Jackson</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    </span>
  </td>
  </tr>
</table>


问:
Differences of using Component template vs templateUrl
Angular 2 allows to write multi-line templates by using ` characters to enquote them. It is also possible to put multi-line template into .html file and reference it by templateUrl.

It seems comfortable for me to put the template directly into component as then it's all in one place, but is there any drawback of doing so?

1st approach:

```<code>import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: `
    <h1>My First Angular 2 multiline template</h1>
    <p>Second line</p>
    `
})
export class AppComponent { }
</code>```

vs
2nd approach:

```<code>import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    templateUrl: 'multi-line.html'
})
export class AppComponent { }
</code>```

together with multi-line.html:

```<code><h1>My First Angular 2 multiline template</h1>
<p>Second line</p>
</code>```

答:
Most of the answers seam to be around editor support, but, while that argument is true, I would not argue that as a strong point for putting the html and css into .html and .css files.

The main reason that I separate my html and css files is because it follows SRP. It allows for easy code portability and reuse as Angular changes versions and syntax of how the typescript should be layed out, your html and css stay for the most part the same.

Body:
Angular 2 allows to write multi-line templates by using ` characters to enquote them. It is also possible to put multi-line template into .html file and reference it by templateUrl.

It seems comfortable for me to put the template directly into component as then it's all in one place, but is there any drawback of doing so?

1st approach:

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: `

My First Angular 2 multiline template

Second line

    `
})
export class AppComponent { }

vs
2nd approach:

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    templateUrl: 'multi-line.html'
})
export class AppComponent { }

together with multi-line.html:

My First Angular 2 multiline template

Second line


问:
How can i download image using selenium webdriver by right clicking the image in java?
I need to save the image by right clicking using selenium and also by "Authenticating the browser with username and password". the link which i am sending through selenium looks like this  "http://111.111.2.125/capture".

As I am new this concept, any suggestions will be highly helpful.

答:
For Right Click on Image you can use :

```<code>WebElement Image =driver.findElement(By.xpath("//img[@border='0']"));
Actions action= new Actions(driver);
action.contextClick(Image).build().perform();
</code>```

Select "Save Image As" option

If you see In Image, We can select "Save Image As" option using CONTROL + V from keyboard. To do It In selenium webdriver, We will use bellow given code.

```<code>action.sendKeys(Keys.CONTROL, "v").build().perform();
</code>```

Body:
For Right Click on Image you can use :

WebElement Image =driver.findElement(By.xpath("//img[@border='0']"));
Actions action= new Actions(driver);
action.contextClick(Image).build().perform();

Select "Save Image As" option

If you see In Image, We can select "Save Image As" option using CONTROL + V from keyboard. To do It In selenium webdriver, We will use bellow given code.

action.sendKeys(Keys.CONTROL, "v").build().perform();


问:
how to get selected id inside interval using jquery
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);```
<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>
<input type="button" value="click" id="btn"></code>```

答:
You can use <strong>.each</strong> function. </p>

```<code>$('#btn').on('click', function(){
   $("body").prepend('<div id="popup_w">A new popup div added</div><div id="Spopup_w">A new popup div added</div>');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    $("div[id$='_w']").each(function(){
        console.log(  this.id  );
    })

  };

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

Body:
Having this piece of code and i want to get selected element id (popup_w) but this.id or $(this).attr('id') or $this returning undefined...

Is there any problem with interval? How i will get the selected element id?

console.clear();
$('#btn').on('click', function(){
   $("body").prepend('
A new popup div added
');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    console.log( this.id );
  };

}, 1000);

<input type="button" value="click" id="btn">

Body:
You can use .each function.

$('#btn').on('click', function(){
   $("body").prepend('<div id="popup_w">A new popup div added</div><div id="Spopup_w">A new popup div added</div>');
});

var found = false;
var checkDiv = setInterval( function() {

  if ( $("div[id$='_w']").length && !found) {
    found = true;
    $("div[id$='_w']").each(function(){
        console.log(  this.id  );
    })

  };

}, 1000);


问:
Hardware “back” button doesn't work after typing in edittext
in my form fragment Hardware "back" button work not correctly. For example when I opened fragment and when I didn't start typing, and I pressed Hardware "back" button it's work excellent. But when I started typing and after typing press to Hardware "back" button not working.

my form fragment i am using OnResume() method use to handle back button process.

```<code>@Override
public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                //getView().clearFocus();

                getActivity().getSupportFragmentManager().popBackStack();

                return true;
            }

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

答:
Override onBackPressed()

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

Body:
in my form fragment Hardware "back" button work not correctly. For example when I opened fragment and when I didn't start typing, and I pressed Hardware "back" button it's work excellent. But when I started typing and after typing press to Hardware "back" button not working.

my form fragment i am using OnResume() method use to handle back button process.

@Override
public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                //getView().clearFocus();

                getActivity().getSupportFragmentManager().popBackStack();

                return true;
            }

            return false;
        }
    });
}

Body:
Override onBackPressed()

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


问:
Fluid Floating Elements Wrapped in Container
I have the following test code to play around with:

http://jsfiddle.net/b6QFY/1/

I want the "left" element to be fixed and the "right" element to be fluid within the parent container so that it will grow and shrink as the browser width changes, and not wrap.  Seems so simple, but have issues getting something to work.

答:
This is what I meant to link to. (I should be getting to bed.)

The core of it:

Padding-left on the container element, absolutely position left element with negative left-margin, and width of 100% on the right element.

To my knowledge this should work in most browsers, except IE6 and possibly 7.