Programs & Examples On #Android location

android-location refers to the location API provided by the Android framework.

Good way of getting the user's location in Android

This is my solution which works fairly well:

private Location bestLocation = null;
private Looper looper;
private boolean networkEnabled = false, gpsEnabled = false;

private synchronized void setLooper(Looper looper) {
    this.looper = looper;
}

private synchronized void stopLooper() {
    if (looper == null) return;
    looper.quit();
}

@Override
protected void runTask() {
    final LocationManager locationManager = (LocationManager) service
            .getSystemService(Context.LOCATION_SERVICE);
    final SharedPreferences prefs = getPreferences();
    final int maxPollingTime = Integer.parseInt(prefs.getString(
            POLLING_KEY, "0"));
    final int desiredAccuracy = Integer.parseInt(prefs.getString(
            DESIRED_KEY, "0"));
    final int acceptedAccuracy = Integer.parseInt(prefs.getString(
            ACCEPTED_KEY, "0"));
    final int maxAge = Integer.parseInt(prefs.getString(AGE_KEY, "0"));
    final String whichProvider = prefs.getString(PROVIDER_KEY, "any");
    final boolean canUseGps = whichProvider.equals("gps")
            || whichProvider.equals("any");
    final boolean canUseNetwork = whichProvider.equals("network")
            || whichProvider.equals("any");
    if (canUseNetwork)
        networkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (canUseGps)
        gpsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // If any provider is enabled now and we displayed a notification clear it.
    if (gpsEnabled || networkEnabled) removeErrorNotification();
    if (gpsEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    if (networkEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (desiredAccuracy == 0
            || getLocationQuality(desiredAccuracy, acceptedAccuracy,
                    maxAge, bestLocation) != LocationQuality.GOOD) {
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (desiredAccuracy != 0
                        && getLocationQuality(desiredAccuracy,
                                acceptedAccuracy, maxAge, bestLocation)
                                == LocationQuality.GOOD)
                    stopLooper();
            }

            public void onProviderEnabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled =true;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = true;
                // The user has enabled a location, remove any error
                // notification
                if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }

            public void onProviderDisabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled=false;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = false;
                if (!gpsEnabled && !networkEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                Log.i(LOG_TAG, "Provider " + provider + " statusChanged");
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER)) networkEnabled = 
                        status == LocationProvider.AVAILABLE
                        || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER))
                    gpsEnabled = status == LocationProvider.AVAILABLE
                      || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                // None of them are available, stop listening
                if (!networkEnabled && !gpsEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
                // The user has enabled a location, remove any error
                // notification
                else if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }
        };
        if (networkEnabled || gpsEnabled) {
            Looper.prepare();
            setLooper(Looper.myLooper());
            // Register the listener with the Location Manager to receive
            // location updates
            if (canUseGps)
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            if (canUseNetwork)
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            Timer t = new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    stopLooper();
                }
            }, maxPollingTime * 1000);
            Looper.loop();
            t.cancel();
            setLooper(null);
            locationManager.removeUpdates(locationListener);
        } else // No provider is enabled, show a notification
        showErrorNotification();
    }
    if (getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
            bestLocation) != LocationQuality.BAD) {
        sendUpdate(new Event(EVENT_TYPE, locationToString(desiredAccuracy,
                acceptedAccuracy, maxAge, bestLocation)));
    } else Log.w(LOG_TAG, "LocationCollector failed to get a location");
}

private synchronized void showErrorNotification() {
    if (notifId != 0) return;
    ServiceHandler handler = service.getHandler();
    NotificationInfo ni = NotificationInfo.createSingleNotification(
            R.string.locationcollector_notif_ticker,
            R.string.locationcollector_notif_title,
            R.string.locationcollector_notif_text,
            android.R.drawable.stat_notify_error);
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    ni.pendingIntent = PendingIntent.getActivity(service, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Message msg = handler.obtainMessage(ServiceHandler.SHOW_NOTIFICATION);
    msg.obj = ni;
    handler.sendMessage(msg);
    notifId = ni.id;
}

private void removeErrorNotification() {
    if (notifId == 0) return;
    ServiceHandler handler = service.getHandler();
    if (handler != null) {
        Message msg = handler.obtainMessage(
                ServiceHandler.CLEAR_NOTIFICATION, notifId, 0);
        handler.sendMessage(msg);
        notifId = 0;
    }
}

@Override
public void interrupt() {
    stopLooper();
    super.interrupt();
}

private String locationToString(int desiredAccuracy, int acceptedAccuracy,
        int maxAge, Location location) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "qual=%s time=%d prov=%s acc=%.1f lat=%f long=%f",
            getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
                    location), location.getTime() / 1000, // Millis to
                                                            // seconds
            location.getProvider(), location.getAccuracy(), location
                    .getLatitude(), location.getLongitude()));
    if (location.hasAltitude())
        sb.append(String.format(" alt=%.1f", location.getAltitude()));
    if (location.hasBearing())
        sb.append(String.format(" bearing=%.2f", location.getBearing()));
    return sb.toString();
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(int desiredAccuracy,
        int acceptedAccuracy, int maxAge, Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < maxAge * 1000
            && location.getAccuracy() <= desiredAccuracy)
        return LocationQuality.GOOD;
    if (acceptedAccuracy == -1
            || location.getAccuracy() <= acceptedAccuracy)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;
    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());
    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) return provider2 == null;
    return provider1.equals(provider2);
}

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if block. Similar to-

if( !isGPSEnabled && !isNetworkEnabled) {

// Can't get location by any way

} else {

    if(isGPSEnabled) {

    // get location from GPS

    } else if(isNetworkEnabled) {

    // get location from Network Provider

    }
}

So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.

EDIT:

To make it better, I'll post a snippet. Consider it is in try-catch:

boolean gps_enabled = false;
boolean network_enabled = false;

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    //smaller the number more accurate result will
    if (gps_loc.getAccuracy() > net_loc.getAccuracy()) 
        finalLoc = net_loc;
    else
        finalLoc = gps_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = gps_loc;
    } else if (net_loc != null) {
        finalLoc = net_loc;
    }
}

Now you check finalLoc for null, if not then return it. You can write above code in a function which returns the desired (finalLoc) location. I think this might help.

How to get the current location latitude and longitude in android

Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation

Demo

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Activity

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;

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

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.getIsGPSTrackingEnabled())
        {
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(R.id.fieldLatitude);
            textview.setText(stringLatitude);

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(R.id.fieldLongitude);
            textview.setText(stringLongitude);

            String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(R.id.fieldCountry);
            textview.setText(country);

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(R.id.fieldCity);
            textview.setText(city);

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(R.id.fieldPostalCode);
            textview.setText(postalCode);

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(R.id.fieldAddressLine);
            textview.setText(addressLine);
        }
        else
        {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gpsTracker.showSettingsAlert();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
        return true;
    }
}

GPS Tracker

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
 * Create this Class from tutorial : 
 * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
 * 
 * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
 * 
 */

public class GPSTracker extends Service implements LocationListener {

    // Get Class Name
    private static String TAG = GPSTracker.class.getName();

    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS Tracking is enabled 
    boolean isGPSTrackingEnabled = false;

    Location location;
    double latitude;
    double longitude;

    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;

    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    /**
     * Try to get my current location by GPS or Network Provider
     */
    public void getLocation() {

        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use GPS Service");

                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */

                provider_info = LocationManager.GPS_PROVIDER;

            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use Network State to get GPS coordinates");

                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;

            } 

            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                    provider_info,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                    this
                );

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }

    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        return latitude;
    }

    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        return longitude;
    }

    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {

        return this.isGPSTrackingEnabled;
    }

    /**
     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title
        alertDialog.setTitle(R.string.GPSAlertDialogTitle);

        //Setting Dialog Message
        alertDialog.setMessage(R.string.GPSAlertDialogMessage);

        //On Pressing Setting button
        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        //On pressing cancel button
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses 
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Note

If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.

Article: Getting the Last Known Location

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

Background service with location listener in android

First you need to create a Service. In that Service, create a class extending LocationListener. For this, use the following code snippet of Service:

public class LocationService extends Service {
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;

Intent intent;
int counter = 0;

@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);
}

@Override
public void onStart(Intent intent, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, (LocationListener) listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}

@Override
public IBinder onBind(Intent intent)
{
    return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}



/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}



@Override
public void onDestroy() {
    // handler.removeCallbacks(sendUpdatesToUI);     
    super.onDestroy();
    Log.v("STOP_SERVICE", "DONE");
    locationManager.removeUpdates(listener);
}

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}
public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(final Location loc)
    {
        Log.i("*****", "Location changed");
        if(isBetterLocation(loc, previousBestLocation)) {
            loc.getLatitude();
            loc.getLongitude();
            intent.putExtra("Latitude", loc.getLatitude());
            intent.putExtra("Longitude", loc.getLongitude());
            intent.putExtra("Provider", loc.getProvider());
            sendBroadcast(intent);

        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
    }


    public void onProviderEnabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
    }
}

Add this Service any where in your project, the way you want! :)

How do I get countifs to select all non-blank cells in Excel?

Use a criteria of "<>". It will count anything which isn't an empty cell, including #NAME? or #DIV/0!. As to why it works, damned if I know, but Excel seems to understand it.

Note: works nicely in Google Spreadsheet too

Recursively find all files newer than a given time

You can find every file what is created/modified in the last day, use this example:

find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print

for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want

What's the difference between VARCHAR and CHAR?

CHAR is fixed length and VARCHAR is variable length. CHAR always uses the same amount of storage space per entry, while VARCHAR only uses the amount necessary to store the actual text.

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

How to access a mobile's camera from a web app?

You'll want to use getUserMedia to access the camera.

This tutorial outlines the basics of accessing a device camera from the browser: https://medium.com/@aBenjamin765/make-a-camera-web-app-tutorial-part-1-ec284af8dddf

Note: This works on most Android devices, and in iOS in Safari only.

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

HashMaps and Null values?

HashMap supports both null keys and values

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

... and permits null values and the null key

So your problem is probably not the map itself.

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

How can I enable auto complete support in Notepad++?

For basic autocompletion, have a look at the files in %ProgramFiles%\Notepad++\plugins\APIs. It's basically just an XML file with keywords in. If you want calltips ("function parameters hint"), check out these instructions.

I've never found any more documentation, but cpp.xml has a calltip for fopen, while php.xml is quite complete.

Eclipse returns error message "Java was started but returned exit code = 1"

I too faced the similar issue , not solved after adding the command in eclipse.ini file. My root cause is different. I was experimenting on sequence diagrams using objectaid. This is throwing an exception and disturbed my workspace. You may have different issue when working on new plugins. Better you check the log file located in your project work-space C:\path\to\workspace\.metadata\.log

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

How to clear the Entry widget after a button is pressed in Tkinter?

Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.

def Reset():
    cmb.set("")

here, cmb is a variable in which you have assigned the Combobox. Now call that function in a button such as,

btn2 = ttk.Button(root, text="Reset",command=Reset)

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

Remove "whitespace" between div element

You can remove extra space inside DIv by using below property of CSS in a parent (container) div element

display:inline-flex

Before Adding dislay:inline-flex;

After Adding display:inline-flex; in css

Storing an object in state of a React component?

You can use ES6 spread on previous values in the object to avoid overwrite

this.setState({
     abc: {
            ...this.state.abc,
            xyz: 'new value'
           }
});

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

CSS/Javascript to force html table row on a single line

If you hide the overflow and there is a long word, you risk loosing that word, so you could go one step further and use the "word-wrap" css attribute.

http://msdn.microsoft.com/en-us/library/ms531186(VS.85).aspx

MongoDB: update every document on one field

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);

Run react-native application on iOS device directly from command line?

If you get this error [email protected] preinstall: ./src/scripts/check_reqs.js && xcodebuild ... using npm install -g ios-deploy

Try this. It works for me:

  1. sudo npm uninstall -g ios-deploy
  2. brew install ios-deploy

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:

<input type="text" name="name" autofocus="autofocus" id="xax" />

If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded.. For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html

How do I grep recursively?

For .gz files, recursively scan all files and directories Change file type or put *

find . -name \*.gz -print0 | xargs -0 zgrep "STRING"

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

suppose you need a label with text customername than you can achive it using 2 ways

[1]@Html.Label("CustomerName")

[2]@Html.LabelFor(a => a.CustomerName)  //strongly typed

2nd method used a property from your model. If your view implements a model then you can use the 2nd method.

More info please visit below link

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

What is an example of the Liskov Substitution Principle?

An important example of the use of LSP is in software testing.

If I have a class A that is an LSP-compliant subclass of B, then I can reuse the test suite of B to test A.

To fully test subclass A, I probably need to add a few more test cases, but at the minimum I can reuse all of superclass B's test cases.

A way to realize is this by building what McGregor calls a "Parallel hierarchy for testing": My ATest class will inherit from BTest. Some form of injection is then needed to ensure the test case works with objects of type A rather than of type B (a simple template method pattern will do).

Note that reusing the super-test suite for all subclass implementations is in fact a way to test that these subclass implementations are LSP-compliant. Thus, one can also argue that one should run the superclass test suite in the context of any subclass.

See also the answer to the Stackoverflow question "Can I implement a series of reusable tests to test an interface's implementation?"

MySQL - Get row number on select

SELECT @rn:=@rn+1 AS rank, itemID, ordercount
FROM (
  SELECT itemID, COUNT(*) AS ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC
) t1, (SELECT @rn:=0) t2;

How to redirect stdout to both file and console with scripting?

Use logging module to debug and follow your app

Here is how I managed to log to file and to console / stdout

import logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    filename='logs_file',
                    filemode='w')
# Until here logs only to file: 'logs_file'

# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')

read it from source: https://docs.python.org/2/howto/logging-cookbook.html

How to ignore certain files in Git

You should write something like

*.class

into your .gitignore file.

Javascript Thousand Separator / string format

// thousand separates a digit-only string using commas
// by element:  onkeyup = "ThousandSeparate(this)"
// by ID:       onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,'');
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

jQuery deferreds and promises - .then() vs .done()

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

Prior to jQuery 1.8, then() was just syntactic sugar:

promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )

As of 1.8, then() is an alias for pipe() and returns a new promise, see here for more information on pipe().

success() and error() are only available on the jqXHR object returned by a call to ajax(). They are simple aliases for done() and fail() respectively:

jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error

Also, done() is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):

// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );

Same goes for fail().

How to delete a localStorage item when the browser window/tab is closed?

There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.

I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.

What is a pre-revprop-change hook in SVN, and how do I create it?

Here is the link to the stack overflow question with many common hooks Common Types of Subversion Hooks, including the original source of the pre-revprop-change hook for Windows cross-posted here.

You should refer there as they may get improved over time.

how to pass command line arguments to main method dynamically

Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab

enter image description here

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Composer - the requested PHP extension mbstring is missing from your system

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Combine two data frames by rows (rbind) when they have different sets of columns

Most of the base R answers address the situation where only one data.frame has additional columns or that the resulting data.frame would have the intersection of the columns. Since the OP writes I am hoping to retain the columns that do not match after the bind, an answer using base R methods to address this issue is probably worth posting.

Below, I present two base R methods: One that alters the original data.frames, and one that doesn't. Additionally, I offer a method that generalizes the non-destructive method to more than two data.frames.

First, let's get some sample data.

# sample data, variable c is in df1, variable d is in df2
df1 = data.frame(a=1:5, b=6:10, d=month.name[1:5])
df2 = data.frame(a=6:10, b=16:20, c = letters[8:12])

Two data.frames, alter originals
In order to retain all columns from both data.frames in an rbind (and allow the function to work without resulting in an error), you add NA columns to each data.frame with the appropriate missing names filled in using setdiff.

# fill in non-overlapping columns with NAs
df1[setdiff(names(df2), names(df1))] <- NA
df2[setdiff(names(df1), names(df2))] <- NA

Now, rbind-em

rbind(df1, df2)
    a  b        d    c
1   1  6  January <NA>
2   2  7 February <NA>
3   3  8    March <NA>
4   4  9    April <NA>
5   5 10      May <NA>
6   6 16     <NA>    h
7   7 17     <NA>    i
8   8 18     <NA>    j
9   9 19     <NA>    k
10 10 20     <NA>    l

Note that the first two lines alter the original data.frames, df1 and df2, adding the full set of columns to both.


Two data.frames, do not alter originals
To leave the original data.frames intact, first loop through the names that differ, return a named vector of NAs that are concatenated into a list with the data.frame using c. Then, data.frame converts the result into an appropriate data.frame for the rbind.

rbind(
  data.frame(c(df1, sapply(setdiff(names(df2), names(df1)), function(x) NA))),
  data.frame(c(df2, sapply(setdiff(names(df1), names(df2)), function(x) NA)))
)

Many data.frames, do not alter originals
In the instance that you have more than two data.frames, you could do the following.

# put data.frames into list (dfs named df1, df2, df3, etc)
mydflist <- mget(ls(pattern="df\\d+"))
# get all variable names
allNms <- unique(unlist(lapply(mydflist, names)))

# put em all together
do.call(rbind,
        lapply(mydflist,
               function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                  function(y) NA)))))

Maybe a bit nicer to not see the row names of original data.frames? Then do this.

do.call(rbind,
        c(lapply(mydflist,
                 function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                    function(y) NA)))),
          make.row.names=FALSE))

Java ArrayList copy

Just for completion: All the answers above are going for a shallow copy - keeping the reference of the original objects. I you want a deep copy, your (reference-) class in the list have to implement a clone / copy method, which provides a deep copy of a single object. Then you can use:

newList.addAll(oldList.stream().map(s->s.clone()).collect(Collectors.toList()));

How to check if memcache or memcached is installed for PHP?

You have several options ;)

$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');

Else clause on Python while statement

In reply to Is there a specific reason?, here is one interesting application: breaking out of multiple levels of looping.

Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.

for k in [2, 3, 5, 7, 11, 13, 17, 25]:
    for m in range(2, 10):
        if k == m:
            continue
        print 'trying %s %% %s' % (k, m)
        if k % m == 0:
            print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
            break
    else:
        continue
    print 'breaking another level of loop'
    break
else:
    print 'no divisor could be found!'

For both while and for loops, the else statement is executed at the end, unless break was used.

In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I simply converted the varchar field that I wanted to convert into a new table (with a DateTime filed) to a DateTime compatible layout first and then SQL will do the conversion from varchar to DateTime without problems.

In the below (not my created table with those names !) I simply make the varchar field to be a DateTime lookalike if you want to:

update report1455062507424 
set [Move Time] = substring([Move Time], 7, 4) + '-'+ substring([Move Time], 4, 2) + '-'+ substring([Move Time], 1, 2) + ' ' + 
    substring([Move Time], 12, 5)  

Reactive forms - disabled attribute

Only who are using reactive forms : For native HTML elements [attr.disabled] will work but for material elements we need to dynamically disable the element.

this.form.get('controlname').disable();

Otherwise it will show in console warning message.

How to obtain the number of CPUs/cores in Linux from the command line?

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:

# lscpu


Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    1
Core(s) per socket:    4
CPU socket(s):         2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 15
Stepping:              7
CPU MHz:               1866.669
BogoMIPS:              3732.83
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              4096K
NUMA node0 CPU(s):     0-7

See also https://unix.stackexchange.com/questions/468766/understanding-output-of-lscpu.

Log all queries in mysql

OS / mysql version:

$ uname -a
Darwin Raphaels-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 x86_64

$ mysql --version
/usr/local/mysql/bin/mysql  Ver 14.14 Distrib 5.6.23, for osx10.8 (x86_64) using  EditLine wrapper

Adding logging (example, I don't think /var/log/... is the best path on Mac OS but that worked:

sudo vi ./usr/local/mysql-5.6.23-osx10.8-x86_64/my.cnf

[mysqld]
general_log = on
general_log_file=/var/log/mysql/mysqld_general.log

Restarted Mysql

Result:

$ sudo tail -f /var/log/mysql/mysqld_general.log
181210  9:41:04    21 Connect   root@localhost on employees
           21 Query /* mysql-connector-java-5.1.47 ( Revision: fe1903b1ecb4a96a917f7ed3190d80c049b1de29 ) */SELECT  @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@collation_server AS collation_server, @@collation_connection AS collation_connection, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS transaction_isolation, @@wait_timeout AS wait_timeout
           21 Query SET NAMES latin1
           21 Query SET character_set_results = NULL
           21 Query SET autocommit=1
           21 Query SELECT USER()
           21 Query SELECT USER()
181210  9:41:10    21 Query show tables
181210  9:41:25    21 Query select count(*) from current_dept_emp

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

Saving ssh key fails

If you prefer to use a GUI to create the keys

  1. Use Putty Gen to generate a key
  2. Export the key as an open SSH key
  3. As mentioned by @VonC create the .ssh directory and then you can drop the private and public keys in there
  4. Or use a GUI program (like Tortoise Git) to use the SSH keys

For a walkthrough on putty gen for the above steps, please see http://ask-leo.com/how_do_i_create_and_use_public_keys_with_ssh.html

How do I rotate a picture in WinForms

This solution assumes that you want to draw the image in a picture box and that the image orientation will follow the mouse movements over this picture box. No image is assigned to the picture box. Instead I'm getting the image from a project resource.

private float _angle;

public Form1()
{
    InitializeComponent();
}

private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
    (float centerX, float centerY) = GetCenter(pictureBox1.ClientRectangle);
    _angle = (float)(Math.Atan2(e.Y - centerY, e.X - centerX) * 180.0 / Math.PI);
    pictureBox1.Invalidate(); // Triggers redrawing
}

private void PictureBox_Paint(object sender, PaintEventArgs e)
{
    Bitmap image = Properties.Resources.ExampleImage;
    float scale = (float)pictureBox1.Width / image.Width;

    (float centerX, float centerY) = GetCenter(e.ClipRectangle);

    e.Graphics.TranslateTransform(centerX, centerY);
    e.Graphics.RotateTransform(_angle);
    e.Graphics.TranslateTransform(-centerX, -centerY);
    e.Graphics.ScaleTransform(scale, scale);
    e.Graphics.DrawImage(image, 0, 0);
}

// Uses C# 7.0 value tuples / .NET Framework 4.7.
// For previous versions, return a PointF instead.
private static (float, float) GetCenter(Rectangle rect)
{
    float centerX = (rect.Left + rect.Right) * 0.5f;
    float centerY = (rect.Top + rect.Bottom) * 0.5f;
    return (centerX, centerY);
}

Make sure to to select the mouse event handlers PictureBox_MouseMove and PictureBox_Paint in properties window of the picture box for these events, after you copy/pasted this code into the form.

Note: You could also use a simple Panel or any other control, like a label; however, the PictureBox has the advantage to use double buffering by default, which eliminates flickering.

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Should I use the Reply-To header when sending emails as a service to others?

After reading all of this, I might just embed a hyperlink in the email body like this:

To reply to this email, click here <a href="mailto:...">[email protected]</a>

Getting the encoding of a Postgres database

Because there's more than one way to skin a cat:

psql -l

Shows all the database names, encoding, and more.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Add an object to a python list

You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

mylist[:]

Example:

>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

C - determine if a number is prime

Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.

By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.

public bool IsPrimeNumber(int val) {
    // Using Sieve of Eratosthenes.
    if (val < 2)
    {
        return false;
    }

    // Reserve place for val + 1 and set with true.
    var mark = new bool[val + 1];
    for(var i = 2; i <= val; i++)
    {
        mark[i] = true;
    }

    // Iterate from 2 ... sqrt(val).
    for (var i = 2; i <= Math.Sqrt(val); i++)
    {
        if (mark[i])
        {
            // Cross out every i-th number in the places after i (all the multiples of i).
            for (var j = (i * i); j <= val; j += i)
            {
                mark[j] = false;
            }
        }
    }

    return mark[val];
}

IsPrimeNumber(1000000000) takes 21s 758ms.

NOTE: Value might vary depend on hardware specifications.

Pygame Drawing a Rectangle

Have you tried this:

PyGame Drawing Basics

Taken from the site:

pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

How can I mimic the bottom sheet from the Maps app?

I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.

See below link for more details.

https://github.com/OfTheWolf/UBottomSheet

ubottom sheet

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

My App.config looks as below:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I noticed that there is localDB in the path that you mentioned above and has the version v11.0. So I entered (LocalDB\V11.0) in Add Connection dialogue and it worked for me.

AWK: Access captured group from line pattern

With gawk, you can use the match function to capture parenthesized groups.

gawk 'match($0, pattern, ary) {print ary[1]}' 

example:

echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}' 

outputs cd.

Note the specific use of gawk which implements the feature in question.

For a portable alternative you can achieve similar results with match() and substr.

example:

echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'

outputs cd.

Running Google Maps v2 on the Android emulator

At the moment, referencing the Google Android Map API v2 you can't run Google Maps v2 on the Android emulator; you must use a device for your tests.

How to set max and min value for Y axis

_x000D_
_x000D_
var config = {_x000D_
            type: 'line',_x000D_
            data: {_x000D_
                labels: ["January", "February", "March", "April", "May", "June", "July"],_x000D_
                datasets: [{_x000D_
                        label: "My First dataset",_x000D_
                        data: [10, 80, 56, 60, 6, 45, 15],_x000D_
                        fill: false,_x000D_
                        backgroundColor: "#eebcde ",_x000D_
                        borderColor: "#eebcde",_x000D_
                        borderCapStyle: 'butt',_x000D_
                        borderDash: [5, 5],_x000D_
                    }]_x000D_
            },_x000D_
            options: {_x000D_
                responsive: true,_x000D_
                legend: {_x000D_
                    position: 'bottom',_x000D_
                },_x000D_
                hover: {_x000D_
                    mode: 'label'_x000D_
                },_x000D_
                scales: {_x000D_
                    xAxes: [{_x000D_
                            display: true,_x000D_
                            scaleLabel: {_x000D_
                                display: true,_x000D_
                                labelString: 'Month'_x000D_
                            }_x000D_
                        }],_x000D_
                    yAxes: [{_x000D_
                            display: true,_x000D_
                            ticks: {_x000D_
                                beginAtZero: true,_x000D_
                                steps: 10,_x000D_
                                stepValue: 5,_x000D_
                                max: 100_x000D_
                            }_x000D_
                        }]_x000D_
                },_x000D_
                title: {_x000D_
                    display: true,_x000D_
                    text: 'Chart.js Line Chart - Legend'_x000D_
                }_x000D_
            }_x000D_
        };_x000D_
_x000D_
        var ctx = document.getElementById("canvas").getContext("2d");_x000D_
       new Chart(ctx, config);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
  <canvas id="canvas"></canvas>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

Programmatically add new column to DataGridView

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

How do you get total amount of RAM the computer has?

You could use WMI. Found a snippit.

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _ 
& strComputer & "\root\cimv2") 
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")

For Each objComputer in colComputer 
  strMemory = objComputer.TotalPhysicalMemory
Next

Java - get the current class name?

Try,

String className = this.getClass().getSimpleName();

This will work as long as you don't use it in a static method.

How to convert String to DOM Document object in java?

Either escape the double quotes with \

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"

or use single quotes instead

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"

How to delete a certain row from mysql table with same column values?

Add a limit to the delete query

delete from orders 
where id_users = 1 and id_product = 2
limit 1

How to get all the values of input array element jquery

You can use .map().

Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Use

var arr = $('input[name="pname[]"]').map(function () {
    return this.value; // $(this).val()
}).get();

Parsing JSON string in Java

Here is the example of one Object, For your case you have to use JSONArray.

public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
try{  
   JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
   String empname=emp.getString("name");  
   int empsalary=emp.getInt("salary");  

   String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
   textView1.setText(str);  

}catch (Exception e) {e.printStackTrace();}  
   //Do when JSON has problem.
}

I don't have time but tried to give an idea. If you still can't do it, then I will help.

Importing from a relative path in Python

Don't do relative import.

From PEP8:

Relative imports for intra-package imports are highly discouraged.

Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.

Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.

Read binary file as string in Ruby

Ruby have binary reading

data = IO.binread(path/filaname)

or if less than Ruby 1.9.2

data = IO.read(path/file)

How to remove all null elements from a ArrayList or String Array?

As of 2015, this is the best way (Java 8):

tourists.removeIf(Objects::isNull);

Note: This code will throw java.lang.UnsupportedOperationException for fixed-size lists (such as created with Arrays.asList), including immutable lists.

How do I implement JQuery.noConflict() ?

In addition to that, passing true to $.noConflict(true); will also restore previous (if any) global variable jQuery, so that plugins can be initialized with correct jQuery version when multiple versions are being used.

Concatenate two PySpark dataframes

This should do it for you ...

from pyspark.sql.types import FloatType
from pyspark.sql.functions import randn, rand, lit, coalesce, col
import pyspark.sql.functions as F

df_1 = sqlContext.range(0, 6)
df_2 = sqlContext.range(3, 10)
df_1 = df_1.select("id", lit("old").alias("source"))
df_2 = df_2.select("id")

df_1.show()
df_2.show()
df_3 = df_1.alias("df_1").join(df_2.alias("df_2"), df_1.id == df_2.id, "outer")\
  .select(\
    [coalesce(df_1.id, df_2.id).alias("id")] +\
    [col("df_1." + c) for c in df_1.columns if c != "id"])\
  .sort("id")
df_3.show()

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was doing what doug suggests ("Reset Content and Settings") which works but takes a lot of time and it is really annoying... until I recently found completely accidental another solution that is much quicker and seems to also work so far! Just hit cmd+L on your simulator or go to the simulator menu "Hardware -> Lock", which locks the screen, when you unlock the screen the app works like nothing ever happened :)

How to register multiple servlets in web.xml in one Spring application

Use config something like this:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

What is the difference between '/' and '//' when used for division?

// is floor division, it will always give you the integer floor of the result. The other is 'regular' division.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

webpack command not working

You can run npx webpack. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package. Source of info: https://webpack.js.org/guides/getting-started/

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

Adding a Method to an Existing Object Instance

In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the Zope Wiki:

from SomeOtherProduct.SomeModule import SomeClass
def speak(self):
   return "ook ook eee eee eee!"
SomeClass.speak = speak

This code will overwrite/create a method called peak in the class. In Jeff Atwood's recent post on monkey patching, he showed an example in C# 3.0 which is the current language I use for work.

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

JOIN queries vs multiple queries

There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.

The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.

Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I have found solution at https://www.youtube.com/watch?v=dm4z9l26O0I

You would need to use Tools > Script Editor. Create .gs and .html files there. See example at http://goo.gl/LxGXfU (link can be also found under Youtube video). Just copy

Once you have .gs and .html files in place save them and reload your spreadsheet. You will see "Custom menu" as the last item of your top menu. Select cell you would like to manage and click on this menu item.

During the first time it will ask you to authorize application - go ahead and do this.

Note (1): make sure that your cell has "Data validation" defined before you click on "Custom menu".

Note (2): it appeared that solution works with "List from a range" criteria for Data validation (it does not work with "List of items")

Salt and hash a password in Python

Here's my proposition:

for i in range(len(rserver.keys())):
    salt = uuid.uuid4().hex
    print(salt)
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
    rsalt.set(rserver.keys()[i], salt)

Difference between RUN and CMD in a Dockerfile

RUN: Can be many, and it is used in build process, e.g. install multiple libraries

CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"], ["node", "app.js"])

How do I use CSS with a ruby on rails application?

The original post might have been true back in 2009, but now it is actually incorrect now, and no linking is even required for the stylesheet as I see mentioned in some of the other responses. Rails will now do this for you by default.

  • Place any new sheet .css (or other) in app/assets/stylesheets
  • Test your server with rails-root/scripts/rails server and you'll see the link is added by rails itself.

You can test this with a path in your browser like testserverpath:3000/assets/filename_to_test.css?body=1

Convert array of strings into a string in Java

Try the Arrays.deepToString method.

Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

String Padding in C

It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long

printf("|%-10s|", "Hello");

will output

|Hello     |

In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.

Printf style formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia's printf page is of help too (mostly a history lesson of how widely printf has spread).

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

Exporting data In SQL Server as INSERT INTO

If you use it SQLServer 2008R2 you need to set Types of data to script field.

enter image description here

Lodash - difference between .extend() / .assign() and .merge()

Lodash version 3.10.1

Methods compared

  • _.merge(object, [sources], [customizer], [thisArg])
  • _.assign(object, [sources], [customizer], [thisArg])
  • _.extend(object, [sources], [customizer], [thisArg])
  • _.defaults(object, [sources])
  • _.defaultsDeep(object, [sources])

Similarities

  • None of them work on arrays as you might expect
  • _.extend is an alias for _.assign, so they are identical
  • All of them seem to modify the target object (first argument)
  • All of them handle null the same

Differences

  • _.defaults and _.defaultsDeep processes the arguments in reverse order compared to the others (though the first argument is still the target object)
  • _.merge and _.defaultsDeep will merge child objects and the others will overwrite at the root level
  • Only _.assign and _.extend will overwrite a value with undefined

Tests

They all handle members at the root in similar ways.

_.assign      ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge       ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults    ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a"  }

_.assign handles undefined but the others will skip it

_.assign      ({}, { a: 'a'  }, { a: undefined }) // => { a: undefined }
_.merge       ({}, { a: 'a'  }, { a: undefined }) // => { a: "a" }
_.defaults    ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }

They all handle null the same

_.assign      ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.merge       ({}, { a: 'a'  }, { a: null }) // => { a: null }
_.defaults    ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }

But only _.merge and _.defaultsDeep will merge child objects

_.assign      ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge       ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults    ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}

And none of them will merge arrays it seems

_.assign      ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge       ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults    ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a"  ] }

All modify the target object

a={a:'a'}; _.assign      (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge       (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults    (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }

None really work as expected on arrays

Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.

_.assign      ([], ['a'], ['bb']) // => [ "bb" ]
_.merge       ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults    ([], ['a'], ['bb']) // => [ "a"  ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a"  ]

_.assign      ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge       ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults    ([], ['a','b'], ['bb']) // => [ "a", "b"  ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b"  ]

Find length of 2D array Python

In addition, correct way to count total item number would be:

sum(len(x) for x in input)

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

How to get a list of installed android applications and pick one to run

@Jas: I don't have that code anymore, but I've found something close. I've made this to search for "components" of my application, they are just activities with a given category.

private List<String> getInstalledComponentList() {
    Intent componentSearchIntent = new Intent();
    componentSearchIntent.addCategory(Constants.COMPONENTS_INTENT_CATEGORY);
    componentSearchIntent.setAction(Constants.COMPONENTS_INTENT_ACTION_DEFAULT);
    List<ResolveInfo> ril = getPackageManager().queryIntentActivities(componentSearchIntent, PackageManager.MATCH_DEFAULT_ONLY);
    List<String> componentList = new ArrayList<String>();
    Log.d(LOG_TAG, "Search for installed components found " + ril.size() + " matches.");
    for (ResolveInfo ri : ril) {
        if (ri.activityInfo != null) {
            componentList.add(ri.activityInfo.packageName);// + ri.activityInfo.name);
            Log.d(LOG_TAG, "Found installed: " + componentList.get(componentList.size()-1));
        }
    }
    return componentList;
}

I've commented the part where it gets the activity name, but it's pretty straightforward.

LINQ select in C# dictionary

This will return all the values matching your key valueTitle

subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Not really answer to the question, but one-liners for foldl and foldr:

a = [8,3,4]

## Foldl
reduce(lambda x,y: x**y, a)
#68719476736

## Foldr
reduce(lambda x,y: y**x, a[::-1])
#14134776518227074636666380005943348126619871175004951664972849610340958208L

How do I use T-SQL's Case/When?

If logical test is against a single column then you could use something like

USE AdventureWorks2012;  
GO  
SELECT   ProductNumber, Category =  
      CASE ProductLine  
         WHEN 'R' THEN 'Road'  
         WHEN 'M' THEN 'Mountain'  
         WHEN 'T' THEN 'Touring'  
         WHEN 'S' THEN 'Other sale items'  
         ELSE 'Not for sale'  
      END,  
   Name  
FROM Production.Product  
ORDER BY ProductNumber;  
GO  

More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

jQuery Remove string from string

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];      
$("h1").text(name);

jsfiddle example

Create multiple threads and wait all of them to complete

I don't know if there is a better way, but the following describes how I did it with a counter and background worker thread.

private object _lock = new object();
private int _runningThreads = 0;

private int Counter{
    get{
        lock(_lock)
            return _runningThreads;
    }
    set{
        lock(_lock)
            _runningThreads = value;
    }
}

Now whenever you create a worker thread, increment the counter:

var t = new BackgroundWorker();
// Add RunWorkerCompleted handler

// Start thread
Counter++;

In work completed, decrement the counter:

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Counter--;
}

Now you can check for the counter anytime to see if any thread is running:

if(Couonter>0){
    // Some thread is yet to finish.
}

Logging in Scala

Using slf4j and a wrapper is nice but the use of it's built in interpolation breaks down when you have more than two values to interpolate, since then you need to create an Array of values to interpolate.

A more Scala like solution is to use a thunk or cluster to delay the concatenation of the error message. A good example of this is Lift's logger

Log.scala Slf4jLog.scala

Which looks like this:

class Log4JLogger(val logger: Logger) extends LiftLogger {
  override def trace(msg: => AnyRef) = if (isTraceEnabled) logger.trace(msg)
}

Note that msg is a call-by-name and won't be evaluated unless isTraceEnabled is true so there's no cost in generating a nice message string. This works around the slf4j's interpolation mechanism which requires parsing the error message. With this model, you can interpolate any number of values into the error message.

If you have a separate trait that mixes this Log4JLogger into your class, then you can do

trace("The foobar from " + a + " doesn't match the foobar from " +
      b + " and you should reset the baz from " + c")

instead of

info("The foobar from {0} doesn't match the foobar from {1} and you should reset the baz from {c},
     Array(a, b, c))

Show current assembly instruction in GDB

Setting the following option:

set  disassemble-next-line on
show disassemble-next-line

Will give you results that look like this:

(gdb) stepi
0x000002ce in ResetISR () at startup_gcc.c:245
245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
=> 0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
   0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0
(gdb) stepi
0x000002d0  245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
   0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
=> 0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Percentage calculation

You can hold onto the percentage as decimal (value \ total) and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:

var displayPercentage = $"{(decimal)value / total:P}";

or

//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

ASP.NET Button to redirect to another page

You can use PostBackUrl="~/Confirm.aspx"

For example:

In your .aspx file

<asp:Button ID="btnConfirm" runat="server" Text="Confirm" PostBackUrl="~/Confirm.aspx" />

or in your .cs file

btnConfirm.PostBackUrl="~/Confirm.aspx"

Can an interface extend multiple interfaces in Java?

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

for example, take a look here: http://www.tutorialspoint.com/java/java_interfaces.htm

Is there a way to ignore a single FindBugs warning?

While other answers on here are valid, they're not a full recipe for solving this.

In the spirit of completeness:

You need to have the findbugs annotations in your pom file - they're only compile time, so you can use the provided scope:

<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>findbugs-annotations</artifactId>
  <version>3.0.1</version>
  <scope>provided</scope>
</dependency>

This allows the use of @SuppressFBWarnings there is another dependency which provides @SuppressWarnings. However, the above is clearer.

Then you add the annotation above your method:

E.g.

@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
        justification = "Scanning generated code of try-with-resources")
@Override
public String get() {
    try (InputStream resourceStream =  owningType.getClassLoader().getResourceAsStream(resourcePath);
         BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream, UTF_8))) { ... }

This includes both the name of the bug and also a reason why you're disabling the scan for it.

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

Set View Width Programmatically

in code add below line:

spin27.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

INFO: No Spring WebApplicationInitializer types detected on classpath

I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.

Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.

Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a

public class HttpGatewayInit implements WebApplicationInitializer { ... }

which implements empty inherited methods, and the whole application works fine!

...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.

Using Exit button to close a winform program

We can close every window using Application.Exit(); Using this method we can close hidden windows also.

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }

How do I check if a PowerShell module is installed?

You can use the ListAvailable option of Get-Module:

if (Get-Module -ListAvailable -Name SomeModule) {
    Write-Host "Module exists"
} 
else {
    Write-Host "Module does not exist"
}

Data binding to SelectedItem in a WPF Treeview

I propose this solution (which I consider the easiest and memory leaks free) which works perfectly for updating the ViewModel's selected item from the View's selected item.

Please note that changing the selected item from the ViewModel won't update the selected item of the View.

public class TreeViewEx : TreeView
{
    public static readonly DependencyProperty SelectedItemExProperty = DependencyProperty.Register("SelectedItemEx", typeof(object), typeof(TreeViewEx), new FrameworkPropertyMetadata(default(object))
    {
        BindsTwoWayByDefault = true // Required in order to avoid setting the "BindingMode" from the XAML
    });

    public object SelectedItemEx
    {
        get => GetValue(SelectedItemExProperty);
        set => SetValue(SelectedItemExProperty, value);
    }

    protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs<object> e)
    {
        SelectedItemEx = e.NewValue;
    }
}

XAML usage

<l:TreeViewEx ItemsSource="{Binding Path=Items}" SelectedItemEx="{Binding Path=SelectedItem}" >

SQL/mysql - Select distinct/UNIQUE but return all columns?

That's a really good question. I have read some useful answers here already, but probably I can add a more precise explanation.

Reducing the number of query results with a GROUP BY statement is easy as long as you don't query additional information. Let's assume you got the following table 'locations'.

--country-- --city--
 France      Lyon
 Poland      Krakow
 France      Paris
 France      Marseille
 Italy       Milano

Now the query

SELECT country FROM locations
GROUP BY country

will result in:

--country--
 France
 Poland
 Italy

However, the following query

SELECT country, city FROM locations
GROUP BY country

...throws an error in MS SQL, because how could your computer know which of the three French cities "Lyon", "Paris" or "Marseille" you want to read in the field to the right of "France"?

In order to correct the second query, you must add this information. One way to do this is to use the functions MAX() or MIN(), selecting the biggest or smallest value among all candidates. MAX() and MIN() are not only applicable to numeric values, but also compare the alphabetical order of string values.

SELECT country, MAX(city) FROM locations
GROUP BY country

will result in:

--country-- --city--
 France      Paris
 Poland      Krakow
 Italy       Milano

or:

SELECT country, MIN(city) FROM locations
GROUP BY country

will result in:

--country-- --city--
 France      Lyon
 Poland      Krakow
 Italy       Milano

These functions are a good solution as long as you are fine with selecting your value from the either ends of the alphabetical (or numeric) order. But what if this is not the case? Let us assume that you need a value with a certain characteristic, e.g. starting with the letter 'M'. Now things get complicated.

The only solution I could find so far is to put your whole query into a subquery, and to construct the additional column outside of it by hands:

SELECT
     countrylist.*,
     (SELECT TOP 1 city
     FROM locations
     WHERE
          country = countrylist.country
          AND city like 'M%'
     )
FROM
(SELECT country FROM locations
GROUP BY country) countrylist

will result in:

--country-- --city--
 France      Marseille
 Poland      NULL
 Italy       Milano

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

How can I preview a merge in git?

git log currentbranch..otherbranch will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.

git diff currentbranch otherbranch will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.

Would these help?

Can I make dynamic styles in React Native?

You'll want something like this:

var RandomBgApp = React.createClass({
    render: function() {

        var getRandomColor = function() {
            var letters = '0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++ ) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        };

        var rows = [
            { name: 'row 1'},
            { name: 'row 2'},
            { name: 'row 3'}
        ];

        var rowNodes = rows.map(function(row) {
            return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
        });

        return (
            <View>
                {rowNodes}
            </View>
        );

    }
});

In this example I take the rows array, containing the data for the rows in the component, and map it into an array of Text components. I use inline styles to call the getRandomColor function every time I create a new Text component.

The issue with your code is that you define the style once and therefore getRandomColor only gets called once - when you define the style.

How to change default text file encoding in Eclipse?

Preferences >> General >> Editors >> Text editors >> Spelling: Enconding

P.S.: Eclipse Indigo and Juno.

What is the difference between function and procedure in PL/SQL?

In dead simple way it makes this meaning.

Functions :

These subprograms return a single value; mainly used to compute and return a value.

Procedure :

These subprograms do not return a value directly; mainly used to perform an action.

Example Program:

CREATE OR REPLACE PROCEDURE greetings

BEGIN 

dbms_output.put_line('Hello World!');

END ;
/

Executing a Standalone Procedure :

A standalone procedure can be called in two ways:

• Using the EXECUTE keyword • Calling the name of procedure from a PL/SQL block

The procedure can also be called from another PL/SQL block:

BEGIN 
greetings;
END;
/

Function:

CREATE OR REPLACE FUNCTION totalEmployees 
RETURN number IS
total number(3) := 0;
BEGIN 
SELECT count(*) into total 
FROM employees;
RETURN total; 
END;
/

Following program calls the function totalCustomers from an another block

DECLARE 
c number(3);
BEGIN 
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/

Creating instance list of different objects

List<Object> objects = new ArrayList<Object>();

objects list will accept any of the Object

You could design like as follows

public class BaseEmployee{/* stuffs */}

public class RegularEmployee extends BaseEmployee{/* stuffs */}

public class Contractors extends BaseEmployee{/* stuffs */}

and in list

List<? extends BaseEmployee> employeeList = new ArrayList<? extends BaseEmployee>();

How to test android apps in a real device with Android Studio?

  • First we have to enable the USB debugging mode. for that go to Settings -> Developer Options ->USB debugging in your phone checked it and allow it.
  • After it open android studio, click on SDK manager , check mark the Google USB Driver and hit install package.
  • After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  • Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  • Select Device Manager –> Portable Devices –> Your Device Name
  • Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  • Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  • Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

Viewing root access files/folders of android on windows

I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.

The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.

Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.

Inserting into Oracle and retrieving the generated sequence ID

Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.

create table batch(batchid number,
    batchname varchar2(30),
    batchtype char(1),
    source char(1),
    intarea number)
/

create sequence batch_seq start with 1
/

create trigger batch_bi
before insert on batch
for each row
begin
    select batch_seq.nextval into :new.batchid from dual;
end;
/

create procedure insert_batch(v_batchname batch.batchname%TYPE,
    v_batchtype batch.batchtype%TYPE,
    v_source batch.source%TYPE,
    v_intarea batch.intarea%TYPE,
    v_batchid out batch.batchid%TYPE)
as
begin
    insert into batch(batchname, batchtype, source, intarea)
    values(v_batchname, v_batchtype, v_source, v_intarea)
    returning batchid into v_batchid;
end;
/

You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:

declare
    l_batchid batch.batchid%TYPE;
begin
    insert_batch(v_batchname => 'Batch 1',
        v_batchtype => 'A',
        v_source => 'Z',
        v_intarea => 1,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);

    insert_batch(v_batchname => 'Batch 99',
        v_batchtype => 'B',
        v_source => 'Y',
        v_intarea => 9,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);
end;
/

Generated id: 1
Generated id: 2

You can make the call without an explicit anonymous block, e.g. from SQL*Plus:

variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);

... and use the bind variable :l_batchid to refer to the generated value afterwards:

print l_batchid;
insert into some_table values(:l_batch_id, ...);

The value violated the integrity constraints for the column

It's as the error message says "The value violated the integrity constraints for the column" for column "Copy of F2"

Make it so it doesn't violate the value in the target table. What the allowable values are, data types, etc are not provided in your question so we cannot be more specific in answering.

To address the downvote, No, really it's as it says: you are putting something into a column that is not allowed. It could be Faizan points out, that you're putting a NULL into a NOT NULLable column, but it could be a whole host of other things and as the original poster never provided any update, we're left to guess. Was there a foreign key constraint that the insert violated? Maybe there's a check constraint that got blown? Maybe the source column in Excel has a valid date value for Excel that is not valid for the target column's date/time data type.

Thus, baring concrete information, the best possible answer is "don't do the thing that breaks it" In this case, something about "Copy of F2" is bad for the target column. Give us table definitions, supplied values, etc, then you can specific answers.

Telling people to make a NOT NULLable column into a NULLable one might be the right answer. It might also be the most horrific answer known to mankind. If an existing process expects there to always be a value in column "Copy of F2" changing the constraint to NULL can wreak havoc on existing queries. For example

SELECT * FROM ArbitraryTable AS T WHERE T.[Copy of F2] = '';

Currently, that query retrieves everything that was freshly imported because Copy of F2 is a poorly named status indicator. That data needs to get fed into the next system so... bills can get paid. As soon as you make it such that unprocessed rows can have a NULL value, the above query no longer satisfies that. Bills don't get paid, collections repos your building and now you're out of a job, all because you didn't do impact analysis, etc, etc.

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

Delete empty lines using sed

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

sed '/^[[:space:]]*$/d'

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d'

(Note that sed does NOT support PCRE.)

Why doesn't file_get_contents work?

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

How do you fix a bad merge, and replay your good commits onto a fixed merge?

You should probably clone your repository first.

Remove your file from all branches history:
git filter-branch --tree-filter 'rm -f filename.orig' -- --all

Remove your file just from the current branch:
git filter-branch --tree-filter 'rm -f filename.orig' -- --HEAD    

Lastly you should run to remove empty commits:
git filter-branch -f --prune-empty -- --all

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

Run as java application option disabled in eclipse

You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".

Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X to open up a context menu, then press J.

How can I round a number in JavaScript? .toFixed() returns a string?

You can simply use a '+' to convert the result to a number.

var x = 22.032423;
x = +x.toFixed(2); // x = 22.03

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to sort in-place using the merge sort algorithm?

There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.

There are also links to more detailed theoretical analysis by the same author associated with this link.

JAXB Exception: Class not known to this context

This error message happens either because your ProfileDto class is not registered in the JAXB Content, or the class using it does not use @XmlSeeAlso(ProfileDto.class) to make processable by JAXB.

About your comment:

I was under the impression the annotations was only needed when the referenced class was a sub-class.

No, they are also needed when not declared in the JAXB context or, for example, when the only class having a static reference to it has this reference annotated with @XmlTransient. I maintain a tutorial here.

Private properties in JavaScript ES6 classes

Yes - you can create encapsulated property, but it's not been done with access modifiers (public|private) at least not with ES6.

Here is a simple example how it can be done with ES6:

1 Create class using class word

2 Inside it's constructor declare block-scoped variable using let OR const reserved words -> since they are block-scope they cannot be accessed from outside (encapsulated)

3 To allow some access control (setters|getters) to those variables you can declare instance method inside it's constructor using: this.methodName=function(){} syntax

"use strict";
    class Something{
        constructor(){
            //private property
            let property="test";
            //private final (immutable) property
            const property2="test2";
            //public getter
            this.getProperty2=function(){
                return property2;
            }
            //public getter
            this.getProperty=function(){
                return property;
            }
            //public setter
            this.setProperty=function(prop){
                property=prop;
            }
        }
    }

Now lets check it:

var s=new Something();
    console.log(typeof s.property);//undefined 
    s.setProperty("another");//set to encapsulated `property`
    console.log(s.getProperty());//get encapsulated `property` value
    console.log(s.getProperty2());//get encapsulated immutable `property2` value

How does @synchronized lock/unlock in Objective-C?

It just associates a semaphore with every object, and uses that.

Tooltips with Twitter Bootstrap

Simply mark all the data-toggles...

jQuery(function () {
    jQuery('[data-toggle=tooltip]').tooltip();
});

http://jsfiddle.net/Amged/xUQ6D/19/

Excel VBA Run-time error '13' Type mismatch

Sub HighlightSpecificValue()

'PURPOSE: Highlight all cells containing a specified values


Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range

'What value do you want to find?
  fnd = InputBox("I want to hightlight cells containing...", "Highlight")

    'End Macro if Cancel Button is Clicked or no Text is Entered
      If fnd = vbNullString Then Exit Sub

Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)

enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)

'Test to see if anything was found
  If Not FoundCell Is Nothing Then
    FirstFound = FoundCell.Address

  Else
    GoTo NothingFound
  End If

Set rng = FoundCell

'Loop until cycled through all unique finds
  Do Until FoundCell Is Nothing
    'Find next cell with fnd value
      Set FoundCell = myRange.FindNext(after:=FoundCell)







    'Add found cell to rng range variable
      Set rng = Union(rng, FoundCell)

    'Test to see if cycled through to first found cell
      If FoundCell.Address = FirstFound Then Exit Do


  Loop

'Highlight Found cells yellow

  rng.Interior.Color = RGB(255, 255, 0)

  Dim fnd1 As String
  fnd1 = "Rah"
  'Condition highlighting

  Set FoundCell = myRange.FindNext(after:=FoundCell)



  If FoundCell.Value("rah") Then
      rng.Interior.Color = RGB(255, 0, 0)

  ElseIf FoundCell.Value("Nav") Then

    rng.Interior.Color = RGB(0, 0, 255)



    End If





'Report Out Message
  MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd

Exit Sub

'Error Handler
NothingFound:
  MsgBox "No cells containing: " & fnd & " were found in this worksheet"

End Sub

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

How can I do a line break (line continuation) in Python?

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

How to compare each item in a list with the rest, only once?

I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:

for index, this in enumerate(mylist):
    for that in mylist[index+1:]:
        compare(this, that)

ImportError: No module named PyQt4

After brew install pyqt, you can brew test pyqt which will use the python you have got in your PATH in oder to do the test (show a Qt window).

For non-brewed Python, you'll have to set your PYTHONPATH as brew info pyqt will tell.

Sometimes it is necessary to open a new shell or tap in order to use the freshly brewed binaries.

I frequently check these issues by printing the sys.path from inside of python: python -c "import sys; print(sys.path)" The $(brew --prefix)/lib/pythonX.Y/site-packages have to be in the sys.path in order to be able to import stuff. As said, for brewed python, this is default but for any other python, you will have to set the PYTHONPATH.

C++: Print out enum value as text

Use the preprocessor:

#define VISIT_ERROR(FIRST, MIDDLE, LAST) \
    FIRST(ErrorA) MIDDLE(ErrorB) /* MIDDLE(ErrorB2) */ LAST(ErrorC)

enum Errors
{
    #define ENUMFIRST_ERROR(E)  E=0,
    #define ENUMMIDDLE_ERROR(E) E,
    #define ENUMLAST_ERROR(E)   E
    VISIT_ERROR(ENUMFIRST_ERROR, ENUMMIDDLE_ERROR, ENUMLAST_ERROR)
    // you might undefine the 3 macros defined above
};

std::string toString(Error e)
{
    switch(e)
    {
    #define CASERETURN_ERROR(E)  case E: return #E;
    VISIT_ERROR(CASERETURN_ERROR, CASERETURN_ERROR, CASERETURN_ERROR)
    // you might undefine the above macro.
    // note that this will produce compile-time error for synonyms in enum;
    // handle those, if you have any, in a distinct macro

    default:
        throw my_favourite_exception();
    }
}

The advantage of this approach is that: - it's still simple to understand, yet - it allows for various visitations (not just string)

If you're willing to drop the first, craft yourself a FOREACH() macro, then #define ERROR_VALUES() (ErrorA, ErrorB, ErrorC) and write your visitors in terms of FOREACH(). Then try to pass a code review :).

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

How to open the Google Play Store directly from my Android application?

public void launchPlayStore(Context context, String packageName) {
    Intent intent = null;
    try {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
        }
    }

How to create a batch file to run cmd as administrator

To prevent the script from failing when the script file resides on a non system drive (c:) and in a directory with spaces.

Batch_Script_Run_As_Admin.cmd

@echo off
if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::   





::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.

pause

How do I get the value of a textbox using jQuery?

Possible Duplicate:

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

 var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

 var txt=$('input:text[name=DrugDurationLength]').val();

Why .NET String is immutable?

You never have to defensively copy immutable data. Despite the fact that you need to copy it to mutate it, often the ability to freely alias and never have to worry about unintended consequences of this aliasing can lead to better performance because of the lack of defensive copying.

Mockito matcher and array of primitives

I used Matchers.refEq for this.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

How to use cookies in Python Requests

From the documentation:

  1. get cookie from response

    url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)`
    

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

Large Numbers in Java

Use the BigInteger class that is a part of the Java library.

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html

Curl GET request with json parameter

For username and password protected services use the following

curl -u admin:password -X GET http://172.16.2.125:9200 -d '{"sort":[{"lastUpdateTime":{"order":"desc"}}]}'

How to make primary key as autoincrement for Room Persistence lib

add @PrimaryKey(autoGenerate = true)

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    @ColumnInfo(name = "phone")
    private String phone;

    public User(){
    }

    //type-1
    public User(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    //type-2
    public User(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

}

while storing data

 //type-1
 db.userDao().InsertAll(new User(sName,sPhone)); 

 //type-2
 db.userDao().InsertAll(new User(0,sName,sPhone)); 

type-1

If you are not passing value for primary key, by default it will 0 or null.

type-2

Put null or zero for the id while creating object (my case user object)

If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.

If the field's type is Integer or Long (Object) (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.

matplotlib colorbar in each subplot

Please have a look at this matplotlib example page. There it is shown how to get the following plot with four individual colorbars for each subplot: enter image description here

I hope this helps.
You can further have a look here, where you can find a lot of what you can do with matplotlib.

VB.Net Properties - Public Get, Private Set

    Public Property Name() As String
        Get
            Return _name
        End Get
        Private Set(ByVal value As String)
            _name = value
        End Set
   End Property

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...

I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:

http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html

Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)

Include these 3 files within your project:

  • oci.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oci.dll)
  • oraociei11.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oraociei11.dll)
  • OraOps11w.dll (ODAC1120320Xcopy_32bit\odp.net4\bin\OraOps11w.dll)

When I tried to create another application with the correct reference and files I would receive that error message.

The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.

I also ran into a registry error, this fixed it.

public void updateRegistryForOracleNLS()
{
    RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
    oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}

For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm

After that, everything worked smooth.

I hope it helps.

How to run function of parent window when child window closes?

Check following link. This would be helpful too..

In Parent Window:

function OpenChildAsPopup() {
        var childWindow = window.open("ChildWindow.aspx", "_blank",
        "width=200px,height=350px,left=200,top=100");
        childWindow.focus();
 }

function ChangeBackgroudColor() {
        var para = document.getElementById('samplePara');
        if (para !="undefied") {
            para.style.backgroundColor = '#6CDBF5';
        }
 }

Parent Window HTML Markup:

<div>
  <p id="samplePara" style="width: 350px;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  </p><br />
 <asp:Button ID="Button1" Text="Open Child Window" 
         runat="server" OnClientClick="OpenChildAsPopup();"/>
</div>

In Child Window:

// This will be called when the child window is closed.     
  window.onunload = function (e) {
        opener.ChangeBackgroudColor();
        //or you can do
        //var para = opener.document.getElementById('samplePara');
        //if (para != "undefied") {
        //    para.style.backgroundColor = '#6CDBF5';
        //}
    };

Creating a UIImage from a UIColor to use as a background image for UIButton

Your code works fine. You can verify the RGB colors with Iconfactory's xScope. Just compare it to [UIColor whiteColor].

c# - approach for saving user settings in a WPF application?

I wanted to use an xml control file based on a class for my VB.net desktop WPF application. The above code to do this all in one is excellent and set me in the right direction. In case anyone is searching for a VB.net solution here is the class I built:

Imports System.IO
Imports System.Xml.Serialization

Public Class XControl

Private _person_ID As Integer
Private _person_UID As Guid

'load from file
Public Function XCRead(filename As String) As XControl
    Using sr As StreamReader = New StreamReader(filename)
        Dim xmls As New XmlSerializer(GetType(XControl))
        Return CType(xmls.Deserialize(sr), XControl)
    End Using
End Function

'save to file
Public Sub XCSave(filename As String)
    Using sw As StreamWriter = New StreamWriter(filename)
        Dim xmls As New XmlSerializer(GetType(XControl))
        xmls.Serialize(sw, Me)
    End Using
End Sub

'all the get/set is below here

Public Property Person_ID() As Integer
    Get
        Return _person_ID
    End Get
    Set(value As Integer)
        _person_ID = value
    End Set
End Property

Public Property Person_UID As Guid
    Get
        Return _person_UID
    End Get
    Set(value As Guid)
        _person_UID = value
    End Set
End Property

End Class

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

How to remove the border highlight on an input text element

None of the solutions worked for me in Firefox.

The following solution changes the border style on focus for Firefox and sets the outline to none for other browsers.

I've effectively made the focus border go from a 3px blue glow to a border style that matches the text area border. Here's some border styles:

Dashed border (border 2px dashed red): Dashed border. border 2px dashed red

No border! (border 0px):
No border. border:0px

Textarea border (border 1px solid gray): Textarea border. border 1px solid gray

Here is the code:

_x000D_
_x000D_
input:focus, textarea:focus {_x000D_
    outline: none; /** For Safari, etc **/_x000D_
    border:1px solid gray; /** For Firefox **/_x000D_
}_x000D_
_x000D_
#textarea  {_x000D_
  position:absolute;_x000D_
  top:10px;_x000D_
  left:10px;_x000D_
  right:10px;_x000D_
  width:calc(100% - 20px);_x000D_
  height:160px;_x000D_
  display:inline-block;_x000D_
  margin-top:-0.2em;_x000D_
}
_x000D_
<textarea id="textarea">yo</textarea>
_x000D_
_x000D_
_x000D_

Google reCAPTCHA: How to get user response and validate in the server side?

Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:

 <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
 <span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) {

var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
 if(v.length != 0)
 {
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
 }
}

add column to mysql table if it does not exist

Check if Column Exist or not in PDO (100%)

{
    if(isset($_POST['Add']))
    {
        $ColumnExist = $dbh->prepare("SELECT * FROM ColumnChecker where column_name='$insert_column_name' LIMIT 1");
        $ColumnExist ->execute();
        $ColumnName = $ColumnExist->fetch(2);
        $Display_Column_Name = $ColumnName['column_name'];

        if($Display_Column_Name == $insert_column_name)
        {
            echo "$Display_Column_Name already exist";
        } //*****************************
        else 
        {
            $InsertColumn = $dbh->prepare("insert into ColumnChecker ( column_name ) values ('$insert_column_name')");
            $InsertColumn->execute();

            if($InsertColumn)
            {
                $Add = $dbh->prepare("ALTER TABLE `$Table` ADD `$insert_column_name` $insert_column_type($insert_column_Length) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
                $Add->execute();

                if($Add)
                {
                    echo 'Table has been updated';  
                }
                else 
                {
                    echo 'Sorry! Try again...'; 
                }
            }   
        }
    }
}#Add Column into Table :)

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How do I check out a specific version of a submodule using 'git submodule'?

Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.

$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0

git-status on the parent repository will now report a dirty tree:

# On branch dev [...]
#
#   modified:   submodule (new commits)

Add the submodule directory and commit to store the new pointer.

How can I reorder my divs using only CSS?

Negative top margins can achieve this effect, but they would need to be customized for each page. For instance, this markup...

<div class="product">
<h2>Greatest Product Ever</h2>
<p class="desc">This paragraph appears in the source code directly after the heading and will appear in the search results.</p>
<p class="sidenote">Note: This information appears in HTML after the product description appearing below.</p>
</div>

...and this CSS...

.product { width: 400px; }
.desc { margin-top: 5em; }
.sidenote { margin-top: -7em; }

...would allow you to pull the second paragraph above the first.

Of course, you'll have to manually tweak your CSS for different description lengths so that the intro paragraph jumps up the appropriate amount, but if you have limited control over the other parts and full control over markup and CSS then this might be an option.

How to convert C++ Code to C

A compiler consists of two major blocks: the 'front end' and the 'back end'. The front end of a compiler analyzes the source code and builds some form of a 'intermediary representation' of said source code which is much easier to analyze by a machine algorithm than is the source code (i.e. whereas the source code e.g. C++ is designed to help the human programmer to write code, the intermediary form is designed to help simplify the algorithm that analyzes said intermediary form easier). The back end of a compiler takes the intermediary form and then converts it to a 'target language'.

Now, the target language for general-use compilers are assembler languages for various processors, but there's nothing to prohibit a compiler back end to produce code in some other language, for as long as said target language is (at least) as flexible as a general CPU assembler.

Now, as you can probably imagine, C is definitely as flexible as a CPU's assembler, such that a C++ to C compiler is really no problem to implement from a technical pov.

So you have: C++ ---frontEnd---> someIntermediaryForm ---backEnd---> C

You may want to check these guys out: http://www.edg.com/index.php?location=c_frontend (the above link is just informative for what can be done, they license their front ends for tens of thousands of dollars)

PS As far as i know, there is no such a C++ to C compiler by GNU, and this totally beats me (if i'm right about this). Because the C language is fairly small and it's internal mechanisms are fairly rudimentary, a C compiler requires something like one man-year work (i can tell you this first hand cause i wrote such a compiler myself may years ago, and it produces a [virtual] stack machine intermediary code), and being able to have a maintained, up-to-date C++ compiler while only having to write a C compiler once would be a great thing to have...

How to put a delay on AngularJS instant search?

In Angular 1.3 I would do this:

HTML:

<input ng-model="msg" ng-model-options="{debounce: 1000}">

Controller:

$scope.$watch('variableName', function(nVal, oVal) {
    if (nVal !== oVal) {
        myDebouncedFunction();
    }
});

Basically you're telling angular to run myDebouncedFunction(), when the the msg scope variable changes. The attribute ng-model-options="{debounce: 1000}" makes sure that msg can only update once a second.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!

as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];

you have to pass this two variable from the retrofit.

as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'

I hope it helps you.

Android Studio AVD - Emulator: Process finished with exit code 1

Sometimes things need a system restart (in my case).

How to detect Adblock on my website?

I'm using JavaScript promises and jQuery to detect if the user has an adblocker enabled:

  1. Create a small image and rename it to ads.jpg (or whatever extension).

  2. Create a JavaScript function to call it when you need:

    function hasAdBlocker() {
      return new Promise(function(resolve, reject) {
        let img = $('<img style="display: none;" src="ads.jpg" />');
    
        img.on("load", reject);
        img.on("error", resolve);
    
        $("body").append(img);
      });
    }
    
  3. Call it like this:

    hasAdBlocker().then(function(){
        console.log('Has adBlock')
    }, function() {
        console.log('No adBlock dedected')
    })
    

How to rebuild docker container in docker-compose.yml?

For me it only fetched new dependencies from Docker Hub with both --no-cache and --pull (which are available for docker-compose build.

# other steps before rebuild
docker-compose build --no-cache --pull nginx # rebuild nginx
# other steps after rebuild, e.g. up (see other answers)

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

Cannot start MongoDB as a service

If you receive the error:

the service name is invalid

when running net start mongodb, you will need to run the following command from Step 4 of Manually Create a Windows Service for MongoDB Community Editition:

sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

jQuery remove special characters from string and more

Remove numbers, underscore, white-spaces and special characters from the string sentence.

str.replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');

Demo

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

Arrays in cookies PHP

Just found the thing needed. Now, I can store products visited on cookies and show them later when they get back to the site.

// set the cookies
setcookie("product[cookiethree]", "cookiethree");
setcookie("product[cookietwo]", "cookietwo");
setcookie("product[cookieone]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['product'])) {
    foreach ($_COOKIE['product'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}

How do I make an asynchronous GET request in PHP?

You don't. While PHP offers lots of ways to call a URL, it doesn't offer out of the box support for doing any kind of asynchronous/threaded processing per request/execution cycle. Any method of sending a request for a URL (or a SQL statement, or a etc.) is going to wait for some kind of response. You'll need some kind of secondary system running on the local machine to achieve this (google around for "php job queue")

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

Ignoring upper case and lower case in Java

You ignore case when you treat the data, not when you retrieve/store it. If you want to store everything in lowercase use String#toLowerCase, in uppercase use String#toUpperCase.

Then when you have to actually treat it, you may use out of the bow methods, like String#equalsIgnoreCase(java.lang.String). If nothing exists in the Java API that fulfill your needs, then you'll have to write your own logic.

Start/Stop and Restart Jenkins service on Windows

To start Jenkins from command line

  1. Open command prompt
  2. Go to the directory where your war file is placed and run the following command:

    java -jar jenkins.war

To stop

Ctrl + C

What is the use of System.in.read()?

It allows you to read from the standard input (mainly, the console). This SO question may helps you.

Regular expression for extracting tag attributes

This works for me. It also take into consideration some end cases I have encountered.

I am using this Regex for XML parser

(?<=\s)[^><:\s]*=*(?=[>,\s])

How to Consolidate Data from Multiple Excel Columns All into One Column

Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.

Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.

Press Alt+F11 to open the VBE

Press Control+R to view the Project Explorer

Navigate to the project for your workbook and choose Insert - Module

Paste this code in the code pane

Sub MakeOneColumn()

    Dim vaCells As Variant
    Dim vOutput() As Variant
    Dim i As Long, j As Long
    Dim lRow As Long

    If TypeName(Selection) = "Range" Then
        If Selection.Count > 1 Then
            If Selection.Count <= Selection.Parent.Rows.Count Then
                vaCells = Selection.Value

                ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)

                For j = LBound(vaCells, 2) To UBound(vaCells, 2)
                    For i = LBound(vaCells, 1) To UBound(vaCells, 1)
                        If Len(vaCells(i, j)) > 0 Then
                            lRow = lRow + 1
                            vOutput(lRow, 1) = vaCells(i, j)
                        End If
                    Next i
                Next j

                Selection.ClearContents
                Selection.Cells(1).Resize(lRow).Value = vOutput
            End If
        End If
    End If

End Sub

Press F5 to run the code

How to convert a SVG to a PNG with ImageMagick?

For simple SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all SVG files in your directory.

pip3 install cairosvg

Open a python shell in the directory which contains your .svg files and run:

import os
import cairosvg

for file in os.listdir('.'):
    name = file.split('.svg')[0]
    cairosvg.svg2png(url=name+'.svg',write_to=name+'.png') 

This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:

$ mv *.png [new directory]

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}