答:
All you need is a closure.

You cant have synchronous return statement to return the response of web service call which in itself is asynchronous in nature. You need closures for that.

You can modify your answer as below. Because you have not answered to my question in comment I have taken liberty to return the wether object rather than returning bool which does not make much sense.

```<code>func getCurrentWeather (completion : @escaping((CurrentWeather?) -> ()) ){
        let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/"

        guard let url = URL(string: jsonUrlString) else { return false }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            // check error/response

            guard let data = data else { return }

            do {
                let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
                CurrentWeather.currentWeather = weather
                if let currentWeatherUnwrapped = currentWeather {
                    completion(CurrentWeather.currentWeather)
                }
            } catch let jsonErr {
                print("Error serializing JSON: ", jsonErr)
                completion(nil)
            }

            // cannot update currentWeather here, as weather is local to do block

            }.resume()
    }
</code>```

Assuming currentWeather is a static variable in your CurrentWeather class you can update your global variable as well as return the actual data to caller as shown above

EDIT:

As pointed out by Duncan in comments below, the above code executes the completion block in background thread. All the UI operations must be done only on main thread. Hence its very much essential to switch the thread before updating the UI.

Two ways :

1- Make sure you execute the completion block on main thread.

```<code>DispatchQueue.main.async {
      completion(CurrentWeather.currentWeather)
}
</code>```

This will make sure that whoever uses your getCurrentWeather in future need not worry about switching thread because your method takes care of it. Useful if your completion block contains only the code to update UI. Lengthier logic in completion block with this approach will burden the main thread.

2 - Else In completion block that you pass as a parameter to getCurrentWeather whenever you update UI elements make sure you wrap those statements in

```<code>DispatchQueue.main.async {
    //your code to update UI
}
</code>```

EDIT 2:

As pointed out by Leo Dabus in comments below, I should have run completion block rather than guard let url = URL(string: jsonUrlString) else { return false } That was a copy paste error. I copied the OP's question and in a hurry din realize that there is a return statement.

Though having a error as a parameter is optional in this case and completely depends on how you designed your error handling model, I appreciate the idea suggested by Leo Dabus which is more general approach and hence updating my answer to have error as a parameter.

Now there are cases where we may need to send our custom error as well for example if guard let data = data else { return } returns false rather than simply calling return you may need to return a error of your own which says invalid input or something like that.

Hence I have taken a liberty to declare a custom errors of my own and you can as well use the model to deal with your error handling

```<code>enum CustomError : Error {
    case invalidServerResponse
    case invalidURL
}

func getCurrentWeather (completion : @escaping((CurrentWeather?,Error?) -> ()) ){
        let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/"

        guard let url = URL(string: jsonUrlString) else {
            DispatchQueue.main.async {
                completion(nil,CustomError.invalidURL)
            }
            return
        }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            // check error/response

            if err != nil {
                DispatchQueue.main.async {
                    completion(nil,err)
                }
                return
            }

            guard let data = data else {
                DispatchQueue.main.async {
                    completion(nil,CustomError.invalidServerResponse)
                }
                return
            }

            do {
                let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
                CurrentWeather.currentWeather = weather

                if let currentWeatherUnwrapped = currentWeather {
                    DispatchQueue.main.async {
                        completion(CurrentWeather.currentWeather,nil)
                    }
                }

            } catch let jsonErr {
                print("Error serializing JSON: ", jsonErr)
                DispatchQueue.main.async {
                    completion(nil,jsonErr)
                }
            }

            // cannot update currentWeather here, as weather is local to do block

            }.resume()
    }
</code>```

Body:
I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?).

The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful.

I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much!

func getCurrentWeather () -> Bool {
let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

guard let url = URL(string: jsonUrlString) else { return false }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

    guard let data = data else { return }

    do {
        let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
        currentWeather = weather
        if let currentWeatherUnwrapped = currentWeather {
            print(currentWeatherUnwrapped)
        }
    } catch let jsonErr {
        print("Error serializing JSON: ", jsonErr)
    }

    // cannot update currentWeather here, as weather is local to do block

    }.resume()

return currentWeather != nil
}

Body:
All you need is a closure.

You cant have synchronous return statement to return the response of web service call which in itself is asynchronous in nature. You need closures for that.

You can modify your answer as below. Because you have not answered to my question in comment I have taken liberty to return the wether object rather than returning bool which does not make much sense.

func getCurrentWeather (completion : @escaping((CurrentWeather?) -> ()) ){
        let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/"

        guard let url = URL(string: jsonUrlString) else { return false }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            // check error/response

            guard let data = data else { return }

            do {
                let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
                CurrentWeather.currentWeather = weather
                if let currentWeatherUnwrapped = currentWeather {
                    completion(CurrentWeather.currentWeather)
                }
            } catch let jsonErr {
                print("Error serializing JSON: ", jsonErr)
                completion(nil)
            }

            // cannot update currentWeather here, as weather is local to do block

            }.resume()
    }

Assuming currentWeather is a static variable in your CurrentWeather class you can update your global variable as well as return the actual data to caller as shown above

EDIT:

As pointed out by Duncan in comments below, the above code executes the completion block in background thread. All the UI operations must be done only on main thread. Hence its very much essential to switch the thread before updating the UI.

Two ways :

1- Make sure you execute the completion block on main thread.

DispatchQueue.main.async {
      completion(CurrentWeather.currentWeather)
}

This will make sure that whoever uses your getCurrentWeather in future need not worry about switching thread because your method takes care of it. Useful if your completion block contains only the code to update UI. Lengthier logic in completion block with this approach will burden the main thread.

2 - Else In completion block that you pass as a parameter to getCurrentWeather whenever you update UI elements make sure you wrap those statements in

DispatchQueue.main.async {
    //your code to update UI
}

EDIT 2:

As pointed out by Leo Dabus in comments below, I should have run completion block rather than guard let url = URL(string: jsonUrlString) else { return false } That was a copy paste error. I copied the OP's question and in a hurry din realize that there is a return statement.

Though having a error as a parameter is optional in this case and completely depends on how you designed your error handling model, I appreciate the idea suggested by Leo Dabus which is more general approach and hence updating my answer to have error as a parameter.

Now there are cases where we may need to send our custom error as well for example if guard let data = data else { return } returns false rather than simply calling return you may need to return a error of your own which says invalid input or something like that.

Hence I have taken a liberty to declare a custom errors of my own and you can as well use the model to deal with your error handling

enum CustomError : Error {
    case invalidServerResponse
    case invalidURL
}

func getCurrentWeather (completion : @escaping((CurrentWeather?,Error?) -> ()) ){
        let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/"

        guard let url = URL(string: jsonUrlString) else {
            DispatchQueue.main.async {
                completion(nil,CustomError.invalidURL)
            }
            return
        }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            // check error/response

            if err != nil {
                DispatchQueue.main.async {
                    completion(nil,err)
                }
                return
            }

            guard let data = data else {
                DispatchQueue.main.async {
                    completion(nil,CustomError.invalidServerResponse)
                }
                return
            }

            do {
                let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
                CurrentWeather.currentWeather = weather

                if let currentWeatherUnwrapped = currentWeather {
                    DispatchQueue.main.async {
                        completion(CurrentWeather.currentWeather,nil)
                    }
                }

            } catch let jsonErr {
                print("Error serializing JSON: ", jsonErr)
                DispatchQueue.main.async {
                    completion(nil,jsonErr)
                }
            }

            // cannot update currentWeather here, as weather is local to do block

            }.resume()
    }


来源: stackexchange

问:
Prevent python script from running if another one is being executed
I have two scripts inside a bigger system I'm developing. Lets call one foo.py and the other one bar.py.

foo creates files that bar will afterwards read and delete. Now, if foo is running and working on a file, bar will mess things up by working on the same file before foo is finished.

foo and bar get started automatically by other stuff, not manually by someone that runs them. How can I make sure that, if foo is working on a file, bar will not start?

I have thought about editing both of them so that foo writes a 1 to a text file at the beginning of the execution and a 0 when it finishes, and to make bar read the text file to check wheter it can start. But I'm not really sure this is the most elegant solution, and also I don't want to block bar if foo ever fails in the middle of execution, leaving the file at 1.

答:
```<code>import fcntl

pid_file = 'mysoftware.pid'
fp = open(pid_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running
    print("already running")
    sys.exit(1)
</code>```

this works for me.

ContentLicense: CC BY-SA 3.0

Body:
import fcntl

pid_file = 'mysoftware.pid'
fp = open(pid_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
    # another instance is running
    print("already running")
    sys.exit(1)

this works for me.


问:
Google Maps set to free driving mode
I have an Android application that has SupportMapFragment added on xml file.
In fragment I set my location as follows: mMap.setMyLocationEnabled(true); to display my current location

The main issue is that the walking mode is enabled[blue dot] by default, I want free driving mode activated [blue arrow]

How can I achieve free driving mode? To have blue arrow as my position instead of blue dot

答:
There is no Driving Mode for SupportMapFragment and no possibilities to change default My Location Marker, but you can:

1) launch Google Maps application in Driving mode via intent as in this answer of Jason Maderski:

```<code>Intent intent = getPackageManager().getLaunchIntentForPackage("com.google.android.apps.maps");
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("google.navigation:/?free=1&mode=d&entry=fnls"));
startActivity(intent);
</code>```

or

2) change custom current location indicator via custom marker on GoogleMap object like in that answer of antonio.

Because of unpredictability of LocationListener update I think better use NMEA data (RMC sentence) from GPS via GpsStatus.NmeaListener (OnNmeaMessageListener for API >= 24) for updating current location. In that case source code can be something like that:

CustomNmeaListener.java:

```<code>public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}
</code>```

MainActivity.java:

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

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 101;

    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private GoogleMap mGoogleMap;
    private MapFragment mMapFragment;

    private LocationManager mLocationManager = null;
    private CustomNmeaListener mNmeaListener = null;

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

        mMapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mMapFragment.getMapAsync(this);

    }

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

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                makeLocationPermissionRequest();
            } else {
                setCustomLocationListener();
            }
        } else {
            setCustomLocationListener();
        }
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

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

    private void makeLocationPermissionRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
    }

    private void setCustomLocationListener() {
        // disable "standard" location marker
        mGoogleMap.setMyLocationEnabled(false);

        initializeLocationManager();
        mNmeaListener = new CustomNmeaListener(mGoogleMap, R.drawable.ic_marker_move, R.drawable.ic_marker_stop);
        mLocationManager.addNmeaListener(mNmeaListener);

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    LOCATION_INTERVAL,
                    LOCATION_DISTANCE,
                    this
            );
        } catch (java.lang.SecurityException ex) {
            Log.d(TAG, "fail to request location update, ignore", ex);
        }
    }

    private void initializeLocationManager() {
        Log.d(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

}
</code>```

and R.drawable.ic_marker_move & R.drawable.ic_marker_stop - drawable resources like:

 0)">

(North orientation is important)

and

respectively.

NB! This is a quick and dirty example without NMEA checksum test, GPS data filtering, saving and restoring marker position on Activity visible/hide, etc.

Title: Google Maps set to free driving mode

Body:
There is no Driving Mode for SupportMapFragment and no possibilities to change default My Location Marker, but you can:

1) launch Google Maps application in Driving mode via intent as in this answer of Jason Maderski:

Intent intent = getPackageManager().getLaunchIntentForPackage("com.google.android.apps.maps");
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("google.navigation:/?free=1&mode=d&entry=fnls"));
startActivity(intent);

or

2) change custom current location indicator via custom marker on GoogleMap object like in that answer of antonio.

Because of unpredictability of LocationListener update I think better use NMEA data (RMC sentence) from GPS via GpsStatus.NmeaListener (OnNmeaMessageListener for API >= 24) for updating current location. In that case source code can be something like that:

CustomNmeaListener.java:

public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}

MainActivity.java:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 101;

    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private GoogleMap mGoogleMap;
    private MapFragment mMapFragment;

    private LocationManager mLocationManager = null;
    private CustomNmeaListener mNmeaListener = null;

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

        mMapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mMapFragment.getMapAsync(this);

    }

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

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                makeLocationPermissionRequest();
            } else {
                setCustomLocationListener();
            }
        } else {
            setCustomLocationListener();
        }
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

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

    private void makeLocationPermissionRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
    }

    private void setCustomLocationListener() {
        // disable "standard" location marker
        mGoogleMap.setMyLocationEnabled(false);

        initializeLocationManager();
        mNmeaListener = new CustomNmeaListener(mGoogleMap, R.drawable.ic_marker_move, R.drawable.ic_marker_stop);
        mLocationManager.addNmeaListener(mNmeaListener);

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    LOCATION_INTERVAL,
                    LOCATION_DISTANCE,
                    this
            );
        } catch (java.lang.SecurityException ex) {
            Log.d(TAG, "fail to request location update, ignore", ex);
        }
    }

    private void initializeLocationManager() {
        Log.d(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

}

and R.drawable.ic_marker_move & R.drawable.ic_marker_stop - drawable resources like:

(North orientation is important)

and

respectively.

NB! This is a quick and dirty example without NMEA checksum test, GPS data filtering, saving and restoring marker position on Activity visible/hide, etc.


问:
Pandas- create rows that show the sum of all items by date minus the specific item (creating ex-item rows for each item)
So I have panel data that shows metrics for each item over a course of time

```<code>date    item    value
1/1/2017    a   1
1/1/2017    b   2
1/1/2017    c   4
1/2/2017    a   6
1/2/2017    b   4
1/2/2017    c   3
1/3/2017    a   6
1/3/2017    b   4
1/3/2017    c   3
1/4/2017    a   2
1/4/2017    b   3
1/4/2017    c   4
</code>```

And what I want to do is create rows for each item for each date that takes the sum of all values for that date, subtracts it by the item, then divides by total number of items. Would look something like:

```<code>date    item    value
1/1/2017    a   1
1/1/2017    b   2
1/1/2017    c   4
1/1/2017    ex-a    2.5
1/1/2017    ex-b    1.5
1/1/2017    ex-c    0.25
1/2/2017    a   6
1/2/2017    b   4
1/2/2017    c   3
1/2/2017    ex-a    0.5
1/2/2017    ex-b    2.5
1/2/2017    ex-c    4.75
</code>```

how would I go about doing this? I'm assuming I'd have to group by date and create a variable that gets the sum of all values for each date, and then loop through each item. Appreciate the help

答:
I'll talk through a process:
- Use groupby to aggregate to the date and item, resetting the index to the date. This is dataframe A
- Use groupby to aggregate to the date, taking the sum and count. This is dataframe B
- Join data frames - B will join multiple rows to A. Subtract each value in A from the aggregate sum in B, and then divide the result by count of rows given in B.

Does that make sense? It's several steps.

Body:
So I have panel data that shows metrics for each item over a course of time

date    item    value
1/1/2017    a   1
1/1/2017    b   2
1/1/2017    c   4
1/2/2017    a   6
1/2/2017    b   4
1/2/2017    c   3
1/3/2017    a   6
1/3/2017    b   4
1/3/2017    c   3
1/4/2017    a   2
1/4/2017    b   3
1/4/2017    c   4

And what I want to do is create rows for each item for each date that takes the sum of all values for that date, subtracts it by the item, then divides by total number of items. Would look something like:

date    item    value
1/1/2017    a   1
1/1/2017    b   2
1/1/2017    c   4
1/1/2017    ex-a    2.5
1/1/2017    ex-b    1.5
1/1/2017    ex-c    0.25
1/2/2017    a   6
1/2/2017    b   4
1/2/2017    c   3
1/2/2017    ex-a    0.5
1/2/2017    ex-b    2.5
1/2/2017    ex-c    4.75

how would I go about doing this? I'm assuming I'd have to group by date and create a variable that gets the sum of all values for each date, and then loop through each item. Appreciate the help


问:
"Paste" string variable in excel VBA instead of the contents of clipboard?
I have a string variable that contains an HTML table in excel VBA. I know that when this table is stored in the clipboard and I invoke .PasteSpecial, Excel does some nifty preprocessing and fills the cells out in the current sheet the same way as they appear in the table.

However, if I simply set the .Value of a cell/range to the string variable, no such preprocessing takes place and the entire string, HTML tags and all, are dumped into the cell. I want the former result, but I cannot use the clipboard because it is being used by this application elsewhere and there is no guarantee I would not overwrite critical data. It is also being used asynchronously so I cannot simply save the current contents of the clipboard, use the clipboard, and then restore the previous contents of the clipboard.

So, is there any way to get the "pasting preprocessing" to occur when setting the value for a range with a formatted string?

答: I would still be curious to know the answer if anyone has it, but I decided to just go ahead and abandon the idea of storing the table in a worksheet. Instead I parse the table myself and find the values I need using the InStr function (as they are mostly adjacent key=value pairs), which is not terribly slow for my application. </p>

ContentLicense: CC BY-SA 2.5


问:
Deleting a row using api.updateRowData(transaction) has no effect on data source
I have a custom cell renderer to delete given entity.

```<code>function ActionButtonsCellRenderer() {}

ActionButtonsCellRenderer.prototype.init = function(cellRenderParams) {
    var tempDiv = document.createElement('div');

    var deleteButton = document.createElement("a");
    deleteButton.href = "javascript:void(0)";
    deleteButton.innerHTML = "<i class='fa fa-trash'></i>";

    tempDiv.appendChild(deleteButton);

    deleteButton.addEventListener("click",function(){
        cellRenderParams.api.updateRowData({remove: [cellRenderParams.data]})

    });

    this.eGui = tempDiv.firstChild;
};

ActionButtonsCellRenderer.prototype.getGui = function() {
    return this.eGui;
};
</code>```

It actually deletes the row from GUI. No problem there.

But when user adds another row using below logic;

```<code>function addRow() {
    var row = {t1 : "test"}

    dataSource[dataSource.length] = row;
    agGridOptions.api.setRowData(dataSource);
}
</code>```

Deleted row also became visible again in the grid. Which means that the dataSource object is not updated.

What am I doing wrong here ? The dataSource must be updated in my scenario.

Isn't there a two-way binding which I can use ?

答:
Ag-grid makes a copy of the data that you provide to it. So when you are using updateRowData, ag-grid will update the data that it has, not your original data array. This is good design to avoid unexpected results and loss of original data.

There are two possible solutions to your issue:

mutate your original data anytime you need to update the data - this will likely get really messy really fast

--- OR ---

use the ag-grid's built in functionality of allowing it to update row data, then when you need to do something with the dataSource (such as downloading in an excel or sending to some other function) use the getModel() function to get the data that ag-grid is aware of.

ContentLicense: CC BY-SA 4.0

Body:
I have a custom cell renderer to delete given entity.

function ActionButtonsCellRenderer() {}

ActionButtonsCellRenderer.prototype.init = function(cellRenderParams) {
    var tempDiv = document.createElement('div');

    var deleteButton = document.createElement("a");
    deleteButton.href = "javascript:void(0)";
    deleteButton.innerHTML = "";

    tempDiv.appendChild(deleteButton);

    deleteButton.addEventListener("click",function(){
        cellRenderParams.api.updateRowData({remove: [cellRenderParams.data]})

    });

    this.eGui = tempDiv.firstChild;
};

ActionButtonsCellRenderer.prototype.getGui = function() {
    return this.eGui;
};

It actually deletes the row from GUI. No problem there.

But when user adds another row using below logic;

function addRow() {
    var row = {t1 : "test"}

    dataSource[dataSource.length] = row;
    agGridOptions.api.setRowData(dataSource);
}

Deleted row also became visible again in the grid. Which means that the dataSource object is not updated.

What am I doing wrong here ? The dataSource must be updated in my scenario.

Isn't there a two-way binding which I can use ?


问:
SQL Returning remaining rows
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

```<code>Name   Qty-Have
A      10
B      10
C      5
</code>```

Table 2, Next two months of future orders for parts A, B, and C:

```<code>Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7
</code>```

Result, the earliest order date for when we will have insufficient inventory:

```<code>Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2
</code>```

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

答:
If you have window functions available (SQL Server or MySQL 8 and above) use the following query:

```<code>select h.name Name, min(o.due) Next_Due, max(o.sumQty) - h.Qtyhave Qty_Want
from
(
  select *, sum(QtyNeed) over (partition by name order by due) sumQty
  from orders
) o
right join onHand h on o.name = h.name and o.sumQty > h.Qtyhave
group by h.name, h.Qtyhave
</code>```

demo - works for SQL Server as well as for MySQL 8 and above

Result

```<code>Name    Next Due    Qty-Want
----------------------------------
A       11/20/17    13
B       12/29/17    2
C       11/10/17    2
</code>```

Title: SQL Returning remaining rows

Body:
I have a table of on hand quantity for a list of parts. I have a second table with a series of order ship dates and required quantities.

I want to return the ship date of the next order that we will not have anymore inventory for.

For example:

Table 1, our on hand quantity for parts A, B, and C:

Name   Qty-Have
A      10
B      10
C      5

Table 2, Next two months of future orders for parts A, B, and C:

Name   Due          Qty-Need
A      11/10/17     4
A      11/15/17     6
A      11/20/17     3
A      11/25/17     10
B      11/12/17     4
B      12/15/17     4
B      12/29/17     4
C      11/10/17     7

Result, the earliest order date for when we will have insufficient inventory:

Name   Next Due         Qty-Want
A      11/20/17         13
B      12/29/17         2
C      11/10/17         2

I know I can do a grouping of Table 2 and subtract inventory to get Qty-Want, but I do not know how to get the next shipment date of the next uncovered order.

The first two orders of part A we have inventory, and I would like to know that we do not have enough for the third order, due 11/20/17 and we should make 13 parts to cover all remaining demand.

Body:
If you have window functions available (SQL Server or MySQL 8 and above) use the following query:

select h.name Name, min(o.due) Next_Due, max(o.sumQty) - h.Qtyhave Qty_Want
from
(
  select *, sum(QtyNeed) over (partition by name order by due) sumQty
  from orders
) o
right join onHand h on o.name = h.name and o.sumQty > h.Qtyhave
group by h.name, h.Qtyhave

demo - works for SQL Server as well as for MySQL 8 and above

Result

Name    Next Due    Qty-Want
----------------------------------
A       11/20/17    13
B       12/29/17    2
C       11/10/17    2


问:
Issue with Android Studio and Main Activity.kt expecting member declaration
I have been trying to learn through following YouTube tutorials.  I am using Android Studio 3.1 Canary and I get to the same point in the tutorials and get stuck.  For instance if you go to this YouTube tutorial https://youtu.be/3RMboPhUbmg?t=210 at the 3:30 min mark.

When they are inputting the MaterialSearchView searchView; it shows up for me with a red underline saying "expecting member declaration" and no matter how many searches I try I cannot find an answer.  What is the solution to this error? Thanks

This is the code contained in the Main2Activity.kt. The result should be calling or knowing the toolbar and materialsearchview objects

```<code>import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import com.miguelcatalan.materialsearchview.MaterialSearchView
import kotlinx.android.synthetic.main.activity_main2.*

class Main2Activity : AppCompatActivity () {
    **MaterialSearchView searchView;**  "expecting member declaration error"
    **Toolbar  toolbar;** "expecting member declaration error"
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        toolbar=(Toolbar()) findViewbyId(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
    *private void searchViewCode()
    {
        searchView=(MaterialSearchView)findViewById(R.id.search_view);
    }
}
</code>```

答:
It seems you are declaring your searchView and toolbar variables using Java syntax, and not the Kotlin syntax, so the compiler does not understand what you are declaring.

So change the declaration to:

```<code>var searchView: MaterialSearchView? = null
val toolbar: Toolbar = view.findViewById(R.id.toolbar) as Toolbar
</code>```

or if you are using Kotlin Android extensions you should be able to retrieve the toolbar like so (using the view id directly):

Body:
I have been trying to learn through following YouTube tutorials.  I am using Android Studio 3.1 Canary and I get to the same point in the tutorials and get stuck.  For instance if you go to this YouTube tutorial https://youtu.be/3RMboPhUbmg?t=210 at the 3:30 min mark.

When they are inputting the MaterialSearchView searchView; it shows up for me with a red underline saying "expecting member declaration" and no matter how many searches I try I cannot find an answer.  What is the solution to this error? Thanks

This is the code contained in the Main2Activity.kt. The result should be calling or knowing the toolbar and materialsearchview objects

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import com.miguelcatalan.materialsearchview.MaterialSearchView
import kotlinx.android.synthetic.main.activity_main2.*

class Main2Activity : AppCompatActivity () {
    **MaterialSearchView searchView;**  "expecting member declaration error"
    **Toolbar  toolbar;** "expecting member declaration error"
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        toolbar=(Toolbar()) findViewbyId(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
    *private void searchViewCode()
    {
        searchView=(MaterialSearchView)findViewById(R.id.search_view);
    }
}

Body:
It seems you are declaring your searchView and toolbar variables using Java syntax, and not the Kotlin syntax, so the compiler does not understand what you are declaring.

So change the declaration to:

var searchView: MaterialSearchView? = null
val toolbar: Toolbar = view.findViewById(R.id.toolbar) as Toolbar

or if you are using Kotlin Android extensions you should be able to retrieve the toolbar like so (using the view id directly):


问:
For loop skips rows in R dataframe
I have a for loop printing values out of this small test dataframe.

```<code>      USA    Finland    China    Sweden
1     1      3         5.505962  8.310596
2     2      4        11.033347  5.425747
3     3      5        14.932882  3.272544
4     4      6        10.155517  5.980190
5     5      7        11.020148  3.692313
Total 0      0         0.000000  0.000000
</code>```

This line prints out a line from the dataframe:

```<code>print(countries[2,])
</code>```

and results in this:

```<code>    USA Finland    China   Sweden
2   2   4        11.03335  5.425747
</code>```

So based on that, I imagine I could do the same in a for loop and print out all the lines. Code for the loop:

```<code>for (i in countries[1,])
{
    print(countries[i,])
}
</code>```

However this results in only every second line printed out which doesn't make sense. The result I get is this:

```<code>    USA Finland    China   Sweden
1   1   3         5.505962 8.310596
    USA Finland    China   Sweden
3   3   5         14.93288 3.272544
    USA Finland    China   Sweden
5   5   7         11.02015 3.692313
    USA Finland    China   Sweden
NA  NA  NA         NA      NA
</code>```

What could possibly lead to this happening? I'm using R studio so could it be the console logging not keeping up with the values?

答:
@lmo comment suggest solution. I think that you want to know why this happend, so I'll try to answer that.

You are using this code:

```<code>1: for (i in countries[1,])
2: {
3:     print(countries[i,])
4: }
</code>```

In line 1 you are selecting a vector of values that i will be using. This vector happens to be the first row of your data: 1 3 5.505962 8.310596. It translates to a vector c(1,3,5,8) - as indexes.

So in line 3 you are printing lines 1, 3, 5, 8 (because you choose that indexes). It was quite random that it were even rows, but I hope you understand it better.

Of course you should use df[1:5,] or print(df) instead of for.

Title: For loop skips rows in R dataframe

Body:
I have a for loop printing values out of this small test dataframe.

      USA    Finland    China    Sweden
1     1      3         5.505962  8.310596
2     2      4        11.033347  5.425747
3     3      5        14.932882  3.272544
4     4      6        10.155517  5.980190
5     5      7        11.020148  3.692313
Total 0      0         0.000000  0.000000

This line prints out a line from the dataframe:

print(countries[2,])

and results in this:

    USA Finland    China   Sweden
2   2   4        11.03335  5.425747

So based on that, I imagine I could do the same in a for loop and print out all the lines. Code for the loop:

for (i in countries[1,])
{
    print(countries[i,])
}

However this results in only every second line printed out which doesn't make sense. The result I get is this:

    USA Finland    China   Sweden
1   1   3         5.505962 8.310596
    USA Finland    China   Sweden
3   3   5         14.93288 3.272544
    USA Finland    China   Sweden
5   5   7         11.02015 3.692313
    USA Finland    China   Sweden
NA  NA  NA         NA      NA

What could possibly lead to this happening? I'm using R studio so could it be the console logging not keeping up with the values?

Body:
@lmo comment suggest solution. I think that you want to know why this happend, so I'll try to answer that.

You are using this code:

1: for (i in countries[1,])
2: {
3:     print(countries[i,])
4: }

In line 1 you are selecting a vector of values that i will be using. This vector happens to be the first row of your data: 1 3 5.505962 8.310596. It translates to a vector c(1,3,5,8) - as indexes.

So in line 3 you are printing lines 1, 3, 5, 8 (because you choose that indexes). It was quite random that it were even rows, but I hope you understand it better.

Of course you should use df[1:5,] or print(df) instead of for.


问:
Expand environment variable for My Documents
I know I can read environment variables like this:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

However, it would be really helpful to me if I could do something like this:

```<code>Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");
</code>```

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

```<code>Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");
</code>```

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

答:
No it does not exist. The easiest way to check is to run "set" from command line and see yourself.</p>

```<code>Start-> run -> cmd
set
set |findstr /i documents
</code>```

Body:
I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

Body:
No it does not exist. The easiest way to check is to run "set" from command line and see yourself.

Start-> run -> cmd
set
set |findstr /i documents


问:
I want to save uploaded files in my local folder using angular2 or angular4
I am using ng2-file-upload to upload files.when I upload file progress bar shows that file is uploaded but not save this file. now I want to save uploaded files in my local folder using angular2 or angular4.</p>

答: you must deploy Api service for save file in db or file System.  or you can deploy server layout by nodejs if you like Javascript.</p>


问:
Getting an absolute URL from a relative one. (IE6 issue)
I'm currently using the following function to 'convert' a relative URL to an absolute one:

```<code>function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.href;
}
</code>```

This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').

The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.

So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?

Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!

There must be a way to do it without having to create a mammoth of a regex'y solution??

答:
How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.

```<code>function escapeHTML(s) {
    return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
function qualifyURL(url) {
    var el= document.createElement('div');
    el.innerHTML= '<a href="'+escapeHTML(url)+'">x</a>';
    return el.firstChild.href;
}
</code>```

A bit ugly, but more concise than Doing It Yourself.

OwnerDisplayName: JimmyP

Body:
I'm currently using the following function to 'convert' a relative URL to an absolute one:

function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.href;
}

This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').

The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.

So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?

Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!

There must be a way to do it without having to create a mammoth of a regex'y solution??

Body:
How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.

function escapeHTML(s) {
    return s.split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
}
function qualifyURL(url) {
    var el= document.createElement('div');
    el.innerHTML= '<a href="'+escapeHTML(url)+'">x</a>';
    return el.firstChild.href;
}

A bit ugly, but more concise than Doing It Yourself.

OwnerDisplayName: bobince


问:
C++ C2466 error
Why we can do something like

```<code>        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }
</code>```

but we can not do

```<code>                               char buffer[destination->imageSize];
</code>```

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?

答:
Using std::vector you can achieve what you desire.  Your function can be defined something like this:

```<code>void readImage(std::vector<char>& imageData, std::string& filename)
{
    size_t imageSize = 0;
    //read file and load imageSize
    imageData.resize(imageSize);
    // load image into imageData using such as you in your question
    for(int i = 0; i < destination->imageSize; i=i+3)
    {

        buffer[2] = destination->imageData[i];
        buffer[1] = destination->imageData[i+1];
        buffer[0] = destination->imageData[i+2];
        buffer+=3;
    }
}
</code>```

For further improvements you could return a bool that indicates success or failure.

Regarding the cause of C2466, I don't have the official answer but you can declare char arrays with const variables only like so:

```<code>const int imageSize = 4242;
char imageData[imageSize]; // No C2466 error
</code>```

Title: C++ C2466 error

Body:
Why we can do something like

        for(int i = 0; i < destination->imageSize; i=i+3)
        {

            buffer[2] = destination->imageData[i];
            buffer[1] = destination->imageData[i+1];
            buffer[0] = destination->imageData[i+2];
            buffer+=3;
        }

but we can not do

                               char buffer[destination->imageSize];

And how to such thing?

Sorry - I am quite new to C++...

BTW: my point is to create a function that would return a char with an image. If I'd use mem copy how do I delete returned value?

Body:
Using std::vector you can achieve what you desire.  Your function can be defined something like this:

void readImage(std::vector<char>& imageData, std::string& filename)
{
    size_t imageSize = 0;
    //read file and load imageSize
    imageData.resize(imageSize);
    // load image into imageData using such as you in your question
    for(int i = 0; i < destination->imageSize; i=i+3)
    {

        buffer[2] = destination->imageData[i];
        buffer[1] = destination->imageData[i+1];
        buffer[0] = destination->imageData[i+2];
        buffer+=3;
    }
}

For further improvements you could return a bool that indicates success or failure.

Regarding the cause of C2466, I don't have the official answer but you can declare char arrays with const variables only like so:

const int imageSize = 4242;
char imageData[imageSize]; // No C2466 error


问:
Getting rid of SQL injection without using Prepared statement
My application has a lot of JDBC queries written using Statement and is thus vulnerable to SQL injection. Unfortunately this application was developed around 10 years back and probably developers didn't know about Prepared statement.

I know that the best way to solve this problem is to use PreparedStatement but it is very tedious to convert it throughout the application. Also, writing any sort of Patten matching for SQL injection could be very tricky as keywords like Select, insert, union, etc are all English words which could also appear in a text field keyed in by the user.

Is there a smarter way to avoid SQL injection without using Prepared statement. If this is a duplicate question, please give me the link to question which has a good answer. Thanks for the help.

答:
Hah.  Unfortunately, it almost always depends on the monetary and managerial decision for what's appropriate, but "it is very tedious" is not generally considered a valid engineering concern -- it is but an excuse to appropriately refactor the code.

Meanwhile, the question requests non-PreparedStatement methods: in short, if you cannot offload the work to a library (e.g. prepared statements), then the only other method is to do it yourself for each "injected" item.  Either way, the work of checking the input must be performed.  The sole question is where it is done, and what programmer's expertise made the input validation code.

For example, consider a simple SELECT statement:

```<code>    sql = "SELECT * FROM mytable WHERE id = " + untrustedVar;
</code>```

For completeness, we might assume the injection example where untrustedVar is a string like 1 OR 1 or 1;  DROP TABLE mytable;  Obviously this would result in unwanted behavior, vis-a-vis all rows returned to the caller, or a now missing database table:

```<code>SELECT * FROM mytable WHERE id = 1;
DROP mytable;
</code>```

Obligatory XKCD reference

In this case, you could let the language semantics at least ensure that unstrustedVar is an integer, perhaps in your function definition:

```<code>String[] selectRowById ( int untrustedVar ) { ...
</code>```

Or if it's a string, you might do this with a regex like:

```<code>Pattern valid_id_re = Pattern.compile('^\d{1,10}$');  // ensure id is between 1 and 10 billion
Matcher m = valid_id_re.matcher( unstrustedVar );
if ( ! m.matches() )
    return null;
</code>```

But if you have longer inputs that do not have any grammar or structure guarantees (e.g., a web form textarea), then you will need to do the lower-level character replacements to escape the potentially bad characters.  Per statement.  Per variable.  Per database flavor (PostgreSQL, Oracle, MySQL, SQLite, etc.).  This ... is a can of worms.

The upside, of course, is that if you are not using prepared statements, and no one has yet done the work to otherwise avoid SQL injection attacks for your application, you have no where to go but up.

Meanwhile, I urge, urge, urge you to reconsider your stance on "We can't use prepared statements because reasons."  More to the point, and as Gord Thompson correctly points out in the comments below, "it will be a considerable amount of work in any case, so why not just do it right and be done with it?"

Edit

After writing the above, it occurred to me that some might think that merely writing a prepared statement = better security.  Actually, it's prepared statements with bound parameters that ups the security.  For example, one could write this:

```<code>String sql = "SELECT * FROM mytable WHERE id = " + untrustedVar;
PreparedStatment pstmt = dbh.prepareStatement( sql );
return pstmt.executeQuery();
</code>```

At this point, you've done little more than prepare a statement that has already been injected with malicious code.  Instead, consider the actual binding of parameters:

```<code>String sql = "SELECT * FROM mytable WHERE id = ?";  // Raw string; never touched by "tainted" variable
PreparedStatment pstmt = dbh.prepareStatement( sql );
pstmt.setObject(1, p);  // Perform the actual binding.
return pstmt.executeQuery();
</code>```

This latter example does two things.  It first creates a known safe format, and sends that to the DB for preparation.  Then, after the DB has returned a handle to the prepared statement, do we bind the variables, and finally execute the statement.

Body:
Hah.  Unfortunately, it almost always depends on the monetary and managerial decision for what's appropriate, but "it is very tedious" is not generally considered a valid engineering concern -- it is but an excuse to appropriately refactor the code.

Meanwhile, the question requests non-PreparedStatement methods: in short, if you cannot offload the work to a library (e.g. prepared statements), then the only other method is to do it yourself for each "injected" item.  Either way, the work of checking the input must be performed.  The sole question is where it is done, and what programmer's expertise made the input validation code.

For example, consider a simple SELECT statement:

    sql = "SELECT * FROM mytable WHERE id = " + untrustedVar;

For completeness, we might assume the injection example where untrustedVar is a string like 1 OR 1 or 1;  DROP TABLE mytable;  Obviously this would result in unwanted behavior, vis-a-vis all rows returned to the caller, or a now missing database table:

SELECT * FROM mytable WHERE id = 1;
DROP mytable;

Obligatory XKCD reference

In this case, you could let the language semantics at least ensure that unstrustedVar is an integer, perhaps in your function definition:

String[] selectRowById ( int untrustedVar ) { ...

Or if it's a string, you might do this with a regex like:

Pattern valid_id_re = Pattern.compile('^\d{1,10}$');  // ensure id is between 1 and 10 billion
Matcher m = valid_id_re.matcher( unstrustedVar );
if ( ! m.matches() )
    return null;

But if you have longer inputs that do not have any grammar or structure guarantees (e.g., a web form textarea), then you will need to do the lower-level character replacements to escape the potentially bad characters.  Per statement.  Per variable.  Per database flavor (PostgreSQL, Oracle, MySQL, SQLite, etc.).  This ... is a can of worms.

The upside, of course, is that if you are not using prepared statements, and no one has yet done the work to otherwise avoid SQL injection attacks for your application, you have no where to go but up.

Meanwhile, I urge, urge, urge you to reconsider your stance on "We can't use prepared statements because reasons."  More to the point, and as Gord Thompson correctly points out in the comments below, "it will be a considerable amount of work in any case, so why not just do it right and be done with it?"

Edit

After writing the above, it occurred to me that some might think that merely writing a prepared statement = better security.  Actually, it's prepared statements with bound parameters that ups the security.  For example, one could write this:

String sql = "SELECT * FROM mytable WHERE id = " + untrustedVar;
PreparedStatment pstmt = dbh.prepareStatement( sql );
return pstmt.executeQuery();

At this point, you've done little more than prepare a statement that has already been injected with malicious code.  Instead, consider the actual binding of parameters:

String sql = "SELECT * FROM mytable WHERE id = ?";  // Raw string; never touched by "tainted" variable
PreparedStatment pstmt = dbh.prepareStatement( sql );
pstmt.setObject(1, p);  // Perform the actual binding.
return pstmt.executeQuery();

This latter example does two things.  It first creates a known safe format, and sends that to the DB for preparation.  Then, after the DB has returned a handle to the prepared statement, do we bind the variables, and finally execute the statement.


问:
How do you get weekdays array for a selected locale using moment.js without changing its global localization?
What I'm currently doing is:

```<code>moment.locale(locale)
moment.weekdays(true)
</code>```

But moment.locale(locale) changes the locale of the whole moment library and I only want to get a list of weekdays in a different locale without changing it.

I tried using

```<code>moment.localeData(locale).weekdays()
</code>```

but you can't pass true to "weekdays" so the result doesn't sort items. For example:

```<code>moment.locale('en-us')
moment.weekdays(true) // ["Sunday", "Monday", ...

moment.locale('en-gb')
moment.weekdays(true) // ["Monday", "Tuesday", ...
</code>```

But

```<code>moment.localeData('en-us').weekdays() // ["Sunday", "Monday", ...

moment.localeData('en-gb').weekdays() // ["Sunday", "Monday", ...
</code>```

And there is no

```<code>moment.localeData('en-gb').weekdays(true)
</code>```

Edit:
Looks like they have an open issue about it, so please suggest your best hacks meanwhile:
https://github.com/moment/moment/issues/4066

答:
The weekday function is locale-aware, so

```<code>const weekdays = [0, 1, 2, 3, 4, 5, 6].map(dow => moment().locale('en-gb').weekday(dow).format('dddd'))
</code>```

will give you array ['Sunday', 'Monday', ...] for en-us, but ['Monday', 'Tuesday', ...] for en-gb.

Body:
What I'm currently doing is:

moment.locale(locale)
moment.weekdays(true)

But moment.locale(locale) changes the locale of the whole moment library and I only want to get a list of weekdays in a different locale without changing it.

I tried using

moment.localeData(locale).weekdays()

but you can't pass true to "weekdays" so the result doesn't sort items. For example:

moment.locale('en-us')
moment.weekdays(true) // ["Sunday", "Monday", ...

moment.locale('en-gb')
moment.weekdays(true) // ["Monday", "Tuesday", ...

But

moment.localeData('en-us').weekdays() // ["Sunday", "Monday", ...

moment.localeData('en-gb').weekdays() // ["Sunday", "Monday", ...

And there is no

moment.localeData('en-gb').weekdays(true)

Edit:
Looks like they have an open issue about it, so please suggest your best hacks meanwhile:
https://github.com/moment/moment/issues/4066

Body:
The weekday function is locale-aware, so

const weekdays = [0, 1, 2, 3, 4, 5, 6].map(dow => moment().locale('en-gb').weekday(dow).format('dddd'))

will give you array ['Sunday', 'Monday', ...] for en-us, but ['Monday', 'Tuesday', ...] for en-gb.


问:
save screenshot of page into folder using php
I wants to develop a project in which user has to enter url and then it will take screenshot of that application and then save the screenshot to a folder.
I am able to take screenshot but it is not saving into folder. i am getting error:

```<code>Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20

Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21
</code>```

Here is code:

```<code><?php
$websiteURL = $_POST["website"];
$api_response =
file_get_contents("https://www.googleapis.com/pagespeedonline/
v2/runPagespeed?url=$websiteURL&screenshot=true");

$result = json_decode($api_response, true);
//screenshot data
$screenshot = $result['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot);
//display screenshot image
echo "<img src=\"data:image/jpeg;base64,".$screenshot."\" />";

$split_image = pathinfo($screenshot);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $screenshot);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C
Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-
folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);
?>
</code>```

答:
You can find to do in PHP...

iF I were you I would have done it via javascript

Just for your knowledge Use right tool for screen capture... ie. phantom.js

here is a simple code to take screenshot

```<code>  var page = require('webpage').create();
    page.open(url, function () {    // your URL
    page.render('D:/MySnapShotBox/saveAsSomeNome.png'); // can change location
   });
</code>```

Body:
I wants to develop a project in which user has to enter url and then it will take screenshot of that application and then save the screenshot to a folder.
I am able to take screenshot but it is not saving into folder. i am getting error:

Notice: Undefined index: extension in C:\xampp\htdocs\curlproject.php on line 20

Warning: fopen(images-folder/Z.): failed to open stream: Permission denied in C:\xampp\htdocs\curlproject.php on line 21

Here is code:

<?php
$websiteURL = $_POST["website"];
$api_response =
file_get_contents("https://www.googleapis.com/pagespeedonline/
v2/runPagespeed?url=$websiteURL&screenshot=true");

$result = json_decode($api_response, true);
//screenshot data
$screenshot = $result['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot);
//display screenshot image
echo "";

$split_image = pathinfo($screenshot);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $screenshot);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C
Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-
folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);
?>

Body:
You can find to do in PHP...

iF I were you I would have done it via javascript

Just for your knowledge Use right tool for screen capture... ie. phantom.js

here is a simple code to take screenshot

  var page = require('webpage').create();
    page.open(url, function () {    // your URL
    page.render('D:/MySnapShotBox/saveAsSomeNome.png'); // can change location
   });


问:
HTML Image Question
I'm trying to do some HTML layouts, and pretty much my problem comes in here:

```<code><img src = "https://something.com/image.png">
</code>```

The image can be displayed in a browser when navigating to the URL, but not in Microsoft Visual Studio (or the browser when loading this HTML page), it displays as a broken image instead.  This leads me to believe it cannot be linked to in such a way (as I can view other images this way).  I'm wondering if it has anything to do with it requiring a secure http connection and if there's any way around this.

Basically, the picture comes up when the url is navigated to.  However, when opening this HTML file that has the image displayed on it, it comes up as a broken image.  I'm wondering why this is.

Thanks.

答:
Try making it a background image in your css.

edit I am getting down voted for this question. I should have prefaced that I am not sure and was taking a wild guess, if anything to offer an idea that was not presented by the asker to help solve the problem :)

Title: HTML Image Question

Body:
I'm trying to do some HTML layouts, and pretty much my problem comes in here:

The image can be displayed in a browser when navigating to the URL, but not in Microsoft Visual Studio (or the browser when loading this HTML page), it displays as a broken image instead.  This leads me to believe it cannot be linked to in such a way (as I can view other images this way).  I'm wondering if it has anything to do with it requiring a secure http connection and if there's any way around this.

Basically, the picture comes up when the url is navigated to.  However, when opening this HTML file that has the image displayed on it, it comes up as a broken image.  I'm wondering why this is.

Thanks.


问:
Compare dates linq c#
I cant seem to get my query to check the database if a date exists. Please help.

```<code> DateTime value = new DateTime(2018, 10, 26);
 item = await table.Where(todoItem => todoItem.Date == value.date)
                   .ToListAsync();
</code>```

I think the format which c# writes their dates and SQL are different so it cant find a match. Also the database is correctly linked to the app as I am able to query other rows in the same table.

答:
This is most likely caused by including a time in your dates, and not formatting them to just the actual date string. You can resolve this by using the .toLocaleString() method. Something like this should work:

```<code>DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date.toLocaleString() ==
  value.date.toLocaleString())
  .ToListAsync();
</code>```

Title: Compare dates linq c#

Body:
I cant seem to get my query to check the database if a date exists. Please help.

 DateTime value = new DateTime(2018, 10, 26);
 item = await table.Where(todoItem => todoItem.Date == value.date)
                   .ToListAsync();

I think the format which c# writes their dates and SQL are different so it cant find a match. Also the database is correctly linked to the app as I am able to query other rows in the same table.

Body:
This is most likely caused by including a time in your dates, and not formatting them to just the actual date string. You can resolve this by using the .toLocaleString() method. Something like this should work:

DateTime value = new DateTime(2018, 10, 26);
item = await table.Where(todoItem => todoItem.Date.toLocaleString() ==
  value.date.toLocaleString())
  .ToListAsync();


问:
A program that prints even and odd characters from a string
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

```<code>#include <stdio.h>
#include <string.h>

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}
</code>```

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

答:
Many answers all ready point out the original code`s problems.

Below are some ideas to reduce memory usage as the 2 arrays odd[], even[] are not needed.

As the "even" characters are seen, print them out.

As the "odd" characters are seen, move them to the first part of the array.

Alternative print: If code used "%.*s", the array does not need a null character termination.

```<code>#include <stdio.h>
#include <string.h>

int main(void) {
  char str[41];

  printf("Enter a string (40 characters maximum): ");
  fflush(stdout);
  if (scanf("%40s", str) == 1) {
    int i;
    printf("The even string is:");
    for (i = 0; str[i]; i++) {
      if (i % 2 == 0) {
        str[i / 2] = str[i];  // copy character to an earlier part of `str[]`
      } else {
        putchar(str[i]);
      }
    }
    printf("\n");
    printf("The odd string is:%.*s\n ", (i + 1) / 2, str);
  }
  return 0;
}
</code>```

or simply

```<code>printf("The even string is:");
for (int i = 0; str[i]; i++) {
  if (i % 2 != 0) {
    putchar(str[i]);
  }
}
printf("\n");
printf("The odd string is:");
for (int i = 0; str[i]; i++) {
  if (i % 2 == 0) {
    putchar(str[i]);
  }
}
printf("\n");
</code>```

Body:
This is for Homework

I have to write a program that asks the user to enter a string, then my program would separate the even and odd values from the entered string. Here is my program.

#include <stdio.h>
#include <string.h>

int main(void) {
    char *str[41];
    char odd[21];
    char even[21];
    int i = 0;
    int j = 0;
    int k = 0;

    printf("Enter a string (40 characters maximum): ");
    scanf("%s", &str);

    while (&str[i] < 41) {
        if (i % 2 == 0) {
            odd[j++] = *str[i];
        } else {
            even[k++] = *str[i];
        }
        i++;
    }

    printf("The even string is:%s\n ", even);
    printf("The odd string is:%s\n ", odd);

    return 0;
}

When I try and compile my program I get two warnings:

For my scanf I get "format '%s' expects arguments of type char but argument has 'char * (*)[41]". I'm not sure what this means but I assume it's because of the array initialization.

On the while loop it gives me the warning that says comparison between pointer and integer. I'm not sure what that means either and I thought it was legal in C to make that comparison.

When I compile the program, I get random characters for both the even and odd string.

Any help would be appreciated!

Body:
Many answers all ready point out the original code`s problems.

Below are some ideas to reduce memory usage as the 2 arrays odd[], even[] are not needed.

As the "even" characters are seen, print them out.

As the "odd" characters are seen, move them to the first part of the array.

Alternative print: If code used "%.*s", the array does not need a null character termination.

#include <stdio.h>
#include <string.h>

int main(void) {
  char str[41];

  printf("Enter a string (40 characters maximum): ");
  fflush(stdout);
  if (scanf("%40s", str) == 1) {
    int i;
    printf("The even string is:");
    for (i = 0; str[i]; i++) {
      if (i % 2 == 0) {
        str[i / 2] = str[i];  // copy character to an earlier part of `str[]`
      } else {
        putchar(str[i]);
      }
    }
    printf("\n");
    printf("The odd string is:%.*s\n ", (i + 1) / 2, str);
  }
  return 0;
}

or simply

printf("The even string is:");
for (int i = 0; str[i]; i++) {
  if (i % 2 != 0) {
    putchar(str[i]);
  }
}
printf("\n");
printf("The odd string is:");
for (int i = 0; str[i]; i++) {
  if (i % 2 == 0) {
    putchar(str[i]);
  }
}
printf("\n");


问:
google sign-in without firebase
I have seen many post about firebase with google sign-in. In google's tutorial for google sign-in for android project, it does not use firebase but on many post people use firebase with google sign-in. What is the advantage of using firebase and when and why we need to use it?</p>

答:
Authenticate users by integrating with federated identity providers. The Firebase Authentication SDK provides methods that allow users to sign in with their Google, Facebook, Twitter, and GitHub accounts.

With Firebase the users will be authenticated and you will have access to the firebase database/cloud functions and other services. So its better to use firebase with google sign in. Basically to make it easier for you after sign in.

Title: google sign-in without firebase


问:
What exactly is the difference between a data mapper and a repository?
Well I've been trying to find out the difference between data mapper and repository, but up to now I still have not. It seems to me that the expert programmer said "Repository is another layer of abstraction over the mapping layer where query construction code is concentrated". It seems understandable but is still somewhat very abstract. I read this article on stackoverflow before, and it just made me even more confused:
How is the Data Mapper pattern different from the Repository Pattern?

I guess what I need are simple explanations and concrete/practical examples on how the two patterns differ, and what a repository does what a data mapper doesnt, and vice versa. Do anyone of you know a good example on illustrating the concept of data mapper and repository? It will be better if it's the same example, just one using data mapper and another using repository. Thanks, I'd very appreciate this. I am still very confused as of now...

答:
I realize that this answer is kind of late, but it may help someone in the future that stumbles upon this same question and finds that the available answer(s) do not quite answer the question (which I felt when I first came across this question).

After having read PoEAA (Martin Fowler), I too was having trouble identifying the difference between a data mapper and a repository.

This is what I've found that the 2 concepts ultimately boil down to:

a Repository acts like a collection of domain objects, with powerful querying capabilities (Evans, DDD)

a DataMapper "moves data between objects and a database while keeping them independent of each other and the mapper itself" (Fowler, PoEAA)

Repositories are a generic concept and don't necessarily have to store anything to a database, its main function is to provide collection like (query-enabled) access to domain objects (whether they are gotten from a database is besides the point). Repositories may (and often will) contain DataMappers themselves.

DataMappers serve as the middle layer between domain objects and a database, allowing them to evolve independently without any one depending on the other. Datamappers might have "find" or query functionality, but that is not really their main function. The more you find that you are using elaborate query logic in your DataMappers, the more you want to start thinking about decoupling that query logic into a repository while leaving your DataMappers to serve their main function, mapping domain objects to the database and vice versa.


问:
Drop all duplicate rows across multiple columns in Python Pandas
The pandas drop_duplicates function is great for "uniquifying" a dataframe. I would like to drop all rows which are duplicates across a subset of columns. Is this possible?

    A   B   C
0   foo 0   A
1   foo 1   A
2   foo 1   B
3   bar 1   A
```

As an example, I would like to drop rows which match on columns A and C so this should drop rows 0 and 1.

答:
Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

first : Drop duplicates except for the first occurrence.

last : Drop duplicates except for the last occurrence.

False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with
  duplicate rows removed, optionally only considering certain columns

Parameters:    subset : column label or sequence of labels, optional
  Only consider certain columns for identifying duplicates, by default
  use all of the columns keep : {‘first’, ‘last’, False}, default
  ‘first’ first : Drop duplicates except for the first occurrence. last
  : Drop duplicates except for the last occurrence. False : Drop all
  duplicates. take_last : deprecated inplace : boolean, default False
  Whether to drop duplicates in place or to return a copy cols : kwargs
  only argument of subset [deprecated] Returns:  deduplicated :
  DataFrame

Body:
The pandas drop_duplicates function is great for "uniquifying" a dataframe. I would like to drop all rows which are duplicates across a subset of columns. Is this possible?

    A   B   C
0   foo 0   A
1   foo 1   A
2   foo 1   B
3   bar 1   A

As an example, I would like to drop rows which match on columns A and C so this should drop rows 0 and 1.


问:
How to set column C value based on a initial column A,B,C value
I have the following table :

```<code>A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan
</code>```

Desired result :

```<code> A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw
</code>```

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

答:
Here a solution using data.table.

```<code>library(data.table)
setDT(dx)[,id:=1:.N] ## create variable to conserve origin order

dx[,C:={
  val <- unique(C[nzchar(C)])
  if(length(val)==0) val <- ""    ## case empty C
  if(length(val)>1) val <- val[1] ## case multiple values

  rep(val,length(C))
  }, "A,B"][order(id)][,id:=NULL]

#       A     B     C
# 1: food fruit apple
# 2: food fruit apple
# 3: food drink
# 4: food fruit apple
# 5:  car   suv  ford
# 6:  car sedan   bmw
# 7:  car   suv  ford
# 8:  car sedan   bmw
</code>```

where :

```<code>dx <- read.table(text="A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)
</code>```

Body:
I have the following table :

A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan

Desired result :

 A     B       C
food  fruit   apple
food  fruit   apple
food  drink
food  fruit   apple
car   suv     ford
car   sedan   bmw
car   suv     ford
car   sedan   bmw

How can complete column C based on the values in both Column A, B?  For example, if the value in Column A = food and Column B = fruit, then Column C should be filled with. Ideally, I want to do it without having to manually enter the column A, B pair and the corresponding column C value since my table has thousands of such combinations.

Would appreciate any help!

Body:
Here a solution using data.table.

library(data.table)
setDT(dx)[,id:=1:.N] ## create variable to conserve origin order

dx[,C:={
  val <- unique(C[nzchar(C)])
  if(length(val)==0) val <- ""    ## case empty C
  if(length(val)>1) val <- val[1] ## case multiple values

  rep(val,length(C))
  }, "A,B"][order(id)][,id:=NULL]

#       A     B     C
# 1: food fruit apple
# 2: food fruit apple
# 3: food drink
# 4: food fruit apple
# 5:  car   suv  ford
# 6:  car sedan   bmw
# 7:  car   suv  ford
# 8:  car sedan   bmw

where :

dx <- read.table(text="A     B       C
food  fruit   apple
food  fruit
food  drink
food  fruit
car   suv     ford
car   sedan   bmw
car   suv
car   sedan",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)


问:
Multi-thread when one thread is done and Suspend other threads
```<code>islem = new Thread(new ThreadStart(ilk));
         islem2 = new Thread(new ThreadStart(ikinci));
         islem3 = new Thread(new ThreadStart(ucuncu));
         islem4 = new Thread(new ThreadStart(dorduncu));
         islem.Start();
         islem2.Start();
         islem3.Start();
         islem4.Start();

        if (!islem.IsAlive)
        {
            islem2.Suspend();
            islem3.Suspend();
            islem4.Suspend();
        }
</code>```

I want to do when islem is done. Other threads suspend but it doesn't work
I read about ManualResetEvent but I can't figure out multi-threading examples.They works just one thread simples. Also I read http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming this paper to and look similar questions like C# controlling threads (resume/suspend) How to pause/suspend a thread then continue it? Pause/Resume thread whith AutoResetEvent I am working multi - thread objects

答:
If you just need to cancel the worker threads, the very simplest approach is to use a flag. You have to mark the flag volatile to ensure all threads are using the same copy.

```<code>private volatile bool _done = false;

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Someone else solved the problem, so exit.
        ContinueSolvingTheProblem();
    }
    _done = true; //Tell everyone else to stop working.
}
</code>```

If you truly want to pause (I'm not sure why) you can use a ManualResetEvent. This allows blocking behavior without consuming resources for the paused thread.

```<code>//When signalled, indicates threads can proceed.
//When reset, threads should pause as soon as possible.
//Constructor argument = true so it is set by default
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        _go.WaitOne();  //Pause if the go event has been reset
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
}
</code>```

You can also combine the approaches, e.g. if you wanted to be able to pause the threads, do some more work, then cancel them:

```<code>private volatile bool _done = false;
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Exit if problem has been solved
        _go.WaitOne();  //Pause if the go event has been reset
        if (_done) return; //Exit if problem was solved while we were waiting
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
    if (VerifyAnswer())
    {
        _done = true; //Set the done flag to indicate all threads should exit
    }
    else
    {
        _go.Set(); //Tell other threads to continue
    }
}
</code>```

Body:
islem = new Thread(new ThreadStart(ilk));
         islem2 = new Thread(new ThreadStart(ikinci));
         islem3 = new Thread(new ThreadStart(ucuncu));
         islem4 = new Thread(new ThreadStart(dorduncu));
         islem.Start();
         islem2.Start();
         islem3.Start();
         islem4.Start();

        if (!islem.IsAlive)
        {
            islem2.Suspend();
            islem3.Suspend();
            islem4.Suspend();
        }

I want to do when islem is done. Other threads suspend but it doesn't work
I read about ManualResetEvent but I can't figure out multi-threading examples.They works just one thread simples. Also I read http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming this paper to and look similar questions like C# controlling threads (resume/suspend) How to pause/suspend a thread then continue it? Pause/Resume thread whith AutoResetEvent I am working multi - thread objects

Body:
If you just need to cancel the worker threads, the very simplest approach is to use a flag. You have to mark the flag volatile to ensure all threads are using the same copy.

private volatile bool _done = false;

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Someone else solved the problem, so exit.
        ContinueSolvingTheProblem();
    }
    _done = true; //Tell everyone else to stop working.
}

If you truly want to pause (I'm not sure why) you can use a ManualResetEvent. This allows blocking behavior without consuming resources for the paused thread.

//When signalled, indicates threads can proceed.
//When reset, threads should pause as soon as possible.
//Constructor argument = true so it is set by default
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        _go.WaitOne();  //Pause if the go event has been reset
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
}

You can also combine the approaches, e.g. if you wanted to be able to pause the threads, do some more work, then cancel them:

private volatile bool _done = false;
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Exit if problem has been solved
        _go.WaitOne();  //Pause if the go event has been reset
        if (_done) return; //Exit if problem was solved while we were waiting
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
    if (VerifyAnswer())
    {
        _done = true; //Set the done flag to indicate all threads should exit
    }
    else
    {
        _go.Set(); //Tell other threads to continue
    }
}


问:
NO Android option in "tool" menu, and no avd manager
Problem : No AVD manager in Android Studio, and no "Android" option in the "tool" menu.

Tried solutions :

re-install (twice)

changed installation partition to the one containing the Android SDK directory

went to "configure" - "project default" - "project structure", and checked my Adroid SDK directory (it's there)

open a new project - there is still no android menu, and no avd manager.

instead of "Android" in the "tool" menu, i have "Kotlin"

i tried to use terminal, and console, to launch android avd : not opening

i tried to search for Android, or AVD, in the search option. they show, but when i click, nothing happens

i saw people saying i needed 5gig storage to install Android Studio. but when i install mine, it only offers one option, and total is 2gig. but i have way more than enough storage space on both my partition for 5gig or 50gig

i tried to customize toolbar, but Android options are just not there to be made visible

i have read all the posts here regarding this issue, and have not found a solution that works.

It must be a simple step that i am missing, but which one ???
 -

答:
Which Android Studio are you trying to use?
I am using 3.0 and I see both "Android" and "Kotlin" submenus under "Tools".
I am using macOS 10.12.6</p>


问:
combinatorics in a grid

We have a grid of 3 rows on 13 columns.
On the first row, we have integers from 1 to 13 in ascending order.
On the second row, we have these same integers in any order.
On the third row, we write the absolute value of the difference of the two integers of each column.
Let N be the number of ways to fill the 2nd row so that 13 distinct integers are on the 3rd row.
Let N (k) be the number of solutions for which the integer k of the 1st and 2nd row appear in the same column.
Thus, N is equal to the sum of N (k) for k ranging from 1 to 13.

What is the sum of k x N (k) for k ranging from 1 to 13?

For instance, here's a solution with k=8 :

```<code>Row 1   1  2  3  4  5  6  7  8  9 10 11 12 13
Row 2   5 13 12 11 10  7  9  8  6  4  3  2  1
Row 3   4 11  9  7  5  1  2  0  3  6  8 10 12
</code>```

Note how 8 is in the same position in rows 1 and 2, giving a 0 in row 3.  The quantity of such solutions is N(8), and I would add 8 * N(8) as that term in the requested summation.

答:
Let's take a look at a single solution for the first stage of the problem.  We'll let k=8 for this example:

```<code>Row 1   1  2  3  4  5  6  7  8  9 10 11 12 13
Row 2   5 13 12 11 10  7  9  8  6  4  3  2  1
Row 3   4 11  9  7  5  1  2  0  3  6  8 10 12
</code>```

Since each solution must have row 3 containing the integers 0-12, there will always be exactly one element in the same column in row 1 and 2.

Now, assume that there are 2 solutions with 8 being that element; you'd include 8 * 2 in your sum.

I would attack the problem via brute force (recursive placement function with backtracking).  Find all of the solutions, and then simply sum the "stable" element in each solution.  That's your final answer.

Title: combinatorics in a grid

Body:
We have a grid of 3 rows on 13 columns.
On the first row, we have integers from 1 to 13 in ascending order.
On the second row, we have these same integers in any order.
On the third row, we write the absolute value of the difference of the two integers of each column.
Let N be the number of ways to fill the 2nd row so that 13 distinct integers are on the 3rd row.
Let N (k) be the number of solutions for which the integer k of the 1st and 2nd row appear in the same column.
Thus, N is equal to the sum of N (k) for k ranging from 1 to 13.

What is the sum of k x N (k) for k ranging from 1 to 13?

For instance, here's a solution with k=8 :

Row 1   1  2  3  4  5  6  7  8  9 10 11 12 13
Row 2   5 13 12 11 10  7  9  8  6  4  3  2  1
Row 3   4 11  9  7  5  1  2  0  3  6  8 10 12

Note how 8 is in the same position in rows 1 and 2, giving a 0 in row 3.  The quantity of such solutions is N(8), and I would add 8 * N(8) as that term in the requested summation.

Body:
Let's take a look at a single solution for the first stage of the problem.  We'll let k=8 for this example:

Row 1   1  2  3  4  5  6  7  8  9 10 11 12 13
Row 2   5 13 12 11 10  7  9  8  6  4  3  2  1
Row 3   4 11  9  7  5  1  2  0  3  6  8 10 12

Since each solution must have row 3 containing the integers 0-12, there will always be exactly one element in the same column in row 1 and 2.

Now, assume that there are 2 solutions with 8 being that element; you'd include 8 * 2 in your sum.

I would attack the problem via brute force (recursive placement function with backtracking).  Find all of the solutions, and then simply sum the "stable" element in each solution.  That's your final answer.


问:
Get second child using jQuery
```<code>$(t).html()
</code>```

returns

```<code><td>test1</td><td>test2</td>
</code>```

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

答:
grab the second child:

```<code>$(t).children().eq(1);
</code>```

or, grab the second child :

```<code>$(t).children('td').eq(1);
</code>```

See documentation for children and eq.

Title: Get second child using jQuery

Body:
$(t).html()

returns

test1	test2

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

Body:
grab the second child:

$(t).children().eq(1);

or, grab the second child <td>:

$(t).children('td').eq(1);

See documentation for children and eq.