问:
How can i draw a Snake path using GoogleMaps?
That's How The Code Does It:

That's How I Want It

(1,2) "This Is What I Mean By Snake Trajectory The Other One Is"

This One Is Correct

Here I Want It To Be 3

(3,4) "I Want To Make It Draw Marker Correct Way
Example:

```<code>7 8 9
6 5 4
1 2 3
</code>```

I Have Tried Changing The Variable I And J And Editing Them To Find My Needs But I Couldn't Make It Everyone Tells Me It's Simple But Can't Figure It Out

for (double J = Lat1; J < Lat2; J += oneMeter) {

    for (double I = Lng1; I < Lng2-oneMeter; I += oneMeter) {
        if(I+oneMeter<=Lng2){
        mMap.addMarker(new MarkerOptions().title(markerNumber++ + "").position(new LatLng(J, I)).icon(BitmapDescriptorFactory.fromResource(R.drawable.pvpanels)));
        //Test
        Polyline line = mMap.addPolyline(new PolylineOptions().add(
                new LatLng(J, I),
                new LatLng(J, I+ oneMeter ))
                .width(10).color(Color.RED));}
        else if(I+oneMeter>Lng2){
            Polyline line = mMap.addPolyline(new PolylineOptions().add(
                    new LatLng(J, I- oneMeter),
                    new LatLng(J+oneMeter , I))
                    .width(10).color(Color.RED));
        }

    }
}
```

I Expect It To Do Snake Shape And The Correct Points Format Image 1 Transfer To 2 And 3 Transfer To 4

答:
Your question is unclear,
I am assuming that you have everything set-up and you're trying to connect to points in a Google Map with a path.

Step 1. add the following dependencies
    implementation 'com.google.code.gson:gson:2.6.1'
    implementation 'com.mcxiaoke.volley:library:1.0.19'

Step 2. in your map_activity.xml

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Step 3. in your MapsActivity.class

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener, GoogleApiClient.ConnectionCallbacks {
private static final String TAG = MapsActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private double latitudeValue = 0.0;
private double longitudeValue = 0.0;
private GoogleMap mMap;
private static final int PERMISSION_LOCATION_REQUEST_CODE = 100;
private List<LatLng> latLngList;
private MarkerOptions yourLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    latLngList = new ArrayList<LatLng>();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    }
    mLocationRequest = createLocationRequest();
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMapClickListener(this);
}
@Override
public void onMapClick(LatLng latLng) {
    if(latLngList.size() > 0){
        refreshMap(mMap);
        latLngList.clear();
    }
    latLngList.add(latLng);
    Log.d(TAG, "Marker number " + latLngList.size());
    mMap.addMarker(yourLocationMarker);
    mMap.addMarker(new MarkerOptions().position(latLng));
    LatLng defaultLocation = yourLocationMarker.getPosition();
    LatLng destinationLocation = latLng;
    //use Google Direction API to get the route between these Locations
    String directionApiPath = Helper.getUrl(String.valueOf(defaultLocation.latitude), String.valueOf(defaultLocation.longitude),
            String.valueOf(destinationLocation.latitude), String.valueOf(destinationLocation.longitude));
    Log.d(TAG, "Path " + directionApiPath);
    getDirectionFromDirectionApiServer(directionApiPath);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.d(TAG, "Connection method has been called");
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        assignLocationValues(mLastLocation);
                        setDefaultMarkerOption(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                    }else{
                        ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION_REQUEST_CODE);
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    break;
            }
        }
    });
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_LOCATION_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // permission was denied, show alert to explain permission
                showPermissionAlert();
            }else{
                //permission is granted now start a background service
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    assignLocationValues(mLastLocation);
                    setDefaultMarkerOption(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                }
            }
        }
    }
}
private void assignLocationValues(Location currentLocation){
    if (currentLocation != null) {
        latitudeValue = currentLocation.getLatitude();
        longitudeValue = currentLocation.getLongitude();
        Log.d(TAG, "Latitude: " + latitudeValue + " Longitude: " + longitudeValue);
        markStartingLocationOnMap(mMap, new LatLng(latitudeValue, longitudeValue));
        addCameraToMap(new LatLng(latitudeValue, longitudeValue));
    }
}
private void addCameraToMap(LatLng latLng){
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(latLng)
            .zoom(16)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void showPermissionAlert(){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.permission_request_title);
    builder.setMessage(R.string.app_permission_notice);
    builder.create();
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION_REQUEST_CODE);
            }
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MapsActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
        }
    });
    builder.show();
}
private void markStartingLocationOnMap(GoogleMap mapObject, LatLng location){
    mapObject.addMarker(new MarkerOptions().position(location).title("Current location"));
    mapObject.moveCamera(CameraUpdateFactory.newLatLng(location));
}
private void refreshMap(GoogleMap mapInstance){
    mapInstance.clear();
}
protected LocationRequest createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(5000);
    mLocationRequest.setFastestInterval(3000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    return mLocationRequest;
}
private void setDefaultMarkerOption(LatLng location){
    if(yourLocationMarker == null){
        yourLocationMarker = new MarkerOptions();
    }
    yourLocationMarker.position(location);
}
@Override
protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}
@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}
private void getDirectionFromDirectionApiServer(String url){
    GsonRequest<DirectionObject> serverRequest = new GsonRequest<DirectionObject>(
            Request.Method.GET,
            url,
            DirectionObject.class,
            createRequestSuccessListener(),
            createRequestErrorListener());
    serverRequest.setRetryPolicy(new DefaultRetryPolicy(
            Helper.MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(serverRequest);
}
private Response.Listener<DirectionObject> createRequestSuccessListener() {
    return new Response.Listener<DirectionObject>() {
        @Override
        public void onResponse(DirectionObject response) {
            try {
                Log.d("JSON Response", response.toString());
                if(response.getStatus().equals("OK")){
                    List<LatLng> mDirections = getDirectionPolylines(response.getRoutes());
                    drawRouteOnMap(mMap, mDirections);
                }else{
                    Toast.makeText(MapsActivity.this, R.string.server_error, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    };
}
private List<LatLng> getDirectionPolylines(List<RouteObject> routes){
    List<LatLng> directionList = new ArrayList<LatLng>();
    for(RouteObject route : routes){
        List<LegsObject> legs = route.getLegs();
        for(LegsObject leg : legs){
            List<StepsObject> steps = leg.getSteps();
            for(StepsObject step : steps){
                PolylineObject polyline = step.getPolyline();
                String points = polyline.getPoints();
                List<LatLng> singlePolyline = decodePoly(points);
                for (LatLng direction : singlePolyline){
                    directionList.add(direction);
                }
            }
        }
    }
    return directionList;
}
private Response.ErrorListener createRequestErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    };
}
private void drawRouteOnMap(GoogleMap map, List<LatLng> positions){
    PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
    options.addAll(positions);
    Polyline polyline = map.addPolyline(options);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(positions.get(1).latitude, positions.get(1).longitude))
            .zoom(17)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
/**
 * Method to decode polyline points
 * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
 * */
private List<LatLng> decodePoly(String encoded) {
    List<LatLng> poly = new ArrayList<>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return poly;
}
}
</code>```

RETURNED JSON RESPONSE OBJECT FROM GOOGLE DIRECTION API

The returned response object is a Json object and the direction path is stored in the Polyline class. This is the class structure of the Json response object. We are going to use the Gson library to convert it to plain Java object class.

And should look something like this:

```<code>{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJZymwbofzU0YRvgugqrVwH8Q",
         "types" : [ "street_address" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "EiJOeWdhdGFuIDMyLCAyNDIgMzEgSMO2cmJ5LCBTdmVyaWdl",
         "types" : [ "street_address" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 55.8541564,
               "lng" : 13.661235
            },
            "southwest" : {
               "lat" : 55.85187149999999,
               "lng" : 13.660381
            }
         },
         "copyrights" : "Map data ©2016 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "0.3 km",
                  "value" : 260
               },
               "duration" : {
                  "text" : "1 min",
                  "value" : 84
               },
               "end_address" : "Nygatan 32, 242 31 Hörby, Sweden",
               "end_location" : {
                  "lat" : 55.85187149999999,
                  "lng" : 13.660381
               },
               "start_address" : "Nygatan 12B, 242 31 Hörby, Sweden",
               "start_location" : {
                  "lat" : 55.8541564,
                  "lng" : 13.661235
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "0.3 km",
                        "value" : 260
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 84
                     },
                     "end_location" : {
                        "lat" : 55.85187149999999,
                        "lng" : 13.660381
                     },
                     "html_instructions" : "Head \u003cb\u003esouth\u003c/b\u003e on \u003cb\u003eNygatan\u003c/b\u003e toward \u003cb\u003eKvarngatan\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the left\u003c/div\u003e",
                     "polyline" : {
                        "points" : "o_|sIwekrAVHxBj@|Bh@nBr@d@Hb@L"
                     },
                     "start_location" : {
                        "lat" : 55.8541564,
                        "lng" : 13.661235
                     },
                     "travel_mode" : "DRIVING"
                  }
               ],
               "traffic_speed_entry" : [],
               "via_waypoint" : []
            }
         ],
         "overview_polyline" : {
            "points" : "o_|sIwekrApCt@|Bh@nBr@hAV"
         },
         "summary" : "Nygatan",
         "warnings" : [],
         "waypoint_order" : []
      }
   ],
   "status" : "OK"
}
</code>```

ENTITY OBJECT CLASSES

We will create the following classes to mimic the structure of the Json response object. The classes are

Starting with DIRECTIONOBJECT.JAVA

```<code>public class DirectionObject {
    private List<RouteObject> routes;
    private String status;
    public DirectionObject(List<RouteObject> routes, String status) {
        this.routes = routes;
        this.status = status;
    }
    public List<RouteObject> getRoutes() {
        return routes;
    }
    public String getStatus() {
        return status;
    }
}
</code>```

Next is LEGSOBJECT.JAVA

```<code>public class LegsObject {
    private List<StepsObject> steps;
    public LegsObject(List<StepsObject> steps) {
        this.steps = steps;
    }
    public List<StepsObject> getSteps() {
        return steps;
    }
}
</code>```

Now the POLYLINEOBJECT.JAVA

```<code>public class PolylineObject {
    private String points;
    public PolylineObject(String points) {
        this.points = points;
    }
    public String getPoints() {
        return points;
    }
}
</code>```

And the we create ROUTEOBJECT.JAVA

```<code>public class RouteObject {
    private List<LegsObject> legs;
    public RouteObject(List<LegsObject> legs) {
        this.legs = legs;
    }
    public List<LegsObject> getLegs() {
        return legs;
    }
}
</code>```

We're almost there! now create the next class which is STEPSOBJECTS.JAVA

```<code>public class StepsObject {
    private PolylineObject polyline;
    public StepsObject(PolylineObject polyline) {
        this.polyline = polyline;
    }
    public PolylineObject getPolyline() {
        return polyline;
    }
}
</code>```

After finishing setting up all of the classes above, now we move to setting up the network calls and API consumption!!

We will be using Volley for Network calls

Create this class:

```<code>public class CustomApplication extends Application{
    private RequestQueue requestQueue;
    @Override
    public void onCreate() {
        super.onCreate();
        requestQueue =
VolleySingleton.getInstance(getApplicationContext()).getRequestQueue();
    }
    public RequestQueue getVolleyRequestQueue(){
        return requestQueue;
    }
}
</code>```

Now the remaining classes are for the API consumption logic:

Now create a class and name it GsonRequest.java

```<code>public class GsonRequest<T> extends Request<T> {
// create variables
private Gson mGson = new Gson();
private Class<T> tClass;
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<T> listener;
public GsonRequest(int method, String url, Class<T> tClass, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.tClass = tClass;
    this.listener = listener;
    mGson = new Gson();
}
public GsonRequest(int method, String url, Class<T> tClass, Map<String, String> params, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.tClass = tClass;
    this.params = params;
    this.listener = listener;
    this.headers = null;
    mGson = new Gson();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers != null ? headers : super.getHeaders();
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
    return params;
}
protected void deliverResponse(T response) {
    listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
        String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(mGson.fromJson(json, tClass), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
        return Response.error(new ParseError(e));
    }
}
}
</code>```

VOLLEYSINGLETON.JAVA

Create a new Java class and name it VolleySingleton.java

```<code>public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
    mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }
        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    });
}
public static synchronized VolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new VolleySingleton(context);
    }
    return mInstance;
}
public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
    return mImageLoader;
}
}
</code>```

AND FINALLY

HELPER.JAVA

Create another Java class name it Helper.java

```<code>public class Helper {
    private static final String DIRECTION_API = "https://maps.googleapis.com/maps/api/directions/json?origin=";
    public static final String API_KEY = "AIzaSyCuZCfoPPUV1upJT10kJbCbV71LUqwhFCM";
    public static final int MY_SOCKET_TIMEOUT_MS = 5000;
    public static String getUrl(String originLat, String originLon, String destinationLat, String destinationLon){
        return Helper.DIRECTION_API + originLat+","+originLon+"&destination="+destinationLat+","+destinationLon+"&key="+API_KEY;
    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}
</code>```

Body:
That's How The Code Does It:

That's How I Want It

(1,2) "This Is What I Mean By Snake Trajectory The Other One Is"

This One Is Correct

Here I Want It To Be 3

(3,4) "I Want To Make It Draw Marker Correct Way
Example:

7 8 9
6 5 4
1 2 3

I Have Tried Changing The Variable I And J And Editing Them To Find My Needs But I Couldn't Make It Everyone Tells Me It's Simple But Can't Figure It Out

for (double J = Lat1; J < Lat2; J += oneMeter) {

    for (double I = Lng1; I < Lng2-oneMeter; I += oneMeter) {
        if(I+oneMeter<=Lng2){
        mMap.addMarker(new MarkerOptions().title(markerNumber++ + "").position(new LatLng(J, I)).icon(BitmapDescriptorFactory.fromResource(R.drawable.pvpanels)));
        //Test
        Polyline line = mMap.addPolyline(new PolylineOptions().add(
                new LatLng(J, I),
                new LatLng(J, I+ oneMeter ))
                .width(10).color(Color.RED));}
        else if(I+oneMeter>Lng2){
            Polyline line = mMap.addPolyline(new PolylineOptions().add(
                    new LatLng(J, I- oneMeter),
                    new LatLng(J+oneMeter , I))
                    .width(10).color(Color.RED));
        }

    }
}

I Expect It To Do Snake Shape And The Correct Points Format Image 1 Transfer To 2 And 3 Transfer To 4

Body:
Your question is unclear,
I am assuming that you have everything set-up and you're trying to connect to points in a Google Map with a path.

Step 1. add the following dependencies
    implementation 'com.google.code.gson:gson:2.6.1'
    implementation 'com.mcxiaoke.volley:library:1.0.19'

Step 2. in your map_activity.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Step 3. in your MapsActivity.class

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener, GoogleApiClient.ConnectionCallbacks {
private static final String TAG = MapsActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private double latitudeValue = 0.0;
private double longitudeValue = 0.0;
private GoogleMap mMap;
private static final int PERMISSION_LOCATION_REQUEST_CODE = 100;
private List<LatLng> latLngList;
private MarkerOptions yourLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    latLngList = new ArrayList<LatLng>();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    }
    mLocationRequest = createLocationRequest();
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMapClickListener(this);
}
@Override
public void onMapClick(LatLng latLng) {
    if(latLngList.size() > 0){
        refreshMap(mMap);
        latLngList.clear();
    }
    latLngList.add(latLng);
    Log.d(TAG, "Marker number " + latLngList.size());
    mMap.addMarker(yourLocationMarker);
    mMap.addMarker(new MarkerOptions().position(latLng));
    LatLng defaultLocation = yourLocationMarker.getPosition();
    LatLng destinationLocation = latLng;
    //use Google Direction API to get the route between these Locations
    String directionApiPath = Helper.getUrl(String.valueOf(defaultLocation.latitude), String.valueOf(defaultLocation.longitude),
            String.valueOf(destinationLocation.latitude), String.valueOf(destinationLocation.longitude));
    Log.d(TAG, "Path " + directionApiPath);
    getDirectionFromDirectionApiServer(directionApiPath);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.d(TAG, "Connection method has been called");
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        assignLocationValues(mLastLocation);
                        setDefaultMarkerOption(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                    }else{
                        ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION_REQUEST_CODE);
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    break;
            }
        }
    });
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_LOCATION_REQUEST_CODE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // permission was denied, show alert to explain permission
                showPermissionAlert();
            }else{
                //permission is granted now start a background service
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    assignLocationValues(mLastLocation);
                    setDefaultMarkerOption(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                }
            }
        }
    }
}
private void assignLocationValues(Location currentLocation){
    if (currentLocation != null) {
        latitudeValue = currentLocation.getLatitude();
        longitudeValue = currentLocation.getLongitude();
        Log.d(TAG, "Latitude: " + latitudeValue + " Longitude: " + longitudeValue);
        markStartingLocationOnMap(mMap, new LatLng(latitudeValue, longitudeValue));
        addCameraToMap(new LatLng(latitudeValue, longitudeValue));
    }
}
private void addCameraToMap(LatLng latLng){
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(latLng)
            .zoom(16)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void showPermissionAlert(){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.permission_request_title);
    builder.setMessage(R.string.app_permission_notice);
    builder.create();
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION_REQUEST_CODE);
            }
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MapsActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
        }
    });
    builder.show();
}
private void markStartingLocationOnMap(GoogleMap mapObject, LatLng location){
    mapObject.addMarker(new MarkerOptions().position(location).title("Current location"));
    mapObject.moveCamera(CameraUpdateFactory.newLatLng(location));
}
private void refreshMap(GoogleMap mapInstance){
    mapInstance.clear();
}
protected LocationRequest createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(5000);
    mLocationRequest.setFastestInterval(3000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    return mLocationRequest;
}
private void setDefaultMarkerOption(LatLng location){
    if(yourLocationMarker == null){
        yourLocationMarker = new MarkerOptions();
    }
    yourLocationMarker.position(location);
}
@Override
protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}
@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}
private void getDirectionFromDirectionApiServer(String url){
    GsonRequest<DirectionObject> serverRequest = new GsonRequest<DirectionObject>(
            Request.Method.GET,
            url,
            DirectionObject.class,
            createRequestSuccessListener(),
            createRequestErrorListener());
    serverRequest.setRetryPolicy(new DefaultRetryPolicy(
            Helper.MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(serverRequest);
}
private Response.Listener<DirectionObject> createRequestSuccessListener() {
    return new Response.Listener<DirectionObject>() {
        @Override
        public void onResponse(DirectionObject response) {
            try {
                Log.d("JSON Response", response.toString());
                if(response.getStatus().equals("OK")){
                    List<LatLng> mDirections = getDirectionPolylines(response.getRoutes());
                    drawRouteOnMap(mMap, mDirections);
                }else{
                    Toast.makeText(MapsActivity.this, R.string.server_error, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    };
}
private List<LatLng> getDirectionPolylines(List<RouteObject> routes){
    List<LatLng> directionList = new ArrayList<LatLng>();
    for(RouteObject route : routes){
        List<LegsObject> legs = route.getLegs();
        for(LegsObject leg : legs){
            List<StepsObject> steps = leg.getSteps();
            for(StepsObject step : steps){
                PolylineObject polyline = step.getPolyline();
                String points = polyline.getPoints();
                List<LatLng> singlePolyline = decodePoly(points);
                for (LatLng direction : singlePolyline){
                    directionList.add(direction);
                }
            }
        }
    }
    return directionList;
}
private Response.ErrorListener createRequestErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    };
}
private void drawRouteOnMap(GoogleMap map, List<LatLng> positions){
    PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
    options.addAll(positions);
    Polyline polyline = map.addPolyline(options);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(positions.get(1).latitude, positions.get(1).longitude))
            .zoom(17)
            .build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
/**
 * Method to decode polyline points
 * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
 * */
private List<LatLng> decodePoly(String encoded) {
    List<LatLng> poly = new ArrayList<>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;
    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    return poly;
}
}

RETURNED JSON RESPONSE OBJECT FROM GOOGLE DIRECTION API

The returned response object is a Json object and the direction path is stored in the Polyline class. This is the class structure of the Json response object. We are going to use the Gson library to convert it to plain Java object class.

And should look something like this:

{
   "geocoded_waypoints" : [
      {
         "geocoder_status" : "OK",
         "place_id" : "ChIJZymwbofzU0YRvgugqrVwH8Q",
         "types" : [ "street_address" ]
      },
      {
         "geocoder_status" : "OK",
         "place_id" : "EiJOeWdhdGFuIDMyLCAyNDIgMzEgSMO2cmJ5LCBTdmVyaWdl",
         "types" : [ "street_address" ]
      }
   ],
   "routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : 55.8541564,
               "lng" : 13.661235
            },
            "southwest" : {
               "lat" : 55.85187149999999,
               "lng" : 13.660381
            }
         },
         "copyrights" : "Map data ©2016 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "0.3 km",
                  "value" : 260
               },
               "duration" : {
                  "text" : "1 min",
                  "value" : 84
               },
               "end_address" : "Nygatan 32, 242 31 Hörby, Sweden",
               "end_location" : {
                  "lat" : 55.85187149999999,
                  "lng" : 13.660381
               },
               "start_address" : "Nygatan 12B, 242 31 Hörby, Sweden",
               "start_location" : {
                  "lat" : 55.8541564,
                  "lng" : 13.661235
               },
               "steps" : [
                  {
                     "distance" : {
                        "text" : "0.3 km",
                        "value" : 260
                     },
                     "duration" : {
                        "text" : "1 min",
                        "value" : 84
                     },
                     "end_location" : {
                        "lat" : 55.85187149999999,
                        "lng" : 13.660381
                     },
                     "html_instructions" : "Head \u003cb\u003esouth\u003c/b\u003e on \u003cb\u003eNygatan\u003c/b\u003e toward \u003cb\u003eKvarngatan\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the left\u003c/div\u003e",
                     "polyline" : {
                        "points" : "o_|sIwekrAVHxBj@|Bh@nBr@d@Hb@L"
                     },
                     "start_location" : {
                        "lat" : 55.8541564,
                        "lng" : 13.661235
                     },
                     "travel_mode" : "DRIVING"
                  }
               ],
               "traffic_speed_entry" : [],
               "via_waypoint" : []
            }
         ],
         "overview_polyline" : {
            "points" : "o_|sIwekrApCt@|Bh@nBr@hAV"
         },
         "summary" : "Nygatan",
         "warnings" : [],
         "waypoint_order" : []
      }
   ],
   "status" : "OK"
}

ENTITY OBJECT CLASSES

We will create the following classes to mimic the structure of the Json response object. The classes are

Starting with DIRECTIONOBJECT.JAVA

public class DirectionObject {
    private List<RouteObject> routes;
    private String status;
    public DirectionObject(List<RouteObject> routes, String status) {
        this.routes = routes;
        this.status = status;
    }
    public List<RouteObject> getRoutes() {
        return routes;
    }
    public String getStatus() {
        return status;
    }
}

Next is LEGSOBJECT.JAVA

public class LegsObject {
    private List<StepsObject> steps;
    public LegsObject(List<StepsObject> steps) {
        this.steps = steps;
    }
    public List<StepsObject> getSteps() {
        return steps;
    }
}

Now the POLYLINEOBJECT.JAVA

public class PolylineObject {
    private String points;
    public PolylineObject(String points) {
        this.points = points;
    }
    public String getPoints() {
        return points;
    }
}

And the we create ROUTEOBJECT.JAVA

public class RouteObject {
    private List<LegsObject> legs;
    public RouteObject(List<LegsObject> legs) {
        this.legs = legs;
    }
    public List<LegsObject> getLegs() {
        return legs;
    }
}

We're almost there! now create the next class which is STEPSOBJECTS.JAVA

public class StepsObject {
    private PolylineObject polyline;
    public StepsObject(PolylineObject polyline) {
        this.polyline = polyline;
    }
    public PolylineObject getPolyline() {
        return polyline;
    }
}

After finishing setting up all of the classes above, now we move to setting up the network calls and API consumption!!

We will be using Volley for Network calls

Create this class:

public class CustomApplication extends Application{
    private RequestQueue requestQueue;
    @Override
    public void onCreate() {
        super.onCreate();
        requestQueue =
VolleySingleton.getInstance(getApplicationContext()).getRequestQueue();
    }
    public RequestQueue getVolleyRequestQueue(){
        return requestQueue;
    }
}

Now the remaining classes are for the API consumption logic:

Now create a class and name it GsonRequest.java

public class GsonRequest<T> extends Request<T> {
// create variables
private Gson mGson = new Gson();
private Class<T> tClass;
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<T> listener;
public GsonRequest(int method, String url, Class<T> tClass, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.tClass = tClass;
    this.listener = listener;
    mGson = new Gson();
}
public GsonRequest(int method, String url, Class<T> tClass, Map<String, String> params, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    this.tClass = tClass;
    this.params = params;
    this.listener = listener;
    this.headers = null;
    mGson = new Gson();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers != null ? headers : super.getHeaders();
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
    return params;
}
protected void deliverResponse(T response) {
    listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
        String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(mGson.fromJson(json, tClass), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
        return Response.error(new ParseError(e));
    }
}
}

VOLLEYSINGLETON.JAVA

Create a new Java class and name it VolleySingleton.java

public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();
    mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }
        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    });
}
public static synchronized VolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new VolleySingleton(context);
    }
    return mInstance;
}
public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
    return mImageLoader;
}
}

AND FINALLY

HELPER.JAVA

Create another Java class name it Helper.java

public class Helper {
    private static final String DIRECTION_API = "https://maps.googleapis.com/maps/api/directions/json?origin=";
    public static final String API_KEY = "AIzaSyCuZCfoPPUV1upJT10kJbCbV71LUqwhFCM";
    public static final int MY_SOCKET_TIMEOUT_MS = 5000;
    public static String getUrl(String originLat, String originLon, String destinationLat, String destinationLon){
        return Helper.DIRECTION_API + originLat+","+originLon+"&destination="+destinationLat+","+destinationLon+"&key="+API_KEY;
    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}


来源: stackexchange

问:
CSS - element custom radius?
I am trying to add a custom border radius like this hero image: https://www.magicleap.com/magic-leap-one

I am aware that it's the image that does that, my question is can I do something like that using CSS?

答:
Try this out. Hope this is what you're looking for.

body {
  margin: 0;
  padding: 0;
}

.block {
  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(https://s1.kkday.com/images/product/8163/20170301045421_Nkoag.jpg);
  background-size: cover;
  background-repeat: no-repeat;
  color: #fff;
  width: 100%;
  padding: 150px 0;
  text-align: center;
  border-bottom-left-radius: 100% 15%;
  border-bottom-right-radius: 100% 15%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block">
  <h1>
    Hello World!
  </h1>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: CSS - element custom radius?

Body:
Try this out. Hope this is what you're looking for.

body {
  margin: 0;
  padding: 0;
}

.block {
  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(https://s1.kkday.com/images/product/8163/20170301045421_Nkoag.jpg);
  background-size: cover;
  background-repeat: no-repeat;
  color: #fff;
  width: 100%;
  padding: 150px 0;
  text-align: center;
  border-bottom-left-radius: 100% 15%;
  border-bottom-right-radius: 100% 15%;
}

<div class="block">
  <h1>
    Hello World!
  </h1>
</div>


问:
Rearranging div elements using purely CSS
My site's main stylesheet has the div elements arranged in a very particular order. In my print stylesheet, I wish to rearrange the order of my div elements using purely CSS. How can I do this?

Presume these to be divs in my main stylesheet:

a d

b e

c f

I want it to look like this on my print stylesheet (I remove non-printer friendly divs):

a

f

c

d

答:
You can remove the unwanted divs and stack the remaining divs like this...

http://jsfiddle.net/ywTJy/2/

```<code>
div {
    width: 50%;
    background-color: #ccc;
    float: left;
}

/* print CSS */

div {
    float: none;
    width: 100%;
}

#b, #e {
    display: none;
}
</code>```

I'm not sure if you intentionally want to move the "F" div to the 2nd position but it seems awkward if you would order your content one way for the Web and re-order it for print.

ContentLicense: CC BY-SA 3.0

Body:
You can remove the unwanted divs and stack the remaining divs like this...

http://jsfiddle.net/ywTJy/2/

div {
    width: 50%;
    background-color: #ccc;
    float: left;
}

/* print CSS */

div {
    float: none;
    width: 100%;
}

#b, #e {
    display: none;
}

I'm not sure if you intentionally want to move the "F" div to the 2nd position but it seems awkward if you would order your content one way for the Web and re-order it for print.


问:
How override the OAuthView with a custom view?
How do you set the provider login as the default login page, instead of being navigated to the OAuth page where you need to select the provider?</p>

答:
I used JS in the login_oauth.html page to override the initial load and redirect as soon as it hit the page.

window.location = "/login/";

e.g. "http://localhost:port/login/google"


问:
How to active a button only when a file uploaded and checked terms and conditions?
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

```<code>    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });
</code>```

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>
```

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

答:
You can do like this

// find elements
var fileCtrl = $("#employeelist");
var termsCtrl = $("#termsNcon");
var btn = $("#stripe-button");

function checkValidation() {
 if(fileCtrl.val() && termsCtrl.prop("checked")) {
   btn.attr("disabled", false);
  }
  else {
   btn.attr("disabled", true);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" onchange="checkValidation()" />
<br />
<input type="checkbox" name="termsNcon" id="termsNcon" onchange="checkValidation()" /> <label for="termsNcon">I have read and agree to the Terms and Conditions and Privacy Policy</label>
<br />
<button id="stripe-button" disabled>Continue to Pay</button></code>```

Body:
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

Body:
You can do like this

// find elements
var fileCtrl = $("#employeelist");
var termsCtrl = $("#termsNcon");
var btn = $("#stripe-button");

function checkValidation() {
 if(fileCtrl.val() && termsCtrl.prop("checked")) {
   btn.attr("disabled", false);
  }
  else {
   btn.attr("disabled", true);
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" onchange="checkValidation()" />
<br />
<input type="checkbox" name="termsNcon" id="termsNcon" onchange="checkValidation()" /> <label for="termsNcon">I have read and agree to the Terms and Conditions and Privacy Policy</label>
<br />
<button id="stripe-button" disabled>Continue to Pay</button>


问:
Select column based on cell
I have a df like so:

```<code>color=c('red','red','blue')
red = c(10,30,50)
blue = c(123,456,789)
df = data.frame(color,red,blue)
</code>```

FOr each row, I would like to select the column value according to which colname is equal to the value in the color column

eg:

```<code>color2=c('red','red','blue')
answer=c(10,30,789)
df2=data.frame(color2, answer)
</code>```

I have tried:
test=match(df$color, names(df))
test2 = df[,test]

but this gives me:

```<code>red=c(10,30,30)
red.1=c(10,30,30)
blue=c(123,456,789)

wrong = data.frame(red,red.1,blue)
</code>```

答:
We can use row index along with the column index from match to extract the values

```<code>cbind(df[1], answer = df[-1][cbind(seq_len(nrow(df)),
                       match(df$color, names(df)[-1]) )])
#    color answer
#1   red     10
#2   red     30
#3  blue    789
</code>```

Title: Select column based on cell

Body:
I have a df like so:

color=c('red','red','blue')
red = c(10,30,50)
blue = c(123,456,789)
df = data.frame(color,red,blue)

FOr each row, I would like to select the column value according to which colname is equal to the value in the color column

eg:

color2=c('red','red','blue')
answer=c(10,30,789)
df2=data.frame(color2, answer)

I have tried:
test=match(df$color, names(df))
test2 = df[,test]

but this gives me:

red=c(10,30,30)
red.1=c(10,30,30)
blue=c(123,456,789)

wrong = data.frame(red,red.1,blue)

Body:
We can use row index along with the column index from match to extract the values

cbind(df[1], answer = df[-1][cbind(seq_len(nrow(df)),
                       match(df$color, names(df)[-1]) )])
#    color answer
#1   red     10
#2   red     30
#3  blue    789


问:
Greying out certain parts of html until a radio button is checked
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

```<code><div class="line">
    <label><span>1.</span>This is a first question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
<div class="line">
    <label><span>2.</span>This is a second question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>

<div class="line">
    <label><span>3.</span>This is a third question?</label>
    <div class="right-box small">
        <input type="radio" name="" value=""><label style="padding-left: 3px; padding-right: 24px;">No</label><input type="radio" name="" value=""><label style="padding-left: 3px;">Yes</label>
    </div>
</div>
</code>```

答:
You could use this at the start to disable all radio buttons

```<code>$('.line').find('input').attr('disabled','true');
</code>```

Then this for each time a radio button is checked

```<code>$('.line').find('input').click(function(){
   $(this).parents('.line').siblings('.line:next').find('input').removeAttr('disabled');
});
</code>```

Or this may also work, slightly shorter

```<code>$('.line input').click(function(){
   $(this).parents('.line').next('.line input').removeAttr('disabled');
});
</code>```

Body:
I have a weird request i havent had before and im not sure how to go about it.

Basically i have an online application form, each question is contained in its own div, at first i want the first div shown and the rest of the questions to be 'greyed' out, then when someone clicks a radio button for the first question, the second question then ungreys itself and so on.

The code for the HTML i have so far is below, i was wondering if someone could help me out with this.

    1.This is a first question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    2.This is a second question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

    3.This is a third question?

        <input type="radio" name="" value="">No<input type="radio" name="" value="">Yes

Body:
You could use this at the start to disable all radio buttons

$('.line').find('input').attr('disabled','true');

Then this for each time a radio button is checked

$('.line').find('input').click(function(){
   $(this).parents('.line').siblings('.line:next').find('input').removeAttr('disabled');
});

Or this may also work, slightly shorter

$('.line input').click(function(){
   $(this).parents('.line').next('.line input').removeAttr('disabled');
});


问:
Solve equation using optim()
I have 2 equation that need to be solved by using optim

```<code>{(4x^2-20x+1/4 y^2+8=0
  1/2 xy^2+2x-5y+8=0)
</code>```

I have already run the code,but I'm confused if there should be 1 answer or 2 because function will only return the results for the last line

Should I do like this

```<code>> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

and

```<code>>  myfunc=function(x){
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

or should I do like this

```<code>> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")
</code>```

For the second one it still give me only the answer for the second function so which method is correct.

答:
You can also use a package for solving systems of non linear equations such as nleqslv.

Slightly redefine your function by making it return a vector containing the result for each equation

```<code>myfunc <- function(x){
    y <- numeric(length(x))
    y[1] <- 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
    y[2] <- (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
    y
}
</code>```

Define a starting value for the solver

```<code>xstart <- c(0,0)
</code>```

Then do this

```<code>library(nleqslv)
nleqslv(xstart,myfunc)
</code>```

giving

```<code>$x
[1] 0.5 2.0

$fvec
[1] -1.472252e-09 -7.081979e-10

$termcd
[1] 1

$message
[1] "Function criterion near zero"

$scalex
[1] 1 1

$nfcnt
[1] 7

$njcnt
[1] 1

$iter
[1] 7
</code>```

There are more packages that can solve equation systems such as BB and pracma.

Title: Solve equation using optim()

Body:
I have 2 equation that need to be solved by using optim

{(4x^2-20x+1/4 y^2+8=0
  1/2 xy^2+2x-5y+8=0)

I have already run the code,but I'm confused if there should be 1 answer or 2 because function will only return the results for the last line

Should I do like this

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

and

>  myfunc=function(x){
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

or should I do like this

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

For the second one it still give me only the answer for the second function so which method is correct.

Body:
You can also use a package for solving systems of non linear equations such as nleqslv.

Slightly redefine your function by making it return a vector containing the result for each equation

myfunc <- function(x){
    y <- numeric(length(x))
    y[1] <- 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
    y[2] <- (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
    y
}

Define a starting value for the solver

xstart <- c(0,0)

Then do this

library(nleqslv)
nleqslv(xstart,myfunc)

giving

$x
[1] 0.5 2.0

$fvec
[1] -1.472252e-09 -7.081979e-10

$termcd
[1] 1

$message
[1] "Function criterion near zero"

$scalex
[1] 1 1

$nfcnt
[1] 7

$njcnt
[1] 1

$iter
[1] 7

There are more packages that can solve equation systems such as BB and pracma.


问:
When I run this code I get error admin is not defined
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

```<code>function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}
</code>```

答:
@prabhat make sure you have included the require libraries in your application.

```<code><body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-firestore.js"></script>
<body>
</code>```

Here is the link for the reference: https://firebase.google.com/docs/web/setup#libraries_CDN

Try change admin with firebase if it not works... do setup the code with node modules.

```<code>https://firebase.google.com/docs/admin/setup#add_the_sdk

npm install firebase-admin --save

// To use the module in your application, require it from any JavaScript file:

var admin = require('firebase-admin');

import * as admin from 'firebase-admin';
</code>```

Body:
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}

Body:
@prabhat make sure you have included the require libraries in your application.

<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-firestore.js"></script>
<body>

Here is the link for the reference: https://firebase.google.com/docs/web/setup#libraries_CDN

Try change admin with firebase if it not works... do setup the code with node modules.

https://firebase.google.com/docs/admin/setup#add_the_sdk

npm install firebase-admin --save

// To use the module in your application, require it from any JavaScript file:

var admin = require('firebase-admin');

import * as admin from 'firebase-admin';


问:
Advice/ on how to plot side by side histograms with line graph going through in ggplot2
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

```<code>ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")
</code>```

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

```<code>opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))
</code>```

答:
You could do a variant on this using geom_violin instead of using histograms, although you wouldn't get labelled counts, just an idea of the relative density. Example with made up data:

```<code>df = data.frame(
    rho = rep(c(0.1, 0.2, 0.3), each = 50),
    val = sample(1:10, 150, replace = TRUE)
)
df$val = df$val + (5 * (df$rho == 0.2)) + (8 * (df$rho == 0.3))

ggplot(df, aes(x = rho, y = val, fill = factor(rho))) +
    geom_violin() +
    stat_summary(aes(group = 1), colour = "black",
                 geom = "line", fun.y = "median")
</code>```

This produces a violin for each value of rho, and joins the medians for each violin.

Body:
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))

Body:
You could do a variant on this using geom_violin instead of using histograms, although you wouldn't get labelled counts, just an idea of the relative density. Example with made up data:

df = data.frame(
    rho = rep(c(0.1, 0.2, 0.3), each = 50),
    val = sample(1:10, 150, replace = TRUE)
)
df$val = df$val + (5 * (df$rho == 0.2)) + (8 * (df$rho == 0.3))

ggplot(df, aes(x = rho, y = val, fill = factor(rho))) +
    geom_violin() +
    stat_summary(aes(group = 1), colour = "black",
                 geom = "line", fun.y = "median")

This produces a violin for each value of rho, and joins the medians for each violin.


问:
Value of type 'System.Data.OleDb.OleDbConnection' cannot be converted to 'System.Data.OleDb.OleDbCommand' in vb.net in oledb
I am trying to run this command

```<code>SELECT *
FROM [Sheet1$] AS A INNER JOIN [Orders$] IN'C:\Users\reddy\Desktop\Orders.xlsx' 'Excel 8.0;'
AS B
ON A.ContactName = B.ContactName;
</code>```

but I am getting an error

"Internal: Could not execute code stage because exception is thrown by
  code stage: Fill: SelectCommand.Connection property has not been
  initialized"

```<code>Dim oComm As New OleDbCommand

        Dim oledbAdapter As new OleDbDataAdapter(SQL,moconnection)

        Dim oDataSet As New DataSet
                oledbAdapter.Fill(oDataSet)
                oledbAdapter.Dispose()
</code>```

But I expected that Command should execute by that code

答:
I am not sure about the join and I can't test it. When it comes to Excel, the .xlsx file is the database and each sheet is a table. I am hoping both Sheet1 and Orders are in the same file. If not you will need to approach this differently with 2 connections and a DataSet that can hold both DataTables where a relationship can be establish.</p>

```<code>Private Sub OPCode()
    Dim dt As New DataTable
    Dim strFileName As String = "C:\Users\reddy\Desktop\Orders.xlsx"
    Dim strCon As String = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={strFileName};Extended Properties=""Excel 12.0;HDR=YES;"""
    Using cn = New OleDbConnection(strCon)
        Dim sql = "Select * FROM [Sheet1$] As A INNER JOIN [Orders$] AS B On A.ContactName = B.ContactName;"
        Using cmd As New OleDbCommand(sql, cn)
            cn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
    End Using
    DataGridView1.DataSource = dt
End Sub
</code>```

Body:
I am trying to run this command

SELECT *
FROM [Sheet1$] AS A INNER JOIN [Orders$] IN'C:\Users\reddy\Desktop\Orders.xlsx' 'Excel 8.0;'
AS B
ON A.ContactName = B.ContactName;

but I am getting an error

"Internal: Could not execute code stage because exception is thrown by
  code stage: Fill: SelectCommand.Connection property has not been
  initialized"

Dim oComm As New OleDbCommand

        Dim oledbAdapter As new OleDbDataAdapter(SQL,moconnection)

        Dim oDataSet As New DataSet
                oledbAdapter.Fill(oDataSet)
                oledbAdapter.Dispose()

But I expected that Command should execute by that code

Body:
I am not sure about the join and I can't test it. When it comes to Excel, the .xlsx file is the database and each sheet is a table. I am hoping both Sheet1 and Orders are in the same file. If not you will need to approach this differently with 2 connections and a DataSet that can hold both DataTables where a relationship can be establish.

Private Sub OPCode()
    Dim dt As New DataTable
    Dim strFileName As String = "C:\Users\reddy\Desktop\Orders.xlsx"
    Dim strCon As String = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={strFileName};Extended Properties=""Excel 12.0;HDR=YES;"""
    Using cn = New OleDbConnection(strCon)
        Dim sql = "Select * FROM [Sheet1$] As A INNER JOIN [Orders$] AS B On A.ContactName = B.ContactName;"
        Using cmd As New OleDbCommand(sql, cn)
            cn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
    End Using
    DataGridView1.DataSource = dt
End Sub


问:
AngularJS $http header for getting token
I am very new to angularJS.
in my angular app, there is a form for login. i checked the API login endpoint on postman and i notice it generates a token after successfully logged in.

I have a form to add blog post.

I want only logged in user can add blog post. below snippet are associate with my add blog form, currently i cant post through this form, coz, it doesn't get authenticated, even if i logged in with my login form.

but it works nice on postman.

I heard of $http header but not getting how to implement this.

It falls me in trouble for last 7 days, yet i couldnt fix this issue.

can anyone help to fix this?

Thanks

```<code>   $http({
            method: 'POST',
            url: 'http://127.0.0.1:8000/api/v1/blog',
            data: $scope.formBlogModel
        }).then(function (response) {
            $scope.success = 'post success'
        }, function(response) {
            $scope.error = "an error occured";
        });
</code>```

答:
Add headers property, also you can implement interceptors:

```<code>$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/api/v1/blog',
    data: $scope.formBlogModel,
    headers: {
        'Authorization': 'Bearer ' + token
    }
}).then(function (response) {
    $scope.success = 'post success'
}, function(response) {
    $scope.error = "an error occured";
});
</code>```

Body:
I am very new to angularJS.
in my angular app, there is a form for login. i checked the API login endpoint on postman and i notice it generates a token after successfully logged in.

I have a form to add blog post.

I want only logged in user can add blog post. below snippet are associate with my add blog form, currently i cant post through this form, coz, it doesn't get authenticated, even if i logged in with my login form.

but it works nice on postman.

I heard of $http header but not getting how to implement this.

It falls me in trouble for last 7 days, yet i couldnt fix this issue.

can anyone help to fix this?

Thanks

   $http({
            method: 'POST',
            url: 'http://127.0.0.1:8000/api/v1/blog',
            data: $scope.formBlogModel
        }).then(function (response) {
            $scope.success = 'post success'
        }, function(response) {
            $scope.error = "an error occured";
        });

Body:
Add headers property, also you can implement interceptors:

$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/api/v1/blog',
    data: $scope.formBlogModel,
    headers: {
        'Authorization': 'Bearer ' + token
    }
}).then(function (response) {
    $scope.success = 'post success'
}, function(response) {
    $scope.error = "an error occured";
});


问:
should I be using pipenv in my travis-ci tests? best practices?
I'm getting the following message when running some predefined Pipenv scripts in Travis-CI, and it bring me to the question of; should I be running Pipenv at all in a Travis environment? Does it defeat the purpose of the CI tests?

Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.

What is the best practice when you use Pipenv for development, and use Travis for CI? Should I be manually running the scripts below that map to pipenv run unit_test instead? See below for a section of my Pipfile.

.travis.yml:

```<code>language: python
python:
  - "3.6"
install:
  - pip install pipenv
  - pipenv install --dev
script:
  - pipenv run unit_tests
  - pipenv run linting
  - pipenv run docs
</code>```

Pipfile:

```<code>[scripts]
deploy = "python ./deploy.py"
docs = "python ./docs.py"
linting = "pylint **/*.py"
unit_tests = "python -m pytest --cov=marian tests"
serve = "sh ./serve.sh"
</code>```

答:
so Travis is using pipenv itself for the virtual env. So, seems awkward beyond installing via pipenv install --dev. I dropped all Pipfile scripts, and went with the following in .travis.yml

```<code>install:
- pip install pipenv
- pipenv install --dev
script:
- pylint **/*.py
- python -m pytest --cov=marian
- python ./docs.py
</code>```

Body:
I'm getting the following message when running some predefined Pipenv scripts in Travis-CI, and it bring me to the question of; should I be running Pipenv at all in a Travis environment? Does it defeat the purpose of the CI tests?

Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.

What is the best practice when you use Pipenv for development, and use Travis for CI? Should I be manually running the scripts below that map to pipenv run unit_test instead? See below for a section of my Pipfile.

.travis.yml:

language: python
python:
  - "3.6"
install:
  - pip install pipenv
  - pipenv install --dev
script:
  - pipenv run unit_tests
  - pipenv run linting
  - pipenv run docs

Pipfile:

[scripts]
deploy = "python ./deploy.py"
docs = "python ./docs.py"
linting = "pylint **/*.py"
unit_tests = "python -m pytest --cov=marian tests"
serve = "sh ./serve.sh"

Body:
so Travis is using pipenv itself for the virtual env. So, seems awkward beyond installing via pipenv install --dev. I dropped all Pipfile scripts, and went with the following in .travis.yml

install:
- pip install pipenv
- pipenv install --dev
script:
- pylint **/*.py
- python -m pytest --cov=marian
- python ./docs.py


问:
How to save grayscale image in Python?
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

```<code>import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()
</code>```

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.

答:
Using a DPI that matches the image size seems to make a difference.

The image is of size width=2240 and height=1488 (img_DR.shape). Using fig.get_size_inches() I see that the image size in inches is array([7.24, 5.34]). So an appropriate dpi is about 310 since 2240/7.24=309.4 and 1488/5.34=278.65.

Now I do plt.savefig('DR.png', dpi=310) and get

One experiment to do would be to choose a high enough DPI, calculate height and width of figure in inches, for example width_inch = width_pixel/DPI and set figure size using plt.figure(figsize=(width_inch, height_inch)), and see if the displayed image itself would increase/decrease in quality.

Hope this helps.

Title: How to save grayscale image in Python?

Body:
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.


问:
Get method is not working in Restsharp using C#
Get Method is not working... below code display all names or other attributes in richtext box from json using restsharp...there is no error but Ouput is not came help me to solve this...

```<code>var client = new RestClient("http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2");
var request = new RestRequest(Method.GET);
var queryResult = client.Execute<List<Detail>>(request).Data;
foreach (var rl in queryResult)
     {
        richTextBox1.Text = rl.name;
     }

public class Detail
    {
        public string city { get; set; }
        public int id { get; set; }
        public string Blood { get; set; }
        public string name { get; set; }
    }
</code>```

Here is json

```<code>{
  "Details": [
    {
      "city": "Londan",
      "id": 1,
      "Blood": "O+",
      "name": "Nicolas"
    },
    {
      "city": "USA",
      "id": 2,
      "Blood": "A+",
      "name": "Jhon"
    },
    {
      "city": "India",
      "id": 3,
      "Blood": "B-",
      "name": "Shiva"
    }
  ]
}
</code>```

答:
I see two problems:

1) "http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2" - doesn't work

2) If you provided a correct JSON example then you should use "RootObject" here:

```<code>client.Execute<List<Detail>>(request).Data;
</code>```

Body:
Get Method is not working... below code display all names or other attributes in richtext box from json using restsharp...there is no error but Ouput is not came help me to solve this...

var client = new RestClient("http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2");
var request = new RestRequest(Method.GET);
var queryResult = client.Execute<List<Detail>>(request).Data;
foreach (var rl in queryResult)
     {
        richTextBox1.Text = rl.name;
     }

public class Detail
    {
        public string city { get; set; }
        public int id { get; set; }
        public string Blood { get; set; }
        public string name { get; set; }
    }

Here is json

{
  "Details": [
    {
      "city": "Londan",
      "id": 1,
      "Blood": "O+",
      "name": "Nicolas"
    },
    {
      "city": "USA",
      "id": 2,
      "Blood": "A+",
      "name": "Jhon"
    },
    {
      "city": "India",
      "id": 3,
      "Blood": "B-",
      "name": "Shiva"
    }
  ]
}

Body:
I see two problems:

1) "http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2" - doesn't work

2) If you provided a correct JSON example then you should use "RootObject" here:

client.Execute<List<Detail>>(request).Data;


问:
Emulator Showing Old Red Phone

When I select any emulator, I'm getting this weird old red phone. The screen is super small and I can't see anything. I've tried searching, but it looks like no one else has had this problem. Does anyone recognize it? My emulators did work fine, but I had to uninstall and reinstall Android Studio because it broke. After reinstalling, this is what's happening :/

答:
Open AVD Manager in Android studio

Select the target emulator and click edit

Click Show Advanced Setting

In the Boot Option section select Cold Boot

Click on Finish

This solved my problem

Title: Emulator Showing Old Red Phone


问:
How to create an immutable map/set from a seq?
I am try to construct immutable Sets/Maps from a Seq.  I am currently doing the following:

```<code>val input: Seq[(String, Object)] = //.....
Map[String, Object]() ++ input
</code>```

and for sets

```<code>val input: Seq[String] = //.....
Set[String]() ++ input
</code>```

Which seems a little convoluted, is there a better way?

答:
To convert a Seq to a Map, simply call toMap on the Seq. Note that the elements of the Seq must be Tuple2 ie. (X,Y) or (X->Y)

```<code>scala> val seq: Seq[(String,String)] = ("A","a")::("B","b")::("C","c")::Nil
seq: Seq[(java.lang.String, java.lang.String)] = List((A,a), (B,b), (C,c))

scala> seq.toMap
res0: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,a), (B,b), (C,c))
</code>```

To convert a Seq to a Set, simply call toSet on the Seq.

```<code>scala> val seq: Seq[String] = "a"::"b"::"c"::Nil
seq: Seq[java.lang.String] = List(a, b, c)

scala> seq.toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am try to construct immutable Sets/Maps from a Seq.  I am currently doing the following:

val input: Seq[(String, Object)] = //.....
Map[String, Object]() ++ input

and for sets

val input: Seq[String] = //.....
Set[String]() ++ input

Which seems a little convoluted, is there a better way?

Body:
To convert a Seq to a Map, simply call toMap on the Seq. Note that the elements of the Seq must be Tuple2 ie. (X,Y) or (X->Y)

scala> val seq: Seq[(String,String)] = ("A","a")::("B","b")::("C","c")::Nil
seq: Seq[(java.lang.String, java.lang.String)] = List((A,a), (B,b), (C,c))

scala> seq.toMap
res0: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,a), (B,b), (C,c))

To convert a Seq to a Set, simply call toSet on the Seq.

scala> val seq: Seq[String] = "a"::"b"::"c"::Nil
seq: Seq[java.lang.String] = List(a, b, c)

scala> seq.toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)


问:
How to remove the inscription in Navigation Bar and leave arrow
I need to remove the inscription next to the arrow. Do as shown in the screenshot

This is my photo

That's how i need to do

答:
In the UIViewController subclass where you want a back arrow without the text, do the following in viewDidLoad

```<code>navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
</code>```

Body:
In the UIViewController subclass where you want a back arrow without the text, do the following in viewDidLoad

navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)


问:
Unable to do bundle install and gem install bundler -v 1.17.3 with ruby version ruby-1.8.7-p374
OS in use:  Mac OS High Sierra
Version: 10.13.6

I have an RVM installed with the following Ruby versions:

```<code>
MAC-070618-A:website anujaw$ rvm list
   ruby-1.8.7-head [ i686 ]
   ruby-1.8.7-p358 [ i686 ]
=> ruby-1.8.7-p374 [ i686 ]
 * ruby-2.3.7 [ x86_64 ]
   ruby-2.4.0 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

</code>```

Ruby version I need for running an app locally on my machine is: ruby-1.8.7-p374
I am trying to do a bundle install and getting below error:

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems.rb:241:in `bin_path': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)
    from /usr/local/bin/bundle:22:in `<main>'

</code>```

When I do gem install bundler as below, I get an error:

```<code>
MAC-070618-A:website anujaw$ gem install bundler -v 1.17.3
ERROR:  Loading command: install (LoadError)
    no such file to load -- openssl
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

</code>```

I already have OpenSSL installed, see below:

```<code>    MAC-070618-A:website anujaw$ brew info openssl
    openssl: stable 1.0.2q (bottled) [keg-only]
    SSL/TLS cryptography library
    https://openssl.org/
    /usr/local/Cellar/openssl/1.0.2o_2 (1,792 files, 12.3MB)
      Poured from bottle on 2018-07-23 at 14:37:12
    /usr/local/Cellar/openssl/1.0.2q (1,794 files, 12.1MB)
      Poured from bottle on 2019-01-30 at 14:12:51
    From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/openssl.rb
    ==> Caveats
    A CA file has been bootstrapped using certificates from the SystemRoots
    keychain. To add additional certificates (e.g. the certificates added in
    the System keychain), place .pem files in
      /usr/local/etc/openssl/certs

    and run
      /usr/local/opt/openssl/bin/c_rehash

    openssl is keg-only, which means it was not symlinked into /usr/local,
    because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

    If you need to have openssl first in your PATH run:
      echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

    For compilers to find openssl you may need to set:
      export LDFLAGS="-L/usr/local/opt/openssl/lib"
      export CPPFLAGS="-I/usr/local/opt/openssl/include"

    For pkg-config to find openssl you may need to set:
      export PKG_CONFIG_PATH="/usr/local/opt/openssl/lib/pkgconfig"

    ==> Analytics
    install: 465,985 (30 days), 1,553,385 (90 days), 6,076,848 (365 days)
    install_on_request: 59,235 (30 days), 217,436 (90 days), 854,397 (365 days)
    build_error: 0 (30 days)

</code>```

Kindly advise how to get past this obstacle? Thanks.

答:
Try running these command for your problem.

sudo gem install -n /usr/local/bin bundler -v 1.17.3

Then, Install Ruby dependencies

bundle install

Body:
OS in use:  Mac OS High Sierra
Version: 10.13.6

I have an RVM installed with the following Ruby versions:

MAC-070618-A:website anujaw$ rvm list
   ruby-1.8.7-head [ i686 ]
   ruby-1.8.7-p358 [ i686 ]
=> ruby-1.8.7-p374 [ i686 ]
 * ruby-2.3.7 [ x86_64 ]
   ruby-2.4.0 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

Ruby version I need for running an app locally on my machine is: ruby-1.8.7-p374
I am trying to do a bundle install and getting below error:

/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems.rb:241:in `bin_path': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)
    from /usr/local/bin/bundle:22:in `'

When I do gem install bundler as below, I get an error:

MAC-070618-A:website anujaw$ gem install bundler -v 1.17.3
ERROR:  Loading command: install (LoadError)
    no such file to load -- openssl
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

I already have OpenSSL installed, see below:

    MAC-070618-A:website anujaw$ brew info openssl
    openssl: stable 1.0.2q (bottled) [keg-only]
    SSL/TLS cryptography library
    https://openssl.org/
    /usr/local/Cellar/openssl/1.0.2o_2 (1,792 files, 12.3MB)
      Poured from bottle on 2018-07-23 at 14:37:12
    /usr/local/Cellar/openssl/1.0.2q (1,794 files, 12.1MB)
      Poured from bottle on 2019-01-30 at 14:12:51
    From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/openssl.rb
    ==> Caveats
    A CA file has been bootstrapped using certificates from the SystemRoots
    keychain. To add additional certificates (e.g. the certificates added in
    the System keychain), place .pem files in
      /usr/local/etc/openssl/certs

    and run
      /usr/local/opt/openssl/bin/c_rehash

    openssl is keg-only, which means it was not symlinked into /usr/local,
    because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

    If you need to have openssl first in your PATH run:
      echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile

    For compilers to find openssl you may need to set:
      export LDFLAGS="-L/usr/local/opt/openssl/lib"
      export CPPFLAGS="-I/usr/local/opt/openssl/include"

    For pkg-config to find openssl you may need to set:
      export PKG_CONFIG_PATH="/usr/local/opt/openssl/lib/pkgconfig"

    ==> Analytics
    install: 465,985 (30 days), 1,553,385 (90 days), 6,076,848 (365 days)
    install_on_request: 59,235 (30 days), 217,436 (90 days), 854,397 (365 days)
    build_error: 0 (30 days)

Kindly advise how to get past this obstacle? Thanks.


问:
Why does the Main(string[] args) function always execute first , ie., before any other function present in the code
I have started learning c#, and it is also my first programming language.
While doing functions, i noticed that all functions are called through the
Main(string[] args) function.

Like, in this code, taken from Microsoft Docs, The Main(string[] args) function calls first.
Does this function have something special?

```<code>using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
       var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);

       Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");
   }

   private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
   {
      int population1 = 0, population2 = 0;
      double area = 0;

      if (name == "New York City") {
         area = 468.48;
         if (year1 == 1960) {
            population1 = 7781984;
         }
         if (year2 == 2010) {
            population2 = 8175133;
         }
      return (name, area, year1, population1, year2, population2);
      }

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

答:
When any program starts its execution OS starts execution of the method from the main method. Let me explain in a lay man's term, There is a house and you want to enter to visit your friend. What would you do? You will look for the entrance gate to enter the house :). So here is main function is just the entrance gate which OS launch at start when the execution of a program get started.

We can also send command line parameters into main method when we execute java program through cmd.

Example Program

```<code>class cmd
{
  public static void main(String[] args)
  {
    for(int i=0;i< args.length;i++)
    {
    System.out.println(args[i]);
    }
  }
}
</code>```

Execute this program like

Execute this program as java cmd 10 20 30

Output:

10

20

30

Body:
I have started learning c#, and it is also my first programming language.
While doing functions, i noticed that all functions are called through the
Main(string[] args) function.

Like, in this code, taken from Microsoft Docs, The Main(string[] args) function calls first.
Does this function have something special?

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
       var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);

       Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");
   }

   private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
   {
      int population1 = 0, population2 = 0;
      double area = 0;

      if (name == "New York City") {
         area = 468.48;
         if (year1 == 1960) {
            population1 = 7781984;
         }
         if (year2 == 2010) {
            population2 = 8175133;
         }
      return (name, area, year1, population1, year2, population2);
      }

      return ("", 0, 0, 0, 0, 0);
   }
}

Body:
When any program starts its execution OS starts execution of the method from the main method. Let me explain in a lay man's term, There is a house and you want to enter to visit your friend. What would you do? You will look for the entrance gate to enter the house :). So here is main function is just the entrance gate which OS launch at start when the execution of a program get started.

We can also send command line parameters into main method when we execute java program through cmd.

Example Program

class cmd
{
  public static void main(String[] args)
  {
    for(int i=0;i< args.length;i++)
    {
    System.out.println(args[i]);
    }
  }
}

Execute this program like

Execute this program as java cmd 10 20 30

Output:

10

20

30


问:
similar_text highest string value
I use similar_text to find which string have the highest similar value to the input

I tried using rsort to get the highest value, but how do I get string which have the highest value?

```<code>$similarities = [];
$input = "makanan daerah";
$type = array('pakaian','senjata','makanan', 'tarian');
foreach ($type as $value) {
    similar_text($input, $value, $percent);
    $similarities[$value] = $percent;
}
rsort($similarities);
echo($similarities[0]);
</code>```

I expect output makanan
but the only output I can display is the percent value 66.6667

答:
We can try using asort to sort the associative array of terms and percentages by the latter.  Then, access the last key, which should coincide with the key having the highest percentage:

```<code>$similarities = [];
$input = "makanan daerah";
$type = array('pakaian','senjata','makanan', 'tarian');
foreach ($type as $value) {
    similar_text($input, $value, $percent);
    $similarities[$value] = $percent;
}
asort($similarities);
print_r($similarities);
end($similarities);
$key = key($similarities);
var_dump($key);

Array
(
    [senjata] => 19.047619047619
    [tarian] => 30
    [pakaian] => 47.619047619048
    [makanan] => 66.666666666667
)
string(7) "makanan"
</code>```

Title: similar_text highest string value

Body:
I use similar_text to find which string have the highest similar value to the input

I tried using rsort to get the highest value, but how do I get string which have the highest value?

$similarities = [];
$input = "makanan daerah";
$type = array('pakaian','senjata','makanan', 'tarian');
foreach ($type as $value) {
    similar_text($input, $value, $percent);
    $similarities[$value] = $percent;
}
rsort($similarities);
echo($similarities[0]);

I expect output makanan
but the only output I can display is the percent value 66.6667

Body:
We can try using asort to sort the associative array of terms and percentages by the latter.  Then, access the last key, which should coincide with the key having the highest percentage:

$similarities = [];
$input = "makanan daerah";
$type = array('pakaian','senjata','makanan', 'tarian');
foreach ($type as $value) {
    similar_text($input, $value, $percent);
    $similarities[$value] = $percent;
}
asort($similarities);
print_r($similarities);
end($similarities);
$key = key($similarities);
var_dump($key);

Array
(
    [senjata] => 19.047619047619
    [tarian] => 30
    [pakaian] => 47.619047619048
    [makanan] => 66.666666666667
)
string(7) "makanan"