问:
Rotate Marker and Move Animation on Map like Uber Android
I am working on a project similar to UBER, Lyft or OLA ie. Map on the home with available moving Cars.
I'm looking for some kind of Library which can make Cars move and take turn smoothly just like UBER. For now I was able to move car smoothly from one lat-long to another with the below code. But tricky part is Taking turn and make sure the car face to front when moving to direction. </p>

<p>Smooth Moving Car Code: </p>

```<code>    final LatLng SomePos = new LatLng(12.7796354, 77.4159606);

    try {
        if (googleMap == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            }
        }
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setMyLocationEnabled(true);
        googleMap.setTrafficEnabled(false);
        googleMap.setIndoorEnabled(false);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(SomePos));
        googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                .target(googleMap.getCameraPosition().target)
                .zoom(17)
                .bearing(30)
                .tilt(45)
                .build()));

        myMarker = googleMap.addMarker(new MarkerOptions()
                .position(SomePos)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
                .title("Hello world"));

        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker arg0) {

                final LatLng startPosition = myMarker.getPosition();
                final LatLng finalPosition = new LatLng(12.7801569, 77.4148528);
                final Handler handler = new Handler();
                final long start = SystemClock.uptimeMillis();
                final Interpolator interpolator = new AccelerateDecelerateInterpolator();
                final float durationInMs = 3000;
                final boolean hideMarker = false;

                handler.post(new Runnable() {
                    long elapsed;
                    float t;
                    float v;

                    @Override
                    public void run() {
                        // Calculate progress using interpolator
                        elapsed = SystemClock.uptimeMillis() - start;
                        t = elapsed / durationInMs;

                        LatLng currentPosition = new LatLng(
                                startPosition.latitude * (1 - t) + finalPosition.latitude * t,
                                startPosition.longitude * (1 - t) + finalPosition.longitude * t);

                        myMarker.setPosition(currentPosition);

                        // Repeat till progress is complete.
                        if (t < 1) {
                            // Post again 16ms later.
                            handler.postDelayed(this, 16);
                        } else {
                            if (hideMarker) {
                                myMarker.setVisible(false);
                            } else {
                                myMarker.setVisible(true);
                            }
                        }
                    }
                });

                return true;

            }

        });

    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

答:
Here is my code to move marker like uber. i have shown two ways to move marker .

Important Note: To move car on proper road [like ola,uber] you need to use road api provided by google

1.By static latitude and longitude

2.By Real time Latitude and longitude

```<code>package com.gangsofcoder.googlemapdemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
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.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

public class MoveCar extends AppCompatActivity {
    private GoogleMap googleMap;
    SupportMapFragment mapFragment;
    Marker marker;
    private boolean isMarkerRotating = false;
    ArrayList<LatLng> listOfPoints = new ArrayList<>();
    int currentPt = 0;
    LatLng finalPosition;
    Marker mMarker;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpMapIfNeeded();
    //new location details
    listOfPoints.add(new LatLng(30.701623, 76.684220));
    listOfPoints.add(new LatLng(30.702486, 76.685487));
    listOfPoints.add(new LatLng(30.703135, 76.684891));
    listOfPoints.add(new LatLng(30.703256, 76.685000));
    listOfPoints.add(new LatLng(30.703883, 76.685941));
    listOfPoints.add(new LatLng(30.703413, 76.685190));
}

private void setUpMapIfNeeded() {
    if (mapFragment == null) {
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        if (mapFragment != null) {
            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    loadMap(googleMap);
                }
            });
        }
    }
}

private void loadMap(GoogleMap map) {
    googleMap = map;

    mMarker = googleMap.addMarker(new MarkerOptions().position(new LatLng(30.701623, 76.684220)).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));

    final Handler handler = new Handler();
    //Code to move car along static latitude and longitude

  /*  handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            if (currentPt < listOfPoints.size()) {
                //post again
                Log.d("tess", "inside run ");
                Location targetLocation = new Location(LocationManager.GPS_PROVIDER);
                targetLocation.setLatitude(listOfPoints.get(currentPt).latitude);
                targetLocation.setLongitude(listOfPoints.get(currentPt).longitude);
                animateMarkerNew(targetLocation, mMarker);
                handler.postDelayed(this, 3000);
                currentPt++;
            } else {
                Log.d("tess", "call back removed");
                //removed callbacks
                handler.removeCallbacks(this);
            }
        }
    }, 3000);*/

    //Here move marker along real time updates
    final RequestParams params = new RequestParams();
    params.put("source_lattitude", "lat");
    params.put("source_longitude", "long");
    params.put("date", "date");

    //new handler
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            LoopjHttpClient.post(getString(R.string.default_upload_website), params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                    try {
                        JSONObject jsonObject = new JSONObject(new String(responseBody));
                        String status = jsonObject.getString("status");
                        String text = jsonObject.getString("text");
                        //reading json array
                        JSONArray jsonArray = jsonObject.getJSONArray("result");
                        String source = jsonArray.getJSONObject(0).getString("source");

                        String[] latLong = source.split(",");
                        Location location = new Location(LocationManager.GPS_PROVIDER);
                        location.setLatitude(Double.parseDouble(latLong[0]));
                        location.setLongitude(Double.parseDouble(latLong[1]));
                        //calling method to animate marker
                        animateMarkerNew(location, mMarker);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.d("onFailure", "onFailure");
                }
            });

            handler.postDelayed(this, 3000);
        }
    }, 3000);

}

private void animateMarkerNew(final Location destination, final Marker marker) {

    if (marker != null) {

                final LatLng startPosition = marker.getPosition();
                final LatLng endPosition = new LatLng(destination.getLatitude(), destination.getLongitude());

                final float startRotation = marker.getRotation();
                final LatLngInterpolatorNew latLngInterpolator = new LatLngInterpolatorNew.LinearFixed();

                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
                valueAnimator.setDuration(3000); // duration 3 second
                valueAnimator.setInterpolator(new LinearInterpolator());
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        try {
                            float v = animation.getAnimatedFraction();
                            LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, endPosition);
                            marker.setPosition(newPosition);
                            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                                    .target(newPosition)
                                    .zoom(15.5f)
                                    .build()));

                            marker.setRotation(getBearing(startPosition, new LatLng(destination.getLatitude(), destination.getLongitude())));
                        } catch (Exception ex) {
                            //I don't care atm..
                        }
                    }
                });
                valueAnimator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);

                        // if (mMarker != null) {
                            // mMarker.remove();
                        // }
                        // mMarker = googleMap.addMarker(new MarkerOptions().position(endPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));

                    }
                });
                valueAnimator.start();
    }
}

private interface LatLngInterpolatorNew {
    LatLng interpolate(float fraction, LatLng a, LatLng b);

    class LinearFixed implements LatLngInterpolatorNew {
        @Override
        public LatLng interpolate(float fraction, LatLng a, LatLng b) {
            double lat = (b.latitude - a.latitude) * fraction + a.latitude;
            double lngDelta = b.longitude - a.longitude;
            // Take the shortest path across the 180th meridian.
            if (Math.abs(lngDelta) > 180) {
                lngDelta -= Math.signum(lngDelta) * 360;
            }
            double lng = lngDelta * fraction + a.longitude;
            return new LatLng(lat, lng);
        }
    }
}

//Method for finding bearing between two points
private float getBearing(LatLng begin, LatLng end) {
    double lat = Math.abs(begin.latitude - end.latitude);
    double lng = Math.abs(begin.longitude - end.longitude);

    if (begin.latitude < end.latitude && begin.longitude < end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)));
    else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
    else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
    else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
    return -1;
}
}
</code>```

Body:
I am working on a project similar to UBER, Lyft or OLA ie. Map on the home with available moving Cars.
I'm looking for some kind of Library which can make Cars move and take turn smoothly just like UBER. For now I was able to move car smoothly from one lat-long to another with the below code. But tricky part is Taking turn and make sure the car face to front when moving to direction.

Smooth Moving Car Code:

    final LatLng SomePos = new LatLng(12.7796354, 77.4159606);

    try {
        if (googleMap == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            }
        }
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setMyLocationEnabled(true);
        googleMap.setTrafficEnabled(false);
        googleMap.setIndoorEnabled(false);
        googleMap.setBuildingsEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(SomePos));
        googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                .target(googleMap.getCameraPosition().target)
                .zoom(17)
                .bearing(30)
                .tilt(45)
                .build()));

        myMarker = googleMap.addMarker(new MarkerOptions()
                .position(SomePos)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
                .title("Hello world"));

        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker arg0) {

                final LatLng startPosition = myMarker.getPosition();
                final LatLng finalPosition = new LatLng(12.7801569, 77.4148528);
                final Handler handler = new Handler();
                final long start = SystemClock.uptimeMillis();
                final Interpolator interpolator = new AccelerateDecelerateInterpolator();
                final float durationInMs = 3000;
                final boolean hideMarker = false;

                handler.post(new Runnable() {
                    long elapsed;
                    float t;
                    float v;

                    @Override
                    public void run() {
                        // Calculate progress using interpolator
                        elapsed = SystemClock.uptimeMillis() - start;
                        t = elapsed / durationInMs;

                        LatLng currentPosition = new LatLng(
                                startPosition.latitude * (1 - t) + finalPosition.latitude * t,
                                startPosition.longitude * (1 - t) + finalPosition.longitude * t);

                        myMarker.setPosition(currentPosition);

                        // Repeat till progress is complete.
                        if (t < 1) {
                            // Post again 16ms later.
                            handler.postDelayed(this, 16);
                        } else {
                            if (hideMarker) {
                                myMarker.setVisible(false);
                            } else {
                                myMarker.setVisible(true);
                            }
                        }
                    }
                });

                return true;

            }

        });

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

Body:
Here is my code to move marker like uber. i have shown two ways to move marker .

Important Note: To move car on proper road [like ola,uber] you need to use road api provided by google

1.By static latitude and longitude

2.By Real time Latitude and longitude

package com.gangsofcoder.googlemapdemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
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.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

public class MoveCar extends AppCompatActivity {
    private GoogleMap googleMap;
    SupportMapFragment mapFragment;
    Marker marker;
    private boolean isMarkerRotating = false;
    ArrayList<LatLng> listOfPoints = new ArrayList<>();
    int currentPt = 0;
    LatLng finalPosition;
    Marker mMarker;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpMapIfNeeded();
    //new location details
    listOfPoints.add(new LatLng(30.701623, 76.684220));
    listOfPoints.add(new LatLng(30.702486, 76.685487));
    listOfPoints.add(new LatLng(30.703135, 76.684891));
    listOfPoints.add(new LatLng(30.703256, 76.685000));
    listOfPoints.add(new LatLng(30.703883, 76.685941));
    listOfPoints.add(new LatLng(30.703413, 76.685190));
}

private void setUpMapIfNeeded() {
    if (mapFragment == null) {
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        if (mapFragment != null) {
            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    loadMap(googleMap);
                }
            });
        }
    }
}

private void loadMap(GoogleMap map) {
    googleMap = map;

    mMarker = googleMap.addMarker(new MarkerOptions().position(new LatLng(30.701623, 76.684220)).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));

    final Handler handler = new Handler();
    //Code to move car along static latitude and longitude

  /*  handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            if (currentPt < listOfPoints.size()) {
                //post again
                Log.d("tess", "inside run ");
                Location targetLocation = new Location(LocationManager.GPS_PROVIDER);
                targetLocation.setLatitude(listOfPoints.get(currentPt).latitude);
                targetLocation.setLongitude(listOfPoints.get(currentPt).longitude);
                animateMarkerNew(targetLocation, mMarker);
                handler.postDelayed(this, 3000);
                currentPt++;
            } else {
                Log.d("tess", "call back removed");
                //removed callbacks
                handler.removeCallbacks(this);
            }
        }
    }, 3000);*/

    //Here move marker along real time updates
    final RequestParams params = new RequestParams();
    params.put("source_lattitude", "lat");
    params.put("source_longitude", "long");
    params.put("date", "date");

    //new handler
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            LoopjHttpClient.post(getString(R.string.default_upload_website), params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                    try {
                        JSONObject jsonObject = new JSONObject(new String(responseBody));
                        String status = jsonObject.getString("status");
                        String text = jsonObject.getString("text");
                        //reading json array
                        JSONArray jsonArray = jsonObject.getJSONArray("result");
                        String source = jsonArray.getJSONObject(0).getString("source");

                        String[] latLong = source.split(",");
                        Location location = new Location(LocationManager.GPS_PROVIDER);
                        location.setLatitude(Double.parseDouble(latLong[0]));
                        location.setLongitude(Double.parseDouble(latLong[1]));
                        //calling method to animate marker
                        animateMarkerNew(location, mMarker);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.d("onFailure", "onFailure");
                }
            });

            handler.postDelayed(this, 3000);
        }
    }, 3000);

}

private void animateMarkerNew(final Location destination, final Marker marker) {

    if (marker != null) {

                final LatLng startPosition = marker.getPosition();
                final LatLng endPosition = new LatLng(destination.getLatitude(), destination.getLongitude());

                final float startRotation = marker.getRotation();
                final LatLngInterpolatorNew latLngInterpolator = new LatLngInterpolatorNew.LinearFixed();

                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
                valueAnimator.setDuration(3000); // duration 3 second
                valueAnimator.setInterpolator(new LinearInterpolator());
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        try {
                            float v = animation.getAnimatedFraction();
                            LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, endPosition);
                            marker.setPosition(newPosition);
                            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                                    .target(newPosition)
                                    .zoom(15.5f)
                                    .build()));

                            marker.setRotation(getBearing(startPosition, new LatLng(destination.getLatitude(), destination.getLongitude())));
                        } catch (Exception ex) {
                            //I don't care atm..
                        }
                    }
                });
                valueAnimator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);

                        // if (mMarker != null) {
                            // mMarker.remove();
                        // }
                        // mMarker = googleMap.addMarker(new MarkerOptions().position(endPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_car)));

                    }
                });
                valueAnimator.start();
    }
}

private interface LatLngInterpolatorNew {
    LatLng interpolate(float fraction, LatLng a, LatLng b);

    class LinearFixed implements LatLngInterpolatorNew {
        @Override
        public LatLng interpolate(float fraction, LatLng a, LatLng b) {
            double lat = (b.latitude - a.latitude) * fraction + a.latitude;
            double lngDelta = b.longitude - a.longitude;
            // Take the shortest path across the 180th meridian.
            if (Math.abs(lngDelta) > 180) {
                lngDelta -= Math.signum(lngDelta) * 360;
            }
            double lng = lngDelta * fraction + a.longitude;
            return new LatLng(lat, lng);
        }
    }
}

//Method for finding bearing between two points
private float getBearing(LatLng begin, LatLng end) {
    double lat = Math.abs(begin.latitude - end.latitude);
    double lng = Math.abs(begin.longitude - end.longitude);

    if (begin.latitude < end.latitude && begin.longitude < end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)));
    else if (begin.latitude >= end.latitude && begin.longitude < end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
    else if (begin.latitude >= end.latitude && begin.longitude >= end.longitude)
        return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
    else if (begin.latitude < end.latitude && begin.longitude >= end.longitude)
        return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
    return -1;
}
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to animate second Activity from bottom to top?
I have a click button on first activity and when we click on that button then I want to animate second activity but in my case my first activity also animated with second
here is code

```<code> Intent createCompaignActivityIntent = new Intent(mActivity, CreateCompaignActivity.class);
 mActivity.startActivity(createCompaignActivityIntent);
 mActivity.overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
</code>```

slide_in_up.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="100%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>
</code>```

slide_out_up.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="-100%p"
    android:duration="@android:integer/config_longAnimTime"/>
</code>```

答:
If you don't want to animate your first Activity, then change android:toYDelta="-100%p" to android:toYDelta="0%p" in your slide_out_up.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>
</code>```

Edit:

To achieve slide down on exit of second activity, create a animation file and copy below code

slide_out_down.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="100%p"
    android:duration="@android:integer/config_longAnimTime"/>
</code>```

and in your second activity's onBackPressed() add the below code.

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.slide_out_up, R.anim.slide_out_down);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a click button on first activity and when we click on that button then I want to animate second activity but in my case my first activity also animated with second
here is code

 Intent createCompaignActivityIntent = new Intent(mActivity, CreateCompaignActivity.class);
 mActivity.startActivity(createCompaignActivityIntent);
 mActivity.overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );

slide_in_up.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="100%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>

slide_out_up.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="-100%p"
    android:duration="@android:integer/config_longAnimTime"/>

Body:
If you don't want to animate your first Activity, then change android:toYDelta="-100%p" to android:toYDelta="0%p" in your slide_out_up.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="0%p"
    android:duration="@android:integer/config_longAnimTime"/>

Edit:

To achieve slide down on exit of second activity, create a animation file and copy below code

slide_out_down.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%p" android:toYDelta="100%p"
    android:duration="@android:integer/config_longAnimTime"/>

and in your second activity's onBackPressed() add the below code.

@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.slide_out_up, R.anim.slide_out_down);
}


问:
Protect Wordpress contacts form from spammers
I have a project http://www.takoplius.lt. I am dealing with with a spam problem which comes through contact form. You can find this form in homepage right here (https://www.screencast.com/t/MvP7d7ZAiEe).

I tried to use Google recaptcha plugin, but it didn't help. In other words, when I put recaptcha shortcode in the form, recaptcha doesn't appear.

I tried akismet, but it didn't help as well.

Could you please help me to find the solution, which will protect my form from spam?

答:
Hey add if possible use contact form 7 for formand add google recatcha on your form.

Also add below plugin to avoid spam mail.

```<code>URL - https://wordpress.org/plugins/stop-spammer-registrations-plugin/
</code>```

Body:
Hey add if possible use contact form 7 for formand add google recatcha on your form.

Also add below plugin to avoid spam mail.

URL - https://wordpress.org/plugins/stop-spammer-registrations-plugin/


问:
Topic Modeling using Mallet Java Api?
Hi i have to do topic modeling using Mallet Java API but i am new to coding so i am finding it real difficult to understand the Java libraries and use them. Does anyone has some sample code where they do topic modeling using the API which can be used to build upon?</p>

答:
You can take a look at the tutorial slides from page 97 onwards here

Also, take a look at my answer to this question here

Title: Topic Modeling using Mallet Java Api?


问:
manage.py command in crontab not working
I have created a executeable script .sh which contains code to run a django managemenet command.

cron.sh

```<code>#!/bin/sh
. /path/to/env/activate
cd /path/to/project
/path/to/env/bin/python manage.py some_command
</code>```

I can confirm this script and manage.py command is working by executing it directly on terminal

$ /path/to/cron.sh

When i do it same via crontab its not working as expected.

** What am i doing wrong ?? I can confirm there is nothing wrong with crontab, it executing the cron.sh file but path/to/env/bin/python manage.py some_command is not working as expected.

cron log also showing

```<code>CRON[14768]: (root) CMD /path/to/cron.sh > /dev/null 2>&1
</code>```

I am using bitnami django ami (ubuntu 14.04.5 LTS)

Update

After removing /dev/null i am getting this error now

```<code>"Cannot locate wrapped file"
</code>```

答:
The problem is that your not using the script that Bitnami uses to load all the environment variables (/opt/bitnami/scritps/setenv.sh).

I would try using this script:

```<code>#!/bin/sh
. /opt/bitnami/scritps/setenv.sh
. /path/to/env/activate
cd /path/to/project
/path/to/env/bin/python manage.py some_command
</code>```

Body:
I have created a executeable script .sh which contains code to run a django managemenet command.

cron.sh

#!/bin/sh
. /path/to/env/activate
cd /path/to/project
/path/to/env/bin/python manage.py some_command

I can confirm this script and manage.py command is working by executing it directly on terminal

$ /path/to/cron.sh

When i do it same via crontab its not working as expected.

** What am i doing wrong ?? I can confirm there is nothing wrong with crontab, it executing the cron.sh file but path/to/env/bin/python manage.py some_command is not working as expected.

cron log also showing

CRON[14768]: (root) CMD /path/to/cron.sh > /dev/null 2>&1

I am using bitnami django ami (ubuntu 14.04.5 LTS)

Update

After removing /dev/null i am getting this error now

"Cannot locate wrapped file"

Body:
The problem is that your not using the script that Bitnami uses to load all the environment variables (/opt/bitnami/scritps/setenv.sh).

I would try using this script:

#!/bin/sh
. /opt/bitnami/scritps/setenv.sh
. /path/to/env/activate
cd /path/to/project
/path/to/env/bin/python manage.py some_command


问:
Validate duplicate rows / columns
I need to do data validation to identify is there any duplicates in CodeA1, CodeA2 and Code A3 (columns).

```<code>  CodeA1 CodeA2 CodeA3
1   1     NA      5
2   3     1       3
3   8     3       3
4   3     NA      NA
5   4     1       2
6   1     8       3
</code>```

The rows in all columns (CodeA1, CodeA2, CodeA3) should be unique across.

Can somebody please help in R?

I would like to identify the duplicates across all the rows and have the result as below

```<code>  CodeA1 CodeA2 CodeA3  Duplicate
1   1     NA       5    No
2   3     1       3     Yes
3   8     3       3     Yes
4   3     NA      NA     No
5   4     1       2     No
6   1     8       3     No
</code>```

答:
A possibile solution is:</p>

```<code>dtset$Duplicate <- apply(dtset,1,function(x) any(table(x)>1))

dtset

########
  CodeA1 CodeA2 CodeA3 Duplicate
1      1     NA      5     FALSE
2      3      1      3      TRUE
3      8      3      3      TRUE
4      3     NA     NA     FALSE
5      4      1      2     FALSE
6      1      8      3     FALSE
</code>```

Title: Validate duplicate rows / columns

Body:
I need to do data validation to identify is there any duplicates in CodeA1, CodeA2 and Code A3 (columns).

  CodeA1 CodeA2 CodeA3
1   1     NA      5
2   3     1       3
3   8     3       3
4   3     NA      NA
5   4     1       2
6   1     8       3

The rows in all columns (CodeA1, CodeA2, CodeA3) should be unique across.

Can somebody please help in R?

I would like to identify the duplicates across all the rows and have the result as below

  CodeA1 CodeA2 CodeA3  Duplicate
1   1     NA       5    No
2   3     1       3     Yes
3   8     3       3     Yes
4   3     NA      NA     No
5   4     1       2     No
6   1     8       3     No

Body:
A possibile solution is:

dtset$Duplicate <- apply(dtset,1,function(x) any(table(x)>1))

dtset

########
  CodeA1 CodeA2 CodeA3 Duplicate
1      1     NA      5     FALSE
2      3      1      3      TRUE
3      8      3      3      TRUE
4      3     NA     NA     FALSE
5      4      1      2     FALSE
6      1      8      3     FALSE


答:
To do this you are missing one more attribute in you initial query.Let's call it Type. You can then use the bellow query to do what you want.</p>

```<code>drop table if exists dbo.TableC;

create table dbo.TableC (
_Index int
, Date datetime
, Sub_index int
, Angle int
, Length int
, Type int
);

insert into dbo.TableC (_Index, Date, Sub_index, Angle, Length, Type)
values (681, CONVERT(datetime, '19/10/2016 15:49', 103), 1, 30, 333, 1)
, (681, CONVERT(datetime, '19/10/2016 15:49', 103), 1, 60, 666, 2)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 0, 44, 1)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 45, 77, 2)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 90, 67, 3)

select
    t._Index, t.Date, t.Sub_index
    , max(case when t.Type = 1 then t.Angle else null end) as Angle1
    , max(case when t.Type = 1 then t.Length else null end) as Length1
    , max(case when t.Type = 2 then t.Angle else null end) as Angle2
    , max(case when t.Type = 2 then t.Length else null end) as Length2
    , max(case when t.Type = 3 then t.Angle else null end) as Angle3
    , max(case when t.Type = 3 then t.Length else null end) as Length3
from dbo.TableC t
group by t._Index, t.Date, t.Sub_index
</code>```

Title: Make one row out of number of rows in a query

Body:
I have two tables with a relationship of one to many.
After executing a query, I got the result table:

+-------+------------------+-----------+-------+--------+
| index |       date       | sub_index | angle | length |
+-------+------------------+-----------+-------+--------+
|   681 | 19/10/2016 15:49 |         1 |    30 |    333 |
|   681 | 19/10/2016 15:49 |         1 |    60 |    666 |
|   682 | 19/10/2016 15:52 |         2 |     0 |     44 |
|   682 | 19/10/2016 15:52 |         2 |    45 |     77 |
|   682 | 19/10/2016 15:52 |         2 |    90 |     67 |
+-------+------------------+-----------+-------+--------+

But the user asked for the information to be flat. Such as the following:

+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+
| index |       date       | sub_index | angle1 | length1 | angle2 | length2 | angle3 | length3 |
+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+
|   681 | 19/10/2016 15:49 |         1 |     30 |     333 |     60 |     666 |        |         |
|   682 | 19/10/2016 15:52 |         2 |      0 |      44 |     45 |      77 |     90 |      67 |
+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+

The number of angles and lengths is unknown and could be any number of items.

I read about a PIVOT, but I don't really know how to use it in this example, because of the changed columns (angle1, angle2...) and because I read that PIVOT need some function (MAX, COUNT, ...) and I need the value as is...

Body:
To do this you are missing one more attribute in you initial query.Let's call it Type. You can then use the bellow query to do what you want.

drop table if exists dbo.TableC;

create table dbo.TableC (
_Index int
, Date datetime
, Sub_index int
, Angle int
, Length int
, Type int
);

insert into dbo.TableC (_Index, Date, Sub_index, Angle, Length, Type)
values (681, CONVERT(datetime, '19/10/2016 15:49', 103), 1, 30, 333, 1)
, (681, CONVERT(datetime, '19/10/2016 15:49', 103), 1, 60, 666, 2)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 0, 44, 1)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 45, 77, 2)
, (682, CONVERT(datetime, '19/10/2016 15:52', 103), 2, 90, 67, 3)

select
    t._Index, t.Date, t.Sub_index
    , max(case when t.Type = 1 then t.Angle else null end) as Angle1
    , max(case when t.Type = 1 then t.Length else null end) as Length1
    , max(case when t.Type = 2 then t.Angle else null end) as Angle2
    , max(case when t.Type = 2 then t.Length else null end) as Length2
    , max(case when t.Type = 3 then t.Angle else null end) as Angle3
    , max(case when t.Type = 3 then t.Length else null end) as Length3
from dbo.TableC t
group by t._Index, t.Date, t.Sub_index


问:
Protractor Unable to click on the button even though it finds it
I have been struggling to click on a button using Protractor.The problem is that even that the driver finds the element but it still doesn't click it.Any Help is appreciated.Thanks in advance.

Below is the HTML for the Sign in Button:

div class="row mod-form-button">
                <button id="sign_in" class="mod-main" tabindex="4">Sign in</button>

                    Not a member yet?

                        Get an Test ID

```
</div>
</div>
</p>

<p>Protractor Code:
This is the specs file:
// spec.js</p>

```    describe(' Demo', function() {

  it('Should Login to Demo Site', function() {
    browser.waitForAngularEnabled(false);
    browser.get('https://stage.com');

   // var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
//browser.wait(EC.elementToBeClickable($('password')), 5000);
    element(by.id('password')).sendKeys('123456');
    element(by.id('username')).sendKeys('Tester@test.com');
    //browser.sleep(35000);

     var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
 element(by.id('sign_in')).click();
 browser.sleep(5000);
 var el = element(by.id('sign_in'));
browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());

el.click();
// browser.wait(EC.elementToBeClickable($('sign_in')), 5000);
//browser.wait(EC.elementToBeClickable($('.btn.coral-btn.coral-btn-primary')), 5000);
//element(by.css('.btn.coral-btn.coral-btn-primary')).click();
  //  expect(element(by.binding('latest')).getText()).
      //  toEqual('5'); // This is wrong!
  });
});
```

<p>This is the config file:
//Config.js</p>

```exports.config = {

  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
   allScriptsTimeout: 5000000,
  specs: ['specs.js']

}
```

答:
Your code is quite confused, you actually declare the protractor.ExpectedConditions but you never use it in the proper way.

Then be careful because all the protractor methods return promises, because all the operations are asynchronous. You should use promises properly.

By the way, try this code it should wait for the element to be visible and then click on it:

```<code>var EC = protractor.ExpectedConditions;
var signinButton = element(by.id('sign_in'));
// waiting for 10 seconds that the button will be visible
browser.wait(EC.visibilityOf(signinButton ), 10000, "Button signin not visible");
    browser.executeScript('document.querySelector("#sign_in").scrollIntoView()').then(function() {
  signinButton.click().then(function() {
    console.log('button has been clicked here');
  });
});
</code>```

Body:
I have been struggling to click on a button using Protractor.The problem is that even that the driver finds the element but it still doesn't click it.Any Help is appreciated.Thanks in advance.

Below is the HTML for the Sign in Button:

div class="row mod-form-button">
                <button id="sign_in" class="mod-main" tabindex="4">Sign in</button>

                    Not a member yet?

                        Get an Test ID

Protractor Code:
This is the specs file:
// spec.js

    describe(' Demo', function() {

  it('Should Login to Demo Site', function() {
    browser.waitForAngularEnabled(false);
    browser.get('https://stage.com');

   // var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
//browser.wait(EC.elementToBeClickable($('password')), 5000);
    element(by.id('password')).sendKeys('123456');
    element(by.id('username')).sendKeys('Tester@test.com');
    //browser.sleep(35000);

     var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
 element(by.id('sign_in')).click();
 browser.sleep(5000);
 var el = element(by.id('sign_in'));
browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());

el.click();
// browser.wait(EC.elementToBeClickable($('sign_in')), 5000);
//browser.wait(EC.elementToBeClickable($('.btn.coral-btn.coral-btn-primary')), 5000);
//element(by.css('.btn.coral-btn.coral-btn-primary')).click();
  //  expect(element(by.binding('latest')).getText()).
      //  toEqual('5'); // This is wrong!
  });
});

This is the config file:
//Config.js

exports.config = {

  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
   allScriptsTimeout: 5000000,
  specs: ['specs.js']

}

Body:
Your code is quite confused, you actually declare the protractor.ExpectedConditions but you never use it in the proper way.

Then be careful because all the protractor methods return promises, because all the operations are asynchronous. You should use promises properly.

By the way, try this code it should wait for the element to be visible and then click on it:

var EC = protractor.ExpectedConditions;
var signinButton = element(by.id('sign_in'));
// waiting for 10 seconds that the button will be visible
browser.wait(EC.visibilityOf(signinButton ), 10000, "Button signin not visible");
    browser.executeScript('document.querySelector("#sign_in").scrollIntoView()').then(function() {
  signinButton.click().then(function() {
    console.log('button has been clicked here');
  });
});


问:
Sikuli can't tell colors apart
I'm developing a program with Java and Sikuli and I want to click on a red image with a specific shape that is located on screen.
The problem is that on the screen there is another image with that same shape but different color, blue.

```<code>import org.sikuli.script.Screen;

this.screen.type("C:\\Images\\TestImage.png", "a"); // this is what I'm using.
</code>```

My mouse keeps moving between the two images because it can't tell the difference in color.

答:
Here's something that might help. Create a Region and try to find the image in that region as in example in the link
http://seleniumqg.blogspot.com/2017/06/findfailed-exception-in-sikuili-script.html?m=1</p>

Title: Sikuli can't tell colors apart

Body:
I'm developing a program with Java and Sikuli and I want to click on a red image with a specific shape that is located on screen.
The problem is that on the screen there is another image with that same shape but different color, blue.

import org.sikuli.script.Screen;

this.screen.type("C:\\Images\\TestImage.png", "a"); // this is what I'm using.

My mouse keeps moving between the two images because it can't tell the difference in color.


问:
Image alignment with reduced opacity
In the program given below I am aligning two images using homography and reducing the opacity of im_dst image in im_out image (say opacity=0.5), so that I can see both im_src and im_dst images in im_out image. But all I am getting is a blackened im_dst image in im_out image!

```<code>import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
img1 = np.array(im_dst , dtype=np.float)
img2 = np.array(im_src , dtype=np.float)
img1 /= 255.0
# pre-multiplication
a_channel = np.ones(img1.shape, dtype=np.float)/2.0
im_dst = img1*a_channel
im_src = img2*(1-a_channel)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)
</code>```

I am new to openCV, so I might be missing something simple. Thanks for help!

答:
Hey I've seen those points before!

What your code is doing is reducing the values of two images, im_dst and im_src, but then you're simply moving the faded image of im_src to a new position and displaying that. Instead, you should add the faded and warped image to the destination image and output that. The following would be a working modification of the end of your code:

```<code>alpha = 0.5
im_dst = img1 * alpha
im_src = img2 * (1-alpha)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
im_blended = im_dst + im_out
cv2.imshow("Blended Warped Image", im_blended)
cv2.waitKey(0)
</code>```

However you only divided img1 and not img2 by 255 so you would want to divide both first.

However, there is no reason to do this manually as you have to worry about converting the image types and scaling and all that. Instead, a much easier way is to use the built-in OpenCV function addWeighted() to add two images together with alpha-blending. So your entire code would instead be this short:

```<code>import cv2
import numpy as np

im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])

h, status = cv2.findHomography(pts_src, pts_dst)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, im_out, beta, 0.0)

cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)
</code>```

The function addWeighted() multiplies the first image im_dst by alpha, and the second image im_out by beta. The last argument is positive shift you can add to the result should you need it. Finally, the result is saturated so that values above whatever is allowable for your datatype is truncated at the maximum. And this way, your result is the same type as your inputs---you don't have to convert to float.

Last point about your code. A lot of tutorials, the one linked above included, use findHomography() to get a homography from four matching points. It is more appropriate to use getPerspectiveTransform() in this case. The function findHomography() finds an optimal homography based on many matching points, using an outlier rejection scheme and random sampling to speed up going through all the possible sets of four matching points. It works fine for sets of four points of course, but it makes more sense to use getPerspectiveTransform() when you have four matching points, and findHomography() when you have more than four. Although, annoyingly, the points you pass into getPerspectiveTransform() have to be of type np.float32 for whatever reason. So this would be my final suggestion for your code:

```<code>import cv2
import numpy as np

# Read source image.
im_src = cv2.imread('src.jpg')
# Four corners of the book in source image
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)

# Read destination image.
im_dst = cv2.imread('dst.jpg')
# Four corners of the book in destination image.
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

# Calculate Homography
h = cv2.getPerspectiveTransform(pts_src, pts_dst)

# Warp source image to destination based on homography
warp_src = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

# Blend the warped image and the destination image
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, warp_src, beta, 0.0)

# Show the output
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)
</code>```

This (and all the other solutions above) will produce the following image:

Title: Image alignment with reduced opacity

Body:
In the program given below I am aligning two images using homography and reducing the opacity of im_dst image in im_out image (say opacity=0.5), so that I can see both im_src and im_dst images in im_out image. But all I am getting is a blackened im_dst image in im_out image!

import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
img1 = np.array(im_dst , dtype=np.float)
img2 = np.array(im_src , dtype=np.float)
img1 /= 255.0
# pre-multiplication
a_channel = np.ones(img1.shape, dtype=np.float)/2.0
im_dst = img1*a_channel
im_src = img2*(1-a_channel)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)

I am new to openCV, so I might be missing something simple. Thanks for help!

Body:
Hey I've seen those points before!

What your code is doing is reducing the values of two images, im_dst and im_src, but then you're simply moving the faded image of im_src to a new position and displaying that. Instead, you should add the faded and warped image to the destination image and output that. The following would be a working modification of the end of your code:

alpha = 0.5
im_dst = img1 * alpha
im_src = img2 * (1-alpha)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
im_blended = im_dst + im_out
cv2.imshow("Blended Warped Image", im_blended)
cv2.waitKey(0)

However you only divided img1 and not img2 by 255 so you would want to divide both first.

However, there is no reason to do this manually as you have to worry about converting the image types and scaling and all that. Instead, a much easier way is to use the built-in OpenCV function addWeighted() to add two images together with alpha-blending. So your entire code would instead be this short:

import cv2
import numpy as np

im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])

h, status = cv2.findHomography(pts_src, pts_dst)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, im_out, beta, 0.0)

cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)

The function addWeighted() multiplies the first image im_dst by alpha, and the second image im_out by beta. The last argument is positive shift you can add to the result should you need it. Finally, the result is saturated so that values above whatever is allowable for your datatype is truncated at the maximum. And this way, your result is the same type as your inputs---you don't have to convert to float.

Last point about your code. A lot of tutorials, the one linked above included, use findHomography() to get a homography from four matching points. It is more appropriate to use getPerspectiveTransform() in this case. The function findHomography() finds an optimal homography based on many matching points, using an outlier rejection scheme and random sampling to speed up going through all the possible sets of four matching points. It works fine for sets of four points of course, but it makes more sense to use getPerspectiveTransform() when you have four matching points, and findHomography() when you have more than four. Although, annoyingly, the points you pass into getPerspectiveTransform() have to be of type np.float32 for whatever reason. So this would be my final suggestion for your code:

import cv2
import numpy as np

# Read source image.
im_src = cv2.imread('src.jpg')
# Four corners of the book in source image
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)

# Read destination image.
im_dst = cv2.imread('dst.jpg')
# Four corners of the book in destination image.
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

# Calculate Homography
h = cv2.getPerspectiveTransform(pts_src, pts_dst)

# Warp source image to destination based on homography
warp_src = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

# Blend the warped image and the destination image
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, warp_src, beta, 0.0)

# Show the output
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)

This (and all the other solutions above) will produce the following image:


问:
Edit Wamp "localhost" page
I wanted to reorganize my Wamp and add a section "My Laravel projects" without adding an extra "index.php" in "www" folder.
After searching and searching, I didn't find any solutions or a folder that contains information/code of the "www" page.

How it looks right now:

How I want to organize it:

Is it possible? Thanks for your help.

答:
You should never amend or add anything to the \wamp\www folder.

Instead, if you add a subfolder like wamp\www\laravelproject or a folder in a completely different folder structure like c:\website\project1\www and then create a Virtual Host for each project. you will then automatically see the new Virtual Host mentioned on the WAMPServer homepage.

See this post for how to easily create Apache Virtual Hosts is WAMPServer

Title: Edit Wamp "localhost" page


问:
Unique 8 digit incremental number
I'm trying to generate a number which will ultimately be stored as string(varchar). e.g.

First - ABC00000001

Second- ABC00000002
.........................
I am able to generate character string as expected. Now the problem is,incremental number.

What i am trying to do is get the last number stored e.g. ABC00000009 and generate the next number that is ABC00000010. How to do the same?

If i extract integers from this than i will get 1 or 10,how to make it according to 8 digit format.

Any help would really be appreciated.

答:
Almost the same approach Gordon Linoff has taken, I just prefer to use math where possible instead of string concatenation. My answer is different only because I add id value to 100000000 instead of using replicate.

```<code>CREATE TABLE dbo.test (
    id int IDENTITY(1, 1) PRIMARY KEY
  , some_value sysname UNIQUE
  , super_column AS 'ABC' + RIGHT(100000000 + id, 8));
GO
INSERT INTO dbo.test (some_value)
VALUES ('some_value_1'), ('some_value_2');

SELECT *
FROM dbo.test AS T;
</code>```

Result:

```<code>+----+--------------+--------------+
| id |  some_value  | super_column |
+----+--------------+--------------+
|  1 | some_value_1 | ABC00000001  |
|  2 | some_value_2 | ABC00000002  |
+----+--------------+--------------+
</code>```

Title: Unique 8 digit incremental number

Body:
Almost the same approach Gordon Linoff has taken, I just prefer to use math where possible instead of string concatenation. My answer is different only because I add id value to 100000000 instead of using replicate.

CREATE TABLE dbo.test (
    id int IDENTITY(1, 1) PRIMARY KEY
  , some_value sysname UNIQUE
  , super_column AS 'ABC' + RIGHT(100000000 + id, 8));
GO
INSERT INTO dbo.test (some_value)
VALUES ('some_value_1'), ('some_value_2');

SELECT *
FROM dbo.test AS T;

Result:

+----+--------------+--------------+
| id |  some_value  | super_column |
+----+--------------+--------------+
|  1 | some_value_1 | ABC00000001  |
|  2 | some_value_2 | ABC00000002  |
+----+--------------+--------------+


问:
Find the earliest date among 3 dates
I have three dates in Java: a, b, c.  Any or all of these dates may be null.  What's the most efficient way of determining the earliest date among a,b,c, without having a massive if-else block?</p>

答:
using before and after : </p>

```<code>  /**
     * find Min Dates
     * @param date1
     * @param date2
     * @return
     */
    public static Date minDate(Date date1, Date date2) {
        // if date1 before date2 then return date1 else return date2
        return date1.before(date2) ? date1 : date2;
    }
     /**
     * find Max Dates
     * @param date1
     * @param date2
     * @return
     */
    public static Date maxDate(Date date1, Date date2) {
        // if date1 after date2 then return date1 else return date2
        return date1.after(date2) ? date1 : date2;
    }
</code>```

Title: Find the earliest date among 3 dates

Body:
using before and after :

  /**
     * find Min Dates
     * @param date1
     * @param date2
     * @return
     */
    public static Date minDate(Date date1, Date date2) {
        // if date1 before date2 then return date1 else return date2
        return date1.before(date2) ? date1 : date2;
    }
     /**
     * find Max Dates
     * @param date1
     * @param date2
     * @return
     */
    public static Date maxDate(Date date1, Date date2) {
        // if date1 after date2 then return date1 else return date2
        return date1.after(date2) ? date1 : date2;
    }


问:
How to make an option selected according to the value of an input given
In my DB table sources i have some sources with their url's.  im getting their values  using eloquent:

```<code><?php $src = App\Source::orderBy("name", "ASC")->get()?>
<select class="form-control selectedSRC" name="sources">
  @foreach($src as $option)
    <option value="{{$option->id}}">{{$option->name}}</option>
  @endforeach
</select>
</code>```

I have an input for a url:

```<code><input class="sources col-md-3 srcURL"
type="url" class="form-control"
name="sourcesUrl" placeholder="Source URL">
</code>```

When I enter an url in the input, I want the name of the source to be selected by checking if the url of the source is contained within the url of the input. Ex:

```<code>input url: www.google.com/images/smiley.jpg
src in DB: www.google.com (with name: GOOGLE)
</code>```

When I input the url above i want GOOGLE option to be selected

答:
To do like that as you say above

First you have to change the select option
Like

```<code>   <?php $src = App\Source::orderBy("name", "ASC")->get()?>
    <select class="form-control selectedSRC" name="sources">
        @foreach($src as $option)
            <option value="{{$option->url}}">{{$option->name}}</option>
        @endforeach
    </select>
</code>```

Now Just add this Jquery to your page then it will work perfect.

```<code>$('.sources .col-md-3 .srcURL').on('change',function(){
        $(".form-control .selectedSRC").val($(this).val());
    });
</code>```

Body:
In my DB table sources i have some sources with their url's.  im getting their values  using eloquent:

<?php $src = App\Source::orderBy("name", "ASC")->get()?>
<select class="form-control selectedSRC" name="sources">
  @foreach($src as $option)
    <option value="{{$option->id}}">{{$option->name}}</option>
  @endforeach
</select>

I have an input for a url:

<input class="sources col-md-3 srcURL"
type="url" class="form-control"
name="sourcesUrl" placeholder="Source URL">

When I enter an url in the input, I want the name of the source to be selected by checking if the url of the source is contained within the url of the input. Ex:

input url: www.google.com/images/smiley.jpg
src in DB: www.google.com (with name: GOOGLE)

When I input the url above i want GOOGLE option to be selected

Body:
To do like that as you say above

First you have to change the select option
Like

   <?php $src = App\Source::orderBy("name", "ASC")->get()?>
    <select class="form-control selectedSRC" name="sources">
        @foreach($src as $option)
            <option value="{{$option->url}}">{{$option->name}}</option>
        @endforeach
    </select>

Now Just add this Jquery to your page then it will work perfect.

$('.sources .col-md-3 .srcURL').on('change',function(){
        $(".form-control .selectedSRC").val($(this).val());
    });


问:
How to rotate an image actor in libgdx by the middle point?
If I understand correctly, LibGDX is rotating an image with the use of the addActions method:

```<code>this.addAction( parallel(rotateBy(360, 0.5f), moveTo(320, 100, 0.5f)));
</code>```

The thing is, it is being rotated by the point=(0,0)  of the image.

Here's my question:

Is there a way to rotate an image by the center point of the object? Something like pinning it in the middle and then turning it like a wheel in a car?
Both rotateBy and rotateTo methods turn it by the (0,0) point of the image itself.

答:
The easiest and shortest way I found for setting the origin is to call:</p>

```<code>Actor a;

...

a.setOrigin(Align.center);
</code>```

Body:
If I understand correctly, LibGDX is rotating an image with the use of the addActions method:

this.addAction( parallel(rotateBy(360, 0.5f), moveTo(320, 100, 0.5f)));

The thing is, it is being rotated by the point=(0,0)  of the image.

Here's my question:

Is there a way to rotate an image by the center point of the object? Something like pinning it in the middle and then turning it like a wheel in a car?
Both rotateBy and rotateTo methods turn it by the (0,0) point of the image itself.

Body:
The easiest and shortest way I found for setting the origin is to call:

Actor a;

...

a.setOrigin(Align.center);


问:
Search an element from the form element using css
To make a search tab I have executed the following:

```<code><form>
   <input type="text" name="search" placeholder="Search..">
</form>
</code>```

However if I want to search another element from the same html page like say a paragraph named "123"  using this search tab how can I proceed?

答:
pretty simple please give a 5 rating to this answer !!!

input[type=text]
{
background-color:green;
font-size:40px;
}
input[type=email]
{
background-color:red;
font-size:40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>

<input type=text placeholder="i an text and i am green"><br>
<input type=email placeholder="i an email and i am red"><br>

</form></code>```

Body:
To make a search tab I have executed the following:

<form>
   <input type="text" name="search" placeholder="Search..">
</form>

However if I want to search another element from the same html page like say a paragraph named "123"  using this search tab how can I proceed?

Body:
pretty simple please give a 5 rating to this answer !!!

input[type=text]
{
background-color:green;
font-size:40px;
}
input[type=email]
{
background-color:red;
font-size:40px;
}

<form>

<input type=text placeholder="i an text and i am green"><br>
<input type=email placeholder="i an email and i am red"><br>

</form>


问:
ArrayList, JList, DefaultListModel, adding elements, displaying them etc
How can I change the output from JTextArea to JList?
The reason: deleting elements, sorting them and editing them is easier.
If I simply change the JTextArea to JList I have the problem of printing the ArrayList in the output area.

This is my code (I cut out certain (probably irrelevant) parts):

```<code>package personFiles;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class Osoblje extends JFrame {
    private JTextArea outputJTA = new JTextArea("");
    private JScrollPane outputJTAScrollPane = new JScrollPane(outputJTA);

    List<Person> personList = new ArrayList<>();

    public Osoblje(String title) {
        // Frame-Initialisierung
        super(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        int frameWidth = 310;
        int frameHeight = 269;
        setSize(frameWidth, frameHeight);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (d.width - getSize().width) / 2;
        int y = (d.height - getSize().height) / 2;
        setLocation(x, y);
        setResizable(false);
        Container cp = getContentPane();
        cp.setLayout(null);
        // Anfang Komponenten

        outputJTAScrollPane.setBounds(8, 8, 129, 217);
        cp.add(outputJTAScrollPane);

        setVisible(true);
    } // end of public Osoblje

    // Anfang Methoden

    public static void main(String[] args) {
        new Osoblje("Osoblje");
    } // end of main

    public void newPersonJB_ActionPerformed(ActionEvent evt) {
        personList.add(new Person(idJTF.getText(), nameJTF.getText(), surnameJTF.getText(), ageJTF.getText(), genderJTF.getText())); //create new person
    } // end of newPersonJB_ActionPerformed

    public void pokaziJB_ActionPerformed(ActionEvent evt) {
        outputJTA.setText(personList + "\n"); //display personList
    } // end of pokaziJB_ActionPerformed

}
</code>```

答:
Try switching from List<Person> onto java.util.List<Person>.

Or better, fix your imports.

Body:
How can I change the output from JTextArea to JList?
The reason: deleting elements, sorting them and editing them is easier.
If I simply change the JTextArea to JList I have the problem of printing the ArrayList in the output area.

This is my code (I cut out certain (probably irrelevant) parts):

package personFiles;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class Osoblje extends JFrame {
    private JTextArea outputJTA = new JTextArea("");
    private JScrollPane outputJTAScrollPane = new JScrollPane(outputJTA);

    List<Person> personList = new ArrayList<>();

    public Osoblje(String title) {
        // Frame-Initialisierung
        super(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        int frameWidth = 310;
        int frameHeight = 269;
        setSize(frameWidth, frameHeight);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (d.width - getSize().width) / 2;
        int y = (d.height - getSize().height) / 2;
        setLocation(x, y);
        setResizable(false);
        Container cp = getContentPane();
        cp.setLayout(null);
        // Anfang Komponenten

        outputJTAScrollPane.setBounds(8, 8, 129, 217);
        cp.add(outputJTAScrollPane);

        setVisible(true);
    } // end of public Osoblje

    // Anfang Methoden

    public static void main(String[] args) {
        new Osoblje("Osoblje");
    } // end of main

    public void newPersonJB_ActionPerformed(ActionEvent evt) {
        personList.add(new Person(idJTF.getText(), nameJTF.getText(), surnameJTF.getText(), ageJTF.getText(), genderJTF.getText())); //create new person
    } // end of newPersonJB_ActionPerformed

    public void pokaziJB_ActionPerformed(ActionEvent evt) {
        outputJTA.setText(personList + "\n"); //display personList
    } // end of pokaziJB_ActionPerformed

}


问:
Count number of times the get method in a dict returns the second option
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

```<code>dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]
</code>```

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

```<code>list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)
</code>```

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

```<code>dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1
</code>```

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?

答:
This will give the desired answer:

```<code>sum(1 for k in [dic.get(k, 0) for k in ['foo', 'bar', 'baz']] if k == 0)
</code>```

Here is another way:

```<code>ks = ['foo', 'bar', 'bad']

sum(1 for i in filter(lambda x: type(x) != int, [dic.get(k) for k in ks]))
</code>```

Body:
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?

Body:
This will give the desired answer:

sum(1 for k in [dic.get(k, 0) for k in ['foo', 'bar', 'baz']] if k == 0)

Here is another way:

ks = ['foo', 'bar', 'bad']

sum(1 for i in filter(lambda x: type(x) != int, [dic.get(k) for k in ks]))


问:
How to reverse a singly linked list using only two pointers?
I wonder if there exists some logic to reverse a singly-linked list using only two pointers.

The following is used to reverse the single linked list using three pointers namely p, q, r:

```<code>struct node {
    int data;
    struct node *link;
};

void reverse() {
    struct node *p = first,
                *q = NULL,
                *r;

    while (p != NULL) {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }
    first = q;
}
</code>```

Is there any other alternate to reverse the linked list?  What would be the best logic to reverse a singly linked list, in terms of time complexity?

答:
```<code>#include <stddef.h>

typedef struct Node {
    struct Node *next;
    int data;
} Node;

Node * reverse(Node *cur) {
    Node *prev = NULL;
    while (cur) {
        Node *temp = cur;
        cur = cur->next; // advance cur
        temp->next = prev;
        prev = temp; // advance prev
    }
    return prev;
}
</code>```

Body:
I wonder if there exists some logic to reverse a singly-linked list using only two pointers.

The following is used to reverse the single linked list using three pointers namely p, q, r:

struct node {
    int data;
    struct node *link;
};

void reverse() {
    struct node *p = first,
                *q = NULL,
                *r;

    while (p != NULL) {
        r = q;
        q = p;
        p = p->link;
        q->link = r;
    }
    first = q;
}

Is there any other alternate to reverse the linked list?  What would be the best logic to reverse a singly linked list, in terms of time complexity?

LastEditorDisplayName: Roger Pate


问:
C programming usin cmd prompt on windows
```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}
</code>```

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.

答:
You need to do it yourself: passing cd to system(...) would no longer do the trick, because your own code is running under the control of a command shell, which believes that the current directory is what it was when you started running your program.

It is a job of the command shell, cmd, to keep track of the current directory. Since you are coding a command shell, you need to keep track of the current location in the directory tree.

You would also need to pass the location to each command that you are running. This task becomes very tricky, though - far beyond a simple pass-through code.

Body:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.


问:
Get a company followers count on LinkedIn
I'm trying to get the number of followers of a company on Linked in.
I use this code:

```<code>HttpWebRequest request = WebRequest.Create("http://api.linkedin.com/v1/companies/?id=SomeCompanyID:(num-followers)") as HttpWebRequest;
request.Method = "Get";
request.Credentials = new NetworkCredential("MyAppClientID", "MyAppClientSecret");

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)   // I'm getting "(401) Unauthorized" exception at this line.
{
    StreamReader reader = new StreamReader(response.GetResponseStream());

    string result = reader.ReadToEnd();
    System.IO.File.WriteAllText(@"WriteText.txt", result);
    Console.WriteLine(reader.ReadToEnd());
}
</code>```

I'm not sure about my syntax and the way I provide credentials, but I don't know how to do so correctly, and documentation is not clear at this point.

Your help is appreciated.

答:
It looks like you haven't registered your application or more accurately you haven't updated the code sample with your own ClientKey and Secret value.

You obtain them from https://www.linkedin.com/developer/apps/

You can also find more information about it here https://developer.linkedin.com/support/faq

Where can I find my API key?

Click on the My Apps link in the top navigation menu to manage your
  LinkedIn applications.

From here, you can create a new application if you don't already have
  one or view the details of your existing applications.  You will find
  your Client ID (otherwise known as API Key/ID or Consumer Key/ID)
  listed in the "Authentication" side nav link, underneath the header
  "Authentication Keys".

Alternatively, you may be using an old format of Rest API call, accoring to this page (https://developer.linkedin.com/docs/company-pages), the new format is as follows

```<code>https://api.linkedin.com/v1/companies/{id}/num-followers?format=json
</code>```

Get a company's followers, by segment

If you choose to target content that you share on behalf of a company,
  there is a minumum number of followers that must make up the segment
  you are targeting before you will be able to successfully share the
  targeted content.  This request allows you to get a follower-count for
  a specific segment to ensure you are at or over the minimum
  requirement for the target segment for the company specified by the
  {id} value in the request. Optional Parameters

https://api.linkedin.com/v1/companies/{id}/num-followers?format=json

sample response
  1147037

Body:
I'm trying to get the number of followers of a company on Linked in.
I use this code:

HttpWebRequest request = WebRequest.Create("http://api.linkedin.com/v1/companies/?id=SomeCompanyID:(num-followers)") as HttpWebRequest;
request.Method = "Get";
request.Credentials = new NetworkCredential("MyAppClientID", "MyAppClientSecret");

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)   // I'm getting "(401) Unauthorized" exception at this line.
{
    StreamReader reader = new StreamReader(response.GetResponseStream());

    string result = reader.ReadToEnd();
    System.IO.File.WriteAllText(@"WriteText.txt", result);
    Console.WriteLine(reader.ReadToEnd());
}

I'm not sure about my syntax and the way I provide credentials, but I don't know how to do so correctly, and documentation is not clear at this point.

Your help is appreciated.

Body:
It looks like you haven't registered your application or more accurately you haven't updated the code sample with your own ClientKey and Secret value.

You obtain them from https://www.linkedin.com/developer/apps/

You can also find more information about it here https://developer.linkedin.com/support/faq

Where can I find my API key?

Click on the My Apps link in the top navigation menu to manage your
  LinkedIn applications.

From here, you can create a new application if you don't already have
  one or view the details of your existing applications.  You will find
  your Client ID (otherwise known as API Key/ID or Consumer Key/ID)
  listed in the "Authentication" side nav link, underneath the header
  "Authentication Keys".

Alternatively, you may be using an old format of Rest API call, accoring to this page (https://developer.linkedin.com/docs/company-pages), the new format is as follows

https://api.linkedin.com/v1/companies/{id}/num-followers?format=json

Get a company's followers, by segment

If you choose to target content that you share on behalf of a company,
  there is a minumum number of followers that must make up the segment
  you are targeting before you will be able to successfully share the
  targeted content.  This request allows you to get a follower-count for
  a specific segment to ensure you are at or over the minimum
  requirement for the target segment for the company specified by the
  {id} value in the request. Optional Parameters

https://api.linkedin.com/v1/companies/{id}/num-followers?format=json

sample response
  1147037


问:
Cannot set property '0' of undefined , creating multidimensional array in for loop
I am trying to group objects by key 'pokoj'.</p>

```<code>var array = [];
            for (var i = 0; i < events.length; i++)
            {
                array[events[i]['pokoj']][i] = events[i];

            }
console.log(array);
</code>```

答:
You have to check first if the subarray exists and if not, create it:</p>

```<code>var array = [];
for (var i = 0; i < events.length; i++) {
  if (!(events[i]['pokoj'] in array)) {
    array[events[i]['pokoj']] = [];
  }
  array[events[i]['pokoj']][i] = events[i];
}
console.log(array);
</code>```

Body:
I am trying to group objects by key 'pokoj'.

var array = [];
            for (var i = 0; i < events.length; i++)
            {
                array[events[i]['pokoj']][i] = events[i];

            }
console.log(array);

Body:
You have to check first if the subarray exists and if not, create it:

var array = [];
for (var i = 0; i < events.length; i++) {
  if (!(events[i]['pokoj'] in array)) {
    array[events[i]['pokoj']] = [];
  }
  array[events[i]['pokoj']][i] = events[i];
}
console.log(array);


问:
serial communication with USB device using 'GNET' protocol
I have a USB device with the following specification. Page 22 describes the GNET protocol that should be used to interact with the device.

The connection is fine but the device just doesn't give me any response, so I think I am not sending the correct data to it, maybe missing the handshake?

From Specification

Support TTY (TELE TYPE) OPERATION - Use TTY to send commands and messages

Use ASCII value for each field and use Separator "," between two
   Fields.

connect_and_send.py

```<code>import serial

port = "COM3"
baud = 9600

ser = serial.Serial(port, baud, timeout=1)

if ser.isOpen():
    print(ser.name + ' is open...')

# STX, N, CR
to_send = b'\x02\x4e\x0d'
print "Sending {}".format(to_send)
ser.write(to_send)
out = ser.read()
print('Receiving...'+out)
</code>```

COM3 is the correct port:

Any help and guidance would be greatly appreciated.

答: I contacted the supplier in the end and the issue was setting to wrong baud rate. Changing from 9600 to 19200 resolved the problem.</p>

Body:
I have a USB device with the following specification. Page 22 describes the GNET protocol that should be used to interact with the device.

The connection is fine but the device just doesn't give me any response, so I think I am not sending the correct data to it, maybe missing the handshake?

From Specification

Support TTY (TELE TYPE) OPERATION - Use TTY to send commands and messages

Use ASCII value for each field and use Separator "," between two
   Fields.

connect_and_send.py

import serial

port = "COM3"
baud = 9600

ser = serial.Serial(port, baud, timeout=1)

if ser.isOpen():
    print(ser.name + ' is open...')

# STX, N, CR
to_send = b'\x02\x4e\x0d'
print "Sending {}".format(to_send)
ser.write(to_send)
out = ser.read()
print('Receiving...'+out)

COM3 is the correct port:

Any help and guidance would be greatly appreciated.


问:
KeyboardAvoidingView + ListView
I have a submission form interface，use ListView Component, and the row contain TextInput Component, I want to user KeyboardAvoidingView to avoid The Keyboard cover the TextInput in row , But it is not working,The row does not move up.

my code:

```<code> render() {
    return (
        <KeyboardAvoidingView style={styles.container}  behavior='padding'>
            <ListView
                dataSource = {this.state.dataSource}
                renderRow = {this._renderRow.bind(this)}
                onEndReachedThreshold = {0}
                overflow = 'hidden'
                keyboardDismissMode = 'on-drag'
                removeClippedSubviews = {true}
            />
        </KeyboardAvoidingView>
    );
}
</code>```

答:
There is one module which I have used for keyboard issue: https://github.com/APSL/react-native-keyboard-aware-scroll-view

You can use it same way:

```<code>import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
render() {
    return (
      <KeyboardAwareScrollView extraHeight={130}>
          // your code here
      </KeyboardAwareScrollView>
    );
  }
</code>```

Let me know if face any issue to use it.

Title: KeyboardAvoidingView + ListView

Body:
I have a submission form interface，use ListView Component, and the row contain TextInput Component, I want to user KeyboardAvoidingView to avoid The Keyboard cover the TextInput in row , But it is not working,The row does not move up.

my code:

 render() {
    return (
        <KeyboardAvoidingView style={styles.container}  behavior='padding'>
            <ListView
                dataSource = {this.state.dataSource}
                renderRow = {this._renderRow.bind(this)}
                onEndReachedThreshold = {0}
                overflow = 'hidden'
                keyboardDismissMode = 'on-drag'
                removeClippedSubviews = {true}
            />
        </KeyboardAvoidingView>
    );
}

Body:
There is one module which I have used for keyboard issue: https://github.com/APSL/react-native-keyboard-aware-scroll-view

You can use it same way:

import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
render() {
    return (
      <KeyboardAwareScrollView extraHeight={130}>
          // your code here
      </KeyboardAwareScrollView>
    );
  }

Let me know if face any issue to use it.


问:
When would getters and setters with mutex be thread safe?
Consider the following class:

```<code>class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};
</code>```

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?

答:
This is an absolute classic.
One thread obtains the value of var, releases the mutex and another obtains the same value before the first thread has chance to update it.

Consequently the process risks losing increments.

There are three obvious solutions:

```<code>void testThreads::inc_var(){
    std::lock_guard<std::mutex> lk(mtx);
    ++var;
}
</code>```

That's safe because the mutex is held until the variable is updated.

Next up:

```<code>bool testThreads::compare_and_inc_var(int val){
    std::lock_guard<std::mutex> lk(mtx);
    if(var!=val) return false;
    ++var;
    return true;
}

Then write code like:

   int val;
   do{
       val=get_var();
   }while(!compare_and_inc_var(val));
</code>```

This works because the loop repeats until it confirms it's updating the value it read. This could result in live-lock though in this case it has to be transient because a thread can only fail to make progress because another does.

Finally replace int var with std::atomic<int> var and either use ++var or var.compare_exchange(val,val+1) or var.fetch_add(1); to update it.
NB: Notice compare_exchange(var,var+1) is invalid...

++ is guaranteed to be atomic on std::atomic<> types but despite 'looking' like a single operation in general no such guarantee exists for int.

std::atomic<> also provides appropriate memory barriers (and ways to hint what kind of barrier is needed) to ensure proper inter-thread communication.

std::atomic<> should be a wait-free, lock-free implementation where available. Check your documentation and the flag is_lock_free().

Body:
Consider the following class:

class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?

Body:
This is an absolute classic.
One thread obtains the value of var, releases the mutex and another obtains the same value before the first thread has chance to update it.

Consequently the process risks losing increments.

There are three obvious solutions:

void testThreads::inc_var(){
    std::lock_guard<std::mutex> lk(mtx);
    ++var;
}

That's safe because the mutex is held until the variable is updated.

Next up:

bool testThreads::compare_and_inc_var(int val){
    std::lock_guard<std::mutex> lk(mtx);
    if(var!=val) return false;
    ++var;
    return true;
}

Then write code like:

   int val;
   do{
       val=get_var();
   }while(!compare_and_inc_var(val));

This works because the loop repeats until it confirms it's updating the value it read. This could result in live-lock though in this case it has to be transient because a thread can only fail to make progress because another does.

Finally replace int var with std::atomic<int> var and either use ++var or var.compare_exchange(val,val+1) or var.fetch_add(1); to update it.
NB: Notice compare_exchange(var,var+1) is invalid...

++ is guaranteed to be atomic on std::atomic<> types but despite 'looking' like a single operation in general no such guarantee exists for int.

std::atomic<> also provides appropriate memory barriers (and ways to hint what kind of barrier is needed) to ensure proper inter-thread communication.

std::atomic<> should be a wait-free, lock-free implementation where available. Check your documentation and the flag is_lock_free().