Programs & Examples On #Location

Location is a specific position in physical space, e.g. a point on the surface of the Earth described using latitude and longitude coordinates. This tag should NOT be used for questions related to the position of a virtual element e.g. position of a pixel on a bitmap or position of a layout element on UI (use [position] tag in that cases).

Android Google Maps API V2 Zoom to Current Location

Try this coding:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
        .zoom(17)                   // Sets the zoom
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));       
}

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Get GPS location via a service in Android

Just complementing, I implemented this way and usually worked in my Service class

In my Service

@Override
public void onCreate()
{
    mHandler = new Handler(Looper.getMainLooper());
    mHandler.post(this);
    super.onCreate();
}

@Override
public void onDestroy() 
{
    mHandler.removeCallbacks(this);     
    super.onDestroy();
}

@Override
public void run()
{
    InciarGPSTracker();
}

How do I get the current GPS location programmatically in Android?

Simple Find Write Code in On Location Method

public void onLocationChanged(Location location) {
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }


    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(18));

    PolylineOptions pOptions = new PolylineOptions()
            .width(5)
            .color(Color.GREEN)
            .geodesic(true);
    for (int z = 0; z < routePoints.size(); z++) {
        LatLng point = routePoints.get(z);
        pOptions.add(point);
    }
    line = mMap.addPolyline(pOptions);
    routePoints.add(latLng);
}

Calculating distance between two geographic locations

    private static Double _MilesToKilometers = 1.609344;
    private static Double _MilesToNautical = 0.8684;


    /// <summary>
    /// Calculates the distance between two points of latitude and longitude.
    /// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
    /// </summary>
    /// <param name="coordinate1">First coordinate.</param>
    /// <param name="coordinate2">Second coordinate.</param>
    /// <param name="unitsOfLength">Sets the return value unit of length.</param>
    public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
    {

        double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
        double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
                       Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
                       Math.cos(ToRadian(theta));

        distance = Math.acos(distance);
        distance = ToDegree(distance);
        distance = distance * 60 * 1.1515;

        if (unitsOfLength == UnitsOfLength.Kilometer)
            distance = distance * _MilesToKilometers;
        else if (unitsOfLength == UnitsOfLength.NauticalMiles)
            distance = distance * _MilesToNautical;

        return (distance);

    }

Location Services not working in iOS 8

To ensure that this is backwards compatible with iOS 7, you should check whether the user is running iOS 8 or iOS 7. For example:

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

//In ViewDidLoad
if(IS_OS_8_OR_LATER) {
   [self.locationManager requestAlwaysAuthorization];
}

[self.locationManager startUpdatingLocation];

Insert variable into Header Location PHP

Try using double quotes and keeping the L in location lowercase...

header("location: http://linkhere.com/HERE_I_WANT_THE_VARIABLE");

or for example

header("location: http://linkhere.com/$variable");

No need to concatenate here to insert variables.

How to mock location on device?

If your device is plugged into your computer and your trying to changed send GPS cords Via the Emulator control, it will not work.
This is an EMULATOR control for a reason.
Just set it up to update you on GPS change.

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

    ll = new LocationListener() {        
        public void onLocationChanged(Location location) {  
          // Called when a new location is found by the network location provider.  
            onGPSLocationChanged(location); 
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {       
            bigInfo.setText("Changed "+ status);  
        }

        public void onProviderEnabled(String provider) {
            bigInfo.setText("Enabled "+ provider);
        }

        public void onProviderDisabled(String provider) {
            bigInfo.setText("Disabled "+ provider);
        }
      };

When GPS is updated rewrite the following method to do what you want it to;

public void onGPSLocationChanged(Location location){  
if(location != null){  
    double pLong = location.getLongitude();  
    double pLat = location.getLatitude();  
    textLat.setText(Double.toString(pLat));  
    textLong.setText(Double.toString(pLong));  
    if(autoSave){  
        saveGPS();  
        }
    }
}

Dont forget to put these in the manifest
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_MOCK_LOCATION

Change window location Jquery

I'm writing common function for change window

this code can be used parallel in all type of project

function changewindow(url,userdata){
    $.ajax({
        type: "POST",
        url: url,
        data: userdata,
        dataType: "html",
        success: function(html){                
            $("#bodycontent").html(html);
        },
        error: function(html){
            alert(html);
        }
    });
}

How to get Android GPS location

Here's your problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

Latitude and Longitude are double-values, because they represent the location in degrees.

By casting them to int, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"

Where are include files stored - Ubuntu Linux, GCC

Karl answered your search-path question, but as far as the "source of the files" goes, one thing to be aware of is that if you install the libfoo package and want to do some development with it (i.e., use its headers), you will also need to install libfoo-dev. The standard library header files are already in /usr/include, as you saw.

Note that some libraries with a lot of headers will install them to a subdirectory, e.g., /usr/include/openssl. To include one of those, just provide the path without the /usr/include part, for example:

#include <openssl/aes.h>

Get User's Current Location / Coordinates

import Foundation
import CoreLocation

enum Result<T> {
  case success(T)
  case failure(Error)
}

final class LocationService: NSObject {
    private let manager: CLLocationManager

    init(manager: CLLocationManager = .init()) {
        self.manager = manager
        super.init()
        manager.delegate = self
    }

    var newLocation: ((Result<CLLocation>) -> Void)?
    var didChangeStatus: ((Bool) -> Void)?

    var status: CLAuthorizationStatus {
        return CLLocationManager.authorizationStatus()
    }

    func requestLocationAuthorization() {
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func getLocation() {
        manager.requestLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }

}

 extension LocationService: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        newLocation?(.failure(error))
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
            newLocation?(.success(location))
        }
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined, .restricted, .denied:
            didChangeStatus?(false)
        default:
            didChangeStatus?(true)
        }
    }
}

Needs to write this code in required ViewController.

 //NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription


let locationService = LocationService()

 @IBAction func action_AllowButtonTapped(_ sender: Any) {
     didTapAllow()
 }

 func didTapAllow() {
     locationService.requestLocationAuthorization()
 }

 func getCurrentLocationCoordinates(){
   locationService.newLocation = {result in
     switch result {
      case .success(let location):
      print(location.coordinate.latitude, location.coordinate.longitude)
      case .failure(let error):
      assertionFailure("Error getting the users location \(error)")
   }
  }
}

func getCurrentLocationCoordinates() {
    locationService.newLocation = { result in
        switch result {
        case .success(let location):
            print(location.coordinate.latitude, location.coordinate.longitude)
            CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                    return
                }
                if (placemarks?.count)! > 0 {
                    print("placemarks", placemarks!)
                    let pmark = placemarks?[0]
                    self.displayLocationInfo(pmark)
                } else {
                    print("Problem with the data received from geocoder")
                }
            })
        case .failure(let error):
            assertionFailure("Error getting the users location \(error)")
        }
    }
}

What is the simplest and most robust way to get the user's current location on Android?

From last more than one year, I was using the combination of GPS_PROVIDER and NETWORK_PROVIDER to get the current location and it was working good, but from last few months I'm getting location after a long delay, so I switched to latest API FusedLocationProviderClient and it is working pretty good.

Here is the class which I wrote to get current location by using FusedLocationProviderClient. In below code, I used a timer to wait for while to get the current location, I scheduled timer 15 seconds delay, you can change it according to you.

private static FusedLocationService ourInstance;
private final LocationRequest locationRequest;
private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;
private Context context;
private FindOutLocation findOutLocation;
private boolean callbackTriggered = false;
private Timer timer;

public static FusedLocationService getInstance(Context pContext) {

    if (null == ourInstance) ourInstance = new FusedLocationService(pContext);

    return ourInstance;
}

private FusedLocationService(Context pContext) {
    context = pContext;
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    locationRequest = getLocationRequest();
    requestLocation(context);
}

public Location getLastKnownLocation() {
    return mLastLocation;
}

private void requestLocation(Context context) {

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null);
    mFusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
        if (location != null) {
            mLastLocation = location;
            triggerCallback(mLastLocation);
        }
    });
}

private LocationRequest getLocationRequest() {
    LocationRequest locationRequest = new LocationRequest();
    long INTERVAL = 10 * 1000;
    long FASTEST_INTERVAL = 5 * 1000;
    locationRequest.setInterval(INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    return locationRequest;
}

private LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for (Location location : locationResult.getLocations()) {
            if (location != null) mLastLocation = location;
        }
        if (null != mLastLocation) triggerCallback(mLastLocation);
    }
};

public static abstract class FindOutLocation {
    public abstract void gotLocation(Location location);
}

@SuppressLint("MissingPermission")
public void findLocation(FindOutLocation findOutLocation) {
    long TIMER_TIME_OUT = 15 * 1000;
    this.findOutLocation = findOutLocation;
    callbackTriggered = false;

    try {
        requestLocation(context);
        timer = new Timer();
        timer.schedule(new GetLastLocation(context), TIMER_TIME_OUT);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private class GetLastLocation extends TimerTask {
    Context context;

    GetLastLocation(Context context) {
        this.context = context;
    }

    @Override
    public void run() {
        triggerCallback(mLastLocation);
    }
}

private void triggerCallback(Location location) {
    if (null != location) mLastLocation = location;
    if (!callbackTriggered && null != findOutLocation) {
        callbackTriggered = true;
        removeLocationUpdates();
        findOutLocation.gotLocation(location);
        findOutLocation = null;
    }
}

private void removeLocationUpdates() {
    if (null != timer) timer.cancel();
    if (null != mFusedLocationClient)
        mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}

And called this from activity, here is the code

    FusedLocationService.FindOutLocation findOutLocation = new FusedLocationService.FindOutLocation() {
        @Override
        public void gotLocation(Location currentLocation) {
            if (currentLocation != null) {
                /*TODO DO SOMETHING WITH CURRENT LOCATION*/
            }
        }
    };
    FusedLocationService.getInstance(this).findLocation(findOutLocation);

Add following entries in the AndroidManifest.xml

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

<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />

Difference between window.location.href, window.location.replace and window.location.assign

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

just remove s from the permission you are using sss you have to use ss

Fastest Way to Find Distance Between Two Lat/Long Points

The full code with details about how to install as MySQL plugin are here: https://github.com/lucasepe/lib_mysqludf_haversine

I posted this last year as comment. Since kindly @TylerCollier suggested me to post as answer, here it is.

Another way is to write a custom UDF function that returns the haversine distance from two points. This function can take in input:

lat1 (real), lng1 (real), lat2 (real), lng2 (real), type (string - optinal - 'km', 'ft', 'mi')

So we can write something like this:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2) < 40;

to fetch all records with a distance less then 40 kilometers. Or:

SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2, 'ft') < 25;

to fetch all records with a distance less then 25 feet.

The core function is:

double
haversine_distance( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error ) {
    double result = *(double*) initid->ptr;
    /*Earth Radius in Kilometers.*/ 
    double R = 6372.797560856;
    double DEG_TO_RAD = M_PI/180.0;
    double RAD_TO_DEG = 180.0/M_PI;
    double lat1 = *(double*) args->args[0];
    double lon1 = *(double*) args->args[1];
    double lat2 = *(double*) args->args[2];
    double lon2 = *(double*) args->args[3];
    double dlon = (lon2 - lon1) * DEG_TO_RAD;
    double dlat = (lat2 - lat1) * DEG_TO_RAD;
    double a = pow(sin(dlat * 0.5),2) + 
        cos(lat1*DEG_TO_RAD) * cos(lat2*DEG_TO_RAD) * pow(sin(dlon * 0.5),2);
    double c = 2.0 * atan2(sqrt(a), sqrt(1-a));
    result = ( R * c );
    /*
     * If we have a 5th distance type argument...
     */
    if (args->arg_count == 5) {
        str_to_lowercase(args->args[4]);
        if (strcmp(args->args[4], "ft") == 0) result *= 3280.8399;
        if (strcmp(args->args[4], "mi") == 0) result *= 0.621371192;
    }

    return result;
}

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

How do I get the full path to a Perl script that is executing?

On *nix, you likely have the "whereis" command, which searches your $PATH looking for a binary with a given name. If $0 doesn't contain the full path name, running whereis $scriptname and saving the result into a variable should tell you where the script is located.

Nginx serves .php files as downloads, instead of executing them

check your nginx config file extension is *.conf.
for example: /etc/nginx/conf.d/myfoo.conf

I got the same situation. After I rename the my config file from myfoo to myfoo.conf, it fixed. Do not forget to restart nginx after rename it.

jquery: change the URL address without redirecting?

You cannot really change the whole URL in the location bar without redirecting (think of the security issues!).

However you can change the hash part (whats after the #) and read that: location.hash

ps. prevent the default onclick redirect of a link by something like:

$("#link").bind("click",function(e){
  doRedirectFunction();
  e.preventDefault();
})

location.host vs location.hostname and cross-browser compatibility?

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

What you really want is this:

/(^|\.)domain\.com$/

Calculate compass bearing / heading to location in Android

@Damian - The idea is very good and I agree with answer, but when I used your code I had wrong values, so I wrote this on my own (somebody told the same in your comments). Counting heading with the declination is good, I think, but later I used something like that:

heading = (bearing - heading) * -1;

instead of Damian's code:

heading = myBearing - (myBearing + heading); 

and changing -180 to 180 for 0 to 360:

      private float normalizeDegree(float value){
          if(value >= 0.0f && value <= 180.0f){
              return value;
          }else{
              return 180 + (180 + value);
          }

and then when you want to rotate your arrow you can use code like this:

      private void rotateArrow(float angle){

            Matrix matrix = new Matrix();
            arrowView.setScaleType(ScaleType.MATRIX);
            matrix.postRotate(angle, 100f, 100f);
            arrowView.setImageMatrix(matrix);
      }

where arrowView is ImageView with arrow picture and 100f parameters in postRotate is pivX and pivY).

I hope I will help somebody.

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

Where does npm install packages?

Windows 7, 8 and 10 - %USERPROFILE%\AppData\Roaming\npm\node_modules.

Note : If you are somewhere in folder type cd .. until you are in C: directory. Then, type cd %USERPROFILE%\AppData\Roaming\npm\node_modules. And, magically %USERPROFILE% will change into Users\YourUserProfile\. I just wanted to clarify on ideas referred by Decko in first response. npm list -g will list all the bits you got globally installed. If you need to find your project related npm package then cd 'your angular project xyz', then run npm list. It will show list of modules in npm package. It will also give you list of dependencies missing, and you may require to effectively run that project.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

As biziclop mentioned, some sort of metric space tree would probably be your best option. I have experience using kd-trees and quad trees to do these sorts of range queries and they're amazingly fast; they're also not that hard to write. I'd suggest looking into one of these structures, as they also let you answer other interesting questions like "what's the closest point in my data set to this other point?"

Redirect using AngularJS

With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.

Try doing this on the directive scope.$apply(function() { $location.path("/route"); });

window.location.href and window.open () methods in JavaScript

There are already answers which describes about window.location.href property and window.open() method.

I will go by Objective use:

1. To redirect the page to another

Use window.location.href. Set href property to the href of another page.

2. Open link in the new or specific window.

Use window.open(). Pass parameters as per your goal.

3. Know current address of the page

Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.

See Location Object for more information.

PHP header(Location: ...): Force URL change in address bar

Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem

Also yes always add whitespace like @Peter O suggested.

Python + Django page redirect

With Django version 1.3, the class based approach is:

from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)

This example lives in in urls.py

How to check if Location Services are enabled?

To get current Geo location in android google maps,you should turn on your device location option.To check whether the location is on or not,you can simple call this method from your onCreate() method.

private void checkGPSStatus() {
    LocationManager locationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    if ( locationManager == null ) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    try {
        gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex){}
    try {
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex){}
    if ( !gps_enabled && !network_enabled ){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this);
        dialog.setMessage("GPS not enabled");
        dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //this will navigate user to the device location settings screen
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        AlertDialog alert = dialog.create();
        alert.show();
    }
}

how to change any data type into a string in python

With str(x). However, every data type can define its own string conversion, so this might not be what you want.

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

Static vs class functions/variables in Swift classes?

I got this confusion in one of my project as well and found this post, very helpful. Tried the same in my playground and here is the summary. Hope this helps someone with stored properties and functions of type static, final,class, overriding class vars etc.

class Simple {

    init() {print("init method called in base")}

    class func one() {print("class - one()")}

    class func two() {print("class - two()")}

    static func staticOne() {print("staticOne()")}

    static func staticTwo() {print("staticTwo()")}

    final func yesFinal() {print("yesFinal()")}

    static var myStaticVar = "static var in base"

    //Class stored properties not yet supported in classes; did you mean 'static'?
    class var myClassVar1 = "class var1"

    //This works fine
    class var myClassVar: String {
       return "class var in base"
    }
}

class SubSimple: Simple {
    //Successful override
    override class func one() {
        print("subClass - one()")
    }
    //Successful override
    override class func two () {
        print("subClass - two()")
    }

    //Error: Class method overrides a 'final' class method
    override static func staticOne() {

    }

    //error: Instance method overrides a 'final' instance method
    override final func yesFinal() {

    }

    //Works fine
    override class var myClassVar: String {
        return "class var in subclass"
    }
}

And here is the testing samples:

print(Simple.one())
print(Simple.two())
print(Simple.staticOne())
print(Simple.staticTwo())
print(Simple.yesFinal(Simple()))
print(SubSimple.one())
print(Simple.myStaticVar)
print(Simple.myClassVar)
print(SubSimple.myClassVar)

//Output
class - one()
class - two()
staticOne()
staticTwo()
init method called in base
(Function)
subClass - one()
static var in base
class var in base
class var in subclass

Initialize static variables in C++ class?

Since C++11 it can be done inside a class with constexpr.

class stat {
    public:
        // init inside class
        static constexpr double inlineStaticVar = 22;
};

The variable can now be accessed with:

stat::inlineStaticVar

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

How much data can a List can hold at the maximum?

How much data can be added in java.util.List in Java at the maximum?

This is very similar to Theoretical limit for number of keys (objects) that can be stored in a HashMap?

The documentation of java.util.List does not explicitly documented any limit on the maximum number of elements. The documentation of List.toArray however, states that ...

Return an array containing all of the elements in this list in proper sequence (from first to last element); would have trouble implementing certain methods faithfully, such as

... so strictly speaking it would not be possible to faithfully implement this method if the list had more than 231-1 = 2147483647 elements since that is the largest possible array.

Some will argue that the documentation of size()...

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

...indicates that there is no upper limit, but this view leads to numerous inconsistencies. See this bug report.

Is there any default size an array list?

If you're referring to ArrayList then I'd say that the default size is 0. The default capacity however (the number of elements you can insert, without forcing the list to reallocate memory) is 10. See the documentation of the default constructor.

The size limit of ArrayList is Integer.MAX_VALUE since it's backed by an ordinary array.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

What does the "assert" keyword do?

assert is a debugging tool that will cause the program to throw an AssertionFailed exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false. Generally speaking, assert should not be used in production code

What's the difference between `raw_input()` and `input()` in Python 3?

If You want to ensure, that your code is running with python2 and python3, use function input () in your script and add this to begin of your script:

from sys import version_info
if version_info.major == 3:
    pass
elif version_info.major == 2:
    try:
        input = raw_input
    except NameError:
        pass
else:
    print ("Unknown python version - input function not safe")

ImageView - have height match width?

In Android 26.0.0 PercentRelativeLayout has been deprecated.

The best way to solve it is now with ConstraintLayout like this:

<android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

    <ImageView android:layout_width="match_parent"
               android:layout_height="0dp"
               android:scaleType="centerCrop"
               android:src="@drawable/you_image"                       
               app:layout_constraintDimensionRatio="1:1"/>


</android.support.constraint.ConstraintLayout>


Here is a tutorial on how to add ConstraintLayout to your project.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

I did apt-get install python3-dev in my Ubuntu and added setup_requires=["wheel"] in setup.py

How to add a color overlay to a background image?

I see 2 easy options:

  • multiple background with a translucent single gradient over image
  • huge inset shadow

gradient option:

html {
  min-height:100%;
  background:linear-gradient(0deg, rgba(255, 0, 150, 0.3), rgba(255, 0, 150, 0.3)), url(http://lorempixel.com/800/600/nature/2);
  background-size:cover;
}

shadow option:

html {
  min-height:100%;
  background:url(http://lorempixel.com/800/600/nature/2);
  background-size:cover;
  box-shadow:inset 0 0 0 2000px rgba(255, 0, 150, 0.3);
}

an old codepen of mine with few examples


a third option

  • with background-blen-mode :

    The background-blend-mode CSS property sets how an element's background images should blend with each other and with the element's background color.

html {
  min-height:100%;
  background:url(http://lorempixel.com/800/600/nature/2) rgba(255, 0, 150, 0.3);
  background-size:cover;
  background-blend-mode: multiply;
}

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

Set the display.max_colwidth option to None (or -1 before version 1.0):

pd.set_option('display.max_colwidth', None)

set_option docs

For example, in iPython, we see that the information is truncated to 50 characters. Anything in excess is ellipsized:

Truncated result

If you set the display.max_colwidth option, the information will be displayed fully:

Non-truncated result

Spring JPA @Query with LIKE

Try to use the following approach (it works for me):

@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List<String> findUsersWithPartOfName(@Param("username") String username);

Notice: The table name in JPQL must start with a capital letter.

Jackson enum Serializing and DeSerializer

In my case, this is what resolved:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PeriodEnum {

    DAILY(1),
    WEEKLY(2),
    ;

    private final int id;

    PeriodEnum(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return this.name();
    }

    @JsonCreator
    public static PeriodEnum fromJson(@JsonProperty("name") String name) {
        return valueOf(name);
    }
}

Serializes and deserializes the following json:

{
  "id": 2,
  "name": "WEEKLY"
}

I hope it helps!

Is there a way to access the "previous row" value in a SELECT statement?

LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".

Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row. Reading it again you just want that rows culled, so you should an inner join rather than a left join.


Update:

Newer versions of Sql Server also have the LAG and LEAD Windowing functions that can be used for this, too.

SQL Server: Best way to concatenate multiple columns?

Blockquote

Using concatenation in Oracle SQL is very easy and interesting. But don't know much about MS-SQL.

Blockquote

Here we go for Oracle : Syntax: SQL> select First_name||Last_Name as Employee from employees;

Result: EMPLOYEE

EllenAbel SundarAnde MozheAtkinson

Here AS: keyword used as alias. We can concatenate with NULL values. e.g. : columnm1||Null

Suppose any of your columns contains a NULL value then the result will show only the value of that column which has value.

You can also use literal character string in concatenation.

e.g. select column1||' is a '||column2 from tableName; Result: column1 is a column2. in between literal should be encolsed in single quotation. you cna exclude numbers.

NOTE: This is only for oracle server//SQL.

Popup Message boxes

JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);

btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it

Trying to Validate URL Using JavaScript

Here's a regular expression which might fit the bill (it's very long):

/^(?:\u0066\u0069\u006C\u0065\u003A\u002F{2}(?:\u002F{2}(?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*\u0040)?(?:\u005B(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){6}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){5}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){4}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A)?[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){3}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,3}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,4}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,5}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,6}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2})\u005D|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?\u002E)+[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?))(?:\u003A(?:\u0030-\u0035\u0030-\u0039{0,4}|\u0036\u0030-\u0034\u0030-\u0039{3}|\u0036\u0035\u0030-\u0034\u0030-\u0039{2}|\u0036\u0035\u0035\u0030-\u0032\u0030-\u0039|\u0036\u0035\u0035\u0033\u0030-\u0035))?(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*|\u002F(?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])+(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*)?|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])+(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*)|[\u0041-\u005A\u0061-\u007A][\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002B\u002D\u002E]*\u003A(?:\u002F{2}(?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*\u0040)?(?:\u005B(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){6}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){5}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){4}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A)?[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){3}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,3}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,4}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035]))|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,5}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}|(?:(?:[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4}\u003A){0,6}[\u0030-\u0039\u0041-\u0046\u0061-\u0066]{1,4})?\u003A{2})\u005D|(?:(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])\u002E){3}(?:[\u0030-\u0039]|[\u0031-\u0039][\u0030-\u0039]|\u0031[\u0030-\u0039]{2}|\u0032[\u0030-\u0034][\u0030-\u0039]|\u0032\u0035[\u0030-\u0035])|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?\u002E)+[\u0041-\u005A\u0061-\u007A\u0030-\u0039](?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D]+)?[\u0041-\u005A\u0061-\u007A\u0030-\u0039])?))(?:\u003A(?:\u0030-\u0035\u0030-\u0039{0,4}|\u0036\u0030-\u0034\u0030-\u0039{3}|\u0036\u0035\u0030-\u0034\u0030-\u0039{2}|\u0036\u0035\u0035\u0030-\u0032\u0030-\u0039|\u0036\u0035\u0035\u0033\u0030-\u0035))?(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*|\u002F(?:(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])+(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*)?|(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])+(?:\u002F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)*)(?:\u003F(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040\u002F\u003F]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)?(?:\u0023(?:[\u0041-\u005A\u0061-\u007A\u0030-\u0039\u002D\u002E\u005F\u007E\u0021\u0024\u0026\u0027\u0028\u0029\u002A\u002B\u002C\u003B\u003D\u003A\u0040\u002F\u003F]|\u0025[\u0030-\u0039\u0041-\u0046\u0061-\u0066][\u0030-\u0039\u0041-\u0046\u0061-\u0066])*)?)$/

There are some caveats to its usage, namely it does not validate URIs which contain additional information after the user name (e.g. "username:password"). Also, only IPv6 addresses can be contained within the IP literal syntax and the "IPvFuture" syntax is currently ignored and will not validate against this regular expression. Port numbers are also constrained to be between 0 and 65,535. Also, only the file scheme can use triple slashes (e.g. "file:///etc/sysconfig") and can ignore both the query and fragment parts of a URI. Finally, it is geared towards regular URIs and not IRIs, hence the extensive focus on the ASCII character set.

This regular expression could be expanded upon, but it's already complex and long enough as it is. I also cannot guarantee it's going to be "100% accurate" or "bug free", but it should correctly validate URIs for all schemes.

You will need to do additional verification for any scheme-specific requirements or do URI normalization as this regular expression will validate a very broad range of URIs.

Inverse of matrix in R

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

How can I add private key to the distribution certificate?

With Xcode 9 the interface has been updated and now the way I did to resolve the problem was this:

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view
  4. Click the gear icon () in the lower-left.

enter image description here

  1. Export Apple Id and Code Signing Assets
  2. After entering a filename in the Save As field and a password in both the Password and Verify fields you'll see a Window like this

enter image description here

  1. Click the gear icon () -> Click Import -> Select the file you exported in step 6

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

Rotating a two-dimensional array in Python

def ruota_orario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento)[::-1] for elemento in ruota][::-1]

Hashmap does not work with int, char

Generic Collection classes cant be used with primitives. Use the Character and Integer wrapper classes instead.

Map<Character , Integer > checkSum = new HashMap<Character, Integer>();

Retrieve last 100 lines logs

You can use tail command as follows:

tail -100 <log file>   > newLogfile

Now last 100 lines will be present in newLogfile

EDIT:

More recent versions of tail as mentioned by twalberg use command:

tail -n 100 <log file>   > newLogfile

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

How to check cordova android version of a cordova/phonegap project?

Try

cordova platform version

It will give you the following output

Installed platforms: android 3.5.1, ios 3.5.0
Available platforms: amazon-fireos, blackberry10, browser, firefoxos

Also to know the version of cordodva cli try

cordova -v 

how to append a css class to an element by javascript?

addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));

This will add ONE class or MULTIPLE classes :

addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"

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

you could also go to Hardware -> reboot, then Hardware -> Home, and click on your App

Where to find extensions installed folder for Google Chrome on Mac?

The default locations of Chrome's profile directory are defined at http://www.chromium.org/user-experience/user-data-directory. For Chrome on Mac, it's

~/Library/Application\ Support/Google/Chrome/Default

The actual location can be different, by setting the --user-data-dir=path/to/directory flag.
If only one user is registered in Chrome, look in the Default/Extensions subdirectory. Otherwise, look in the <profile user name>/Extensions directory.

If that didn't help, you can always do a custom search.

  1. Go to chrome://extensions/, and find out the ID of an extension (32 lowercase letters) (if not done already, activate "Developer mode" first).

  2. Open the terminal, cd to the directory which is most likely a parent of your Chrome profile (if unsure, try ~ then /).

  3. Run find . -type d -iname "<EXTENSION ID HERE>", for example:

    find . -type d -iname jifpbeccnghkjeaalbbjmodiffmgedin
    

    Result:

    ./Library/Application Support/Google/Chrome/Default/Extensions/jifpbeccnghkjeaalbbjmodiffmgedin

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Material effect on button with background color

The @ianhanniballake's answer is absolutely correct and simple. But it took me few days to understand. For someone who don't understand his answer, here is more detail implementation

<Button
        android:id="@+id/btn"
        style="@style/MaterialButton"
        ... />


<style name="MaterialButton" parent="Widget.AppCompat.Button.Colored">
    <item name="android:theme">@style/Theme.MaterialButton</item>
   ...
</style>


<style name="Theme.MaterialButton" parent="YourTheme">
    <item name="colorAccent">@color/yourAccentColor</item>
    <item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>

===Or===

<Button
        android:id="@+id/btn"
        style="@style/Widget.AppCompat.Button.Colored"
        android:theme="@style/Theme.MaterialButton" />

<style name="Theme.MaterialButton" parent="YourTheme">
    <item name="colorAccent">@color/yourAccentColor</item>
    <item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>

Using different Web.config in development and production environment

I use a NAnt Build Script to deploy to my different environments. I have it modify my config files via XPath depending on where they're being deployed to, and then it automagically puts them into that environment using Beyond Compare.

Takes a minute or two to setup, but you only need to do it once. Then batch files take over while I go get another cup of coffee. :)

Here's an article I found on it.

Find and Replace Inside a Text File from a Bash Command

The easiest way is to use sed (or perl):

sed -i -e 's/abc/XYZ/g' /tmp/file.txt

Which will invoke sed to do an in-place edit due to the -i option. This can be called from bash.

If you really really want to use just bash, then the following can work:

while read a; do
    echo ${a//abc/XYZ}
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}

This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name.

For Mac users:

sed -i '' 's/abc/XYZ/g' /tmp/file.txt (See the comment below why)

CSS table layout: why does table-row not accept a margin?

Have you tried setting the bottom margin to .row div, i.e. to your "cells"? When you work with actual HTML tables, you cannot set margins to rows, too - only to cells.

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

How to check whether a string is Base64 encoded or not

As of Java 8, you can simply use java.util.Base64 to try and decode the string:

String someString = "...";
Base64.Decoder decoder = Base64.getDecoder();

try {
    decoder.decode(someString);
} catch(IllegalArgumentException iae) {
    // That string wasn't valid.
}

Windows 7 - Add Path

In answer to the OP:

The PATH environment variable specifies which folders Windows will search in, in order to find such files as executable programs or DLLs. To make your Windows installation find your program, you specify the folder that the program resides in, NOT the program file itself!

So, if you want Windows to look for executables (or other desired files) in the folder:

C:\PHP

because, for example, you want to install PHP manually, and choose that folder into which to install PHP, then you add the entry:

C:\PHP

to your PATH environment variable, NOT an entry such as "C:\PHP\php.exe".

Once you've added the folder entry to your PATH environment variable, Windows will search that folder, and will execute ANY named executable file you specify, if that file happens to reside in that folder, just the same as with all the other existing PATH entries.

Before editing your PATH variable, though, protect yourself against foul ups in advance. Copy the existing value of the PATH variable to a Notepad file, and save it as a backup. If you make a mistake editing PATH, you can simply revert to the previous version with ease if you take this step.

Once you've done that, append your desired path entries to the text (again, I suggest you do this in Notepad so you can see what you're doing - the Windows 7 text box is a pain to read if you have even slight vision impairment), then paste that text into the Windows text box, and click OK.

Your PATH environment variable is a text string, consisting of a list of folder paths, each entry separated by semicolons. An example has already been given by someone else above, such as:

C:\Program Files; C:\Winnt; C:\Winnt\System32

Your exact version may vary depending upon your system.

So, to add "C:\PHP" to the above, you change it to read as follows:

C:\Program Files; C:\Winnt; C:\Winnt\System32; C:\PHP

Then you copy & paste that text into the windows dialogue box, click OK, and you should now have a new PATH variable, ready to roll. If your changes don't take effect immediately, you can always restart the computer.

Spring Boot + JPA : Column name annotation ignored

By default Spring uses org.springframework.boot.orm.jpa.SpringNamingStrategy to generate table names. This is a very thin extension of org.hibernate.cfg.ImprovedNamingStrategy. The tableName method in that class is passed a source String value but it is unaware if it comes from a @Column.name attribute or if it has been implicitly generated from the field name.

The ImprovedNamingStrategy will convert CamelCase to SNAKE_CASE where as the EJB3NamingStrategy just uses the table name unchanged.

If you don't want to change the naming strategy you could always just specify your column name in lowercase:

@Column(name="testname")

Why are exclamation marks used in Ruby methods?

From themomorohoax.com:

A bang can used in the below ways, in order of my personal preference.

1) An active record method raises an error if the method does not do what it says it will.

2) An active record method saves the record or a method saves an object (e.g. strip!)

3) A method does something “extra”, like posts to someplace, or does some action.

The point is: only use a bang when you’ve really thought about whether it’s necessary, to save other developers the annoyance of having to check why you are using a bang.

The bang provides two cues to other developers.

1) that it’s not necessary to save the object after calling the method.

2) when you call the method, the db is going to be changed.

http://www.themomorohoax.com/2009/02/11/when-to-use-a-bang-exclamation-point-after-rails-methods

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.

Checking the following section in DatabaseInterface.class.php,

        define(
            'PMA_MYSQL_INT_VERSION',
            PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
        );

I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start and stop.

# restart the service
systemd restart php-fpm

# start and stop the service
systemd stop php-fpm
systemd start php-fpm

Doing a stop followed by a start fixed the issue for me.

Howto? Parameters and LIKE statement SQL

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)

File path issues in R using Windows ("Hex digits in character string" error)

My Solution is to define an RStudio snippet as follows:

snippet pp
    "`r gsub("\\\\", "\\\\\\\\\\\\\\\\", readClipboard())`"

This snippet converts backslashes \ into double backslashes \\. The following version will work if you prefer to convert backslahes to forward slashes /.

snippet pp
    "`r gsub("\\\\", "/", readClipboard())`"

Once your preferred snippet is defined, paste a path from the clipboard by typing p-p-TAB-ENTER (that is pp and then the tab key and then enter) and the path will be magically inserted with R friendly delimiters.

How to duplicate a whole line in Vim?

I know I'm late to the party, but whatever; I have this in my .vimrc:

nnoremap <C-d> :copy .<CR>
vnoremap <C-d> :copy '><CR>

the :copy command just copies the selected line or the range (always whole lines) to below the line number given as its argument.

In normal mode what this does is copy . copy this line to just below this line.

And in visual mode it turns into '<,'> copy '> copy from start of selection to end of selection to the line below end of selection.

In Swift how to call method with parameters on GCD main thread?

Here's a nice little global function you can add for a nicer syntax:

func dispatch_on_main(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

And usage

dispatch_on_main {
    // Do some UI stuff
}

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

How can I pipe stderr, and not stdout?

This will redirect command1 stderr to command2 stdin, while leaving command1 stdout as is.

exec 3>&1
command1 2>&1 >&3 3>&- | command2 3>&-
exec 3>&-

Taken from LDP

less than 10 add 0 to number

if(myNumber.toString().length < 2)
   myNumber= "0"+myNumber;

or:

return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

Capturing mobile phone traffic on Wireshark

Preconditions: adb and wireshark is installed on your computer and you have a rooted android device.

  1. Download tcpdump to ~/Downloads
  2. adb push ~/Downloads/tcpdump /sdcard/
  3. adb shell
  4. su root
  5. mv /sdcard/tcpdump /data/local/
  6. cd /data/local/
  7. chmod +x tcpdump
  8. ./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
  9. CTRL+C after you've captured enough packets.
  10. exit
  11. exit
  12. adb pull /sdcard/dump.pcap ~/Downloads/

Now you can open the pcap file using Wireshark.

Interface or an Abstract Class: which one to use?

Just to throw this into the mix, but as Cletus mentioned using an interface in conjunction with an abstract class, I often use the interface to clarify my design thinking.

For instance:

<?php
class parser implements parserDecoratorPattern {
    //...
}

That way, anyone reading my code (and who knows what a Decorator Pattern is) will know right away a) how I build my parser and b) be able to see what methods are used to implement the decorator pattern.

Also, and I may be off base here not being a Java/C++/etc programmer, but data types can come into play here. Your objects are of a type, and when you pass them around the type matters programmatically. Moving your contractable items into the interface only dictates the types that the methods return, but not the base type of the class that implements it.

It's late and I can't think of a better psudo-code example, but here goes:

<?php
interface TelevisionControls {};
class Remote implements TelevisionControls {};
class Spouse implements TelevisionControls {};
Spouse spouse = new Spouse();
Remote remote = new Remote();
isSameType = (bool)(remote == spouse)

How to convert a char to a String?

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

Printing column separated by comma using Awk command line

A simple, although -less solution in :

while IFS=, read -r a a a b; do echo "$a"; done <inputfile

It works faster for small files (<100 lines) then as it uses less resources (avoids calling the expensive fork and execve system calls).

EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):

To put to rest the myth that shell will run faster than awk for small files:

$ wc -l file
99 file

$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

$ time awk -F, '{print $3}' file >/dev/null

real    0m0.016s
user    0m0.000s
sys     0m0.015s

I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?

And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:

$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file

$

Apache giving 403 forbidden errors

In my case it was failing as the IP of my source server was not whitelisted in the target server.

For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig

This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.

Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)

Find the config file for the target application for e.g. prodcat-443.conf

RewriteCond %{REMOTE_ADDR} <YOUR Server's IP> 
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98

Hope this helps someone

NavigationBar bar, tint, and title text color in iOS 8

For custom color to TitleText at NavigationBar, here a simple and short code for Swift 3:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]

or

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName :UIColor.white]

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");

alert(dateToString(date));

You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [
    "January",
    "February",
    "March",
    ...
  ];

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",
    ...
  };

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;
}

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;

alert(date.toString());

Faster way to zero memory than with memset?

Nowadays your compiler should do all the work for you. At least of what I know gcc is very efficient in optimizing calls to memset away (better check the assembler, though).

Then also, avoid memset if you don't have to:

  • use calloc for heap memory
  • use proper initialization (... = { 0 }) for stack memory

And for really large chunks use mmap if you have it. This just gets zero initialized memory from the system "for free".

Change route params without reloading in Angular 2

As of RC6 you can do the following to change URL without change state and thereby keeping your route history

    import {OnInit} from '@angular/core';

    import {Location} from '@angular/common'; 
    // If you dont import this angular will import the wrong "Location"

    @Component({
        selector: 'example-component',
        templateUrl: 'xxx.html'
    })
    export class ExampleComponent implements OnInit {
        
        constructor( private location: Location )
        {}

        ngOnInit() {    
            this.location.replaceState("/some/newstate/");
        }
    }

How can I convert string to datetime with format specification in JavaScript?

You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.

Reference:

1. moment library: https://momentjs.com/

2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript

convertDate(date) {
        var momentDate = moment(date).format('hh : mm A');
        return momentDate;
}

and you can call this method like:

this.convertDate('2020-05-01T10:31:18.837Z');

I hope it helps. Enjoy coding.

Open a facebook link by native Facebook app on iOS

If the Facebook application is logged in, the page will be opened when executing the following code. If the Facebook application is not logged in when executing the code, the user will then be redirected to the Facebook app to login and then after connecting the Facebook is not redirected to the page!

NSURL *fbNativeAppURL = [NSURL URLWithString:@"fb://page/yourPageIDHere"] [[UIApplication sharedApplication] openURL:fbNativeAppURL]

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

At least one item in your list is either not three dimensional, or its second or third dimension does not match the other elements. If only the first dimension does not match, the arrays are still matched, but as individual objects, no attempt is made to reconcile them into a new (four dimensional) array. Some examples are below:

That is, the offending element's shape != (?, 224, 3),
or ndim != 3 (with the ? being non-negative integer).
That is what is giving you the error.

You'll need to fix that, to be able to turn your list into a four (or three) dimensional array. Without context, it is impossible to say if you want to lose a dimension from the 3D items or add one to the 2D items (in the first case), or change the second or third dimension (in the second case).


Here's an example of the error:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224))]
>>> np.array(a)
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

or, different type of input, but the same error:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224,13))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

Alternatively, similar but with a different error message:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,100,3))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224)

But the following will work, albeit with different results than (presumably) intended:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((10,224,3))]
>>> np.array(a)
# long output omitted
>>> newa = np.array(a)
>>> newa.shape
3  # oops
>>> newa.dtype
dtype('O')
>>> newa[0].shape
(224, 224, 3)
>>> newa[1].shape
(224, 224, 3)
>>> newa[2].shape
(10, 224, 3)
>>> 

Disable submit button ONLY after submit

I put this in my global code to work on all submit buttons:

$("input[type='submit']").on("click", function (e) {
    $(this).attr("disabled", true);
    $(this).closest("form").submit()
});

How to install and run phpize

Hmm... actually i dont know how this solved it? But the following steps solved it for me:

find / -name 'config.m4'

Now look if the config.m4 is anywhere in a folder of that stuff you want to phpize. Go to that folder and run phpize directly in there.

How to test valid UUID/GUID?

All type-specific regexes posted so far are failing on the "type 0" Nil UUID, defined in 4.1.7 of the RFC as:

The nil UUID is special form of UUID that is specified to have all 128 bits set to zero: 00000000-0000-0000-0000-000000000000

To modify Wolf's answer:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

Or, to properly exclude a "type 0" without all zeros, we have the following (thanks to Luke):

/^(?:[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a??-f]{3}-?[0-9a-f]{12}??|00000000-0000-0000-??0000-000000000000)$/??i

Changing the default icon in a Windows Forms application

On the solution explorer, right click on the project title and select the 'Properties' on the context menu to open the 'Project Property' form. In the 'Application' tab, on the 'Resources' group box there is a entry field where you can select the icon file you want for your application.

Get the height and width of the browser viewport without scrollbars using jquery?

$(window).height();
$(window).width();

More info

Using jQuery is not essential for getting those values, however. Use

document.documentElement.clientHeight;
document.documentElement.clientWidth;

to get sizes excluding scrollbars, or

window.innerHeight;
window.innerWidth;

to get the whole viewport, including scrollbars.

document.documentElement.clientHeight <= window.innerHeight;  // is always true

What is the difference between a JavaBean and a POJO?

All JavaBeans are POJOs but not all POJOs are JavaBeans.

A JavaBean is a Java object that satisfies certain programming conventions:

  • the JavaBean class must implement either Serializable or Externalizable;
  • the JavaBean class must have a public no-arg constructor;
  • all JavaBean properties must have public setter and getter methods (as appropriate);
  • all JavaBean instance variables should be private.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Unresolved Import Issues with PyDev and Eclipse

KD.py

class A:
a=10;

KD2.py 
from com.jbk.KD import A;
class B:
  b=120;

aa=A();
print(aa.a)

THIS works perfectly file for me

Another example is

main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff

_init();
stuff();

settings.py
==========
def _init():
print("kiran")


subfile.py
==========
def stuff():
print("asasas")    

How to get relative path from absolute path

I'd split both of your paths at the directory level. From there, find the point of divergence and work your way back to the assembly folder, prepending a '../' everytime you pass a directory.

Keep in mind however, that an absolute path works everywhere and is usually easier to read than a relative one. I personally wouldn't show an user a relative path unless it was absolutely necessary.

MVC 3 file upload and model binding

If you won't always have images posting to your action, you can do something like this:

[HttpPost]
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{
    //do container stuff

    if (Request.Files != null)
    {
        foreach (string requestFile in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[requestFile]; 
            if (file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string directory = Server.MapPath("~/App_Data/uploads/");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string path = Path.Combine(directory, fileName);
                file.SaveAs(path);
            }
        }
    }

} 

With CSS, use "..." for overflowed block of multi-lines

I found a javascript trick, but you have to use the length of the string. Lets say you want 3 lines of width 250px, you can calculate the length per line i.e.

//get the total character length.
//Haha this might vary if you have a text with lots of "i" vs "w"
var totalLength = (width / yourFontSize) * yourNumberOfLines

//then ellipsify
function shorten(text, totalLength) {
    var ret = text;
    if (ret.length > totalLength) {
        ret = ret.substr(0, totalLength-3) + "...";
    }
    return ret;
}

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

How to add element in List while iterating in java?

To help with this I created a function to make this more easy to achieve it.

public static <T> void forEachCurrent(List<T> list, Consumer<T> action) {
    final int size = list.size();
    for (int i = 0; i < size; i++) {
        action.accept(list.get(i));
    }
}

Example

    List<String> l = new ArrayList<>();
    l.add("1");
    l.add("2");
    l.add("3");
    forEachCurrent(l, e -> {
        l.add(e + "A");
        l.add(e + "B");
        l.add(e + "C");
    });
    l.forEach(System.out::println);

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?

In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Excel 2013 VBA Clear All Filters macro

I usually use this code

Sub AutoFilter_Remove()
    Sheet1.AutoFilterMode = False  'Change Sheet1 to the relevant sheet
                                   'Alternatively: Worksheets("[Your Sheet Name]").AutoFilterMode = False
End Sub

How do I get the full path of the current file's directory?

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}

Examples

Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

Labels

Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

How do shift operators work in Java?

The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.

value= value >> steps  // Right shift, signed data.
value= value << steps  // Left shift, signed data.

How do you add a Dictionary of items into another Dictionary

You can add a Dictionary extension like this:

extension Dictionary {
    func mergedWith(otherDictionary: [Key: Value]) -> [Key: Value] {
        var mergedDict: [Key: Value] = [:]
        [self, otherDictionary].forEach { dict in
            for (key, value) in dict {
                mergedDict[key] = value
            }
        }
        return mergedDict
    }
}

Then usage is as simple as the following:

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = dict1.mergedWith(dict2)
// => ["a": "foo", "b": "bar"]

If you prefer a framework that also includes some more handy features then checkout HandySwift. Just import it to your project and you can use the above code without adding any extensions to the project yourself.

case in sql stored procedure on SQL Server

Try this

If @NewStatus  = 'InOffice' 
BEGIN
     Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'OutOffice'
BEGIN
    Update tblEmployee set InOffice = -1 where EmpID = @EmpID
END
Else If @NewStatus  = 'Home'
BEGIN
    Update tblEmployee set Home = -1 where EmpID = @EmpID
END

Element count of an array in C++

Use the Microsoft "_countof(array)" Macro. This link to the Microsoft Developer Network explains it and offers an example that demonstrates the difference between "sizeof(array)" and the "_countof(array)" macro.

Microsoft and the "_countof(array)" Macro

Can you pass parameters to an AngularJS controller on creation?

If using angular-ui-router, then this is the correct solution: https://github.com/angular-ui/ui-router/wiki#resolve

Basically, you declare a set of dependecies to "resolve" before the controller is instantiated. You may declare dependencies for each of your "states". These dependencies are then passed in the controller's "constructor".

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

How to change the text color of first select option

What about this:

_x000D_
_x000D_
select{
  width: 150px;
  height: 30px;
  padding: 5px;
  color: green;
}
select option { color: black; }
select option:first-child{
  color: green;
}
_x000D_
<select>
  <option>one</option>
  <option>two</option>
</select>
_x000D_
_x000D_
_x000D_

http://jsbin.com/acucan/9

What are bitwise shift (bit-shift) operators and how do they work?

Some useful bit operations/manipulations in Python.

I implemented Ravi Prakash's answer in Python.

# Basic bit operations
# Integer to binary
print(bin(10))

# Binary to integer
print(int('1010', 2))

# Multiplying x with 2 .... x**2 == x << 1
print(200 << 1)

# Dividing x with 2 .... x/2 == x >> 1
print(200 >> 1)

# Modulo x with 2 .... x % 2 == x & 1
if 20 & 1 == 0:
    print("20 is a even number")

# Check if n is power of 2: check !(n & (n-1))
print(not(33 & (33-1)))

# Getting xth bit of n: (n >> x) & 1
print((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0

# Toggle nth bit of x : x^(1 << n)
# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)
print(10^(1 << 2))

How to specify in crontab by what user to run script?

Since you're running Ubuntu, your system crontab is located at /etc/crontab.

As the root user (or using sudo), you can simply edit this file and specify the user that should run this command. Here is the format of entries in the system crontab and how you should enter your command:

# m h dom mon dow user  command
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

Of course the permissions for your php script and your log file should be set so that the www-data user has access to them.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

How can I show dots ("...") in a span with hidden overflow?

Try this,

.truncate {
    display:inline-block;
    width:180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

add .truncate class to your element.


EDIT,

Above solution is not working in all the browsers. you can try following jQuery plugin with cross browser support.

(function ($) {
    $.fn.ellipsis = function () {
        return this.eachAsync({
            delay: 100,
            bulk: 0,
            loop: function (index) {
                var el = $(this);

                if (el.data("fullText") !== undefined) {
                    el.html(el.data("fullText"));
                } else {
                    el.data("fullText", el.html());
                }

                if (el.css("overflow") == "hidden") {
                    var text = el.html();
                    var t = $(this.cloneNode(true))
                                        .hide()
                                        .css('position', 'absolute')
                                        .css('overflow', 'visible')
                                        .width('auto')
                                        .height(el.height())
                                        ;

                    el.after(t);

                    function width() { return t.width() > el.width(); };

                    var func = width;
                    while (text.length > 0 && width()) {
                        text = text.substr(0, text.length - text.length * 25 / 100);
                        t.html(text + "...");
                    }

                    el.html(t.html());
                    t.remove();
                }
            }
        });
    };
})(jQuery);

how to call,

$("#content_right_head span").ellipsis();

UIButton action in table view cell

As Apple DOC

targetForAction:withSender:
Returns the target object that responds to an action.

You can't use that method to set target for UIButton.
Try addTarget(_:action:forControlEvents:) method

Parsing JSON from URL

I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class can be also a complex type. Just for example used.

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Do we need type="text/css" for <link> in HTML5

The HTML5 spec says that the type attribute is purely advisory and explains in detail how browsers should act if it's omitted (too much to quote here). It doesn't explicitly say that an omitted type attribute is either valid or invalid, but you can safely omit it knowing that browsers will still react as you expect.

svn : how to create a branch from certain revision of trunk

$ svn copy http://svn.example.com/repos/calc/trunk@192 \
   http://svn.example.com/repos/calc/branches/my-calc-branch \
   -m "Creating a private branch of /calc/trunk."

Where 192 is the revision you specify

You can find this information from the SVN Book, specifically here on the page about svn copy

How do I make a fully statically linked .exe with Visual Studio Express 2005?

I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:

How to: Deploy using XCopy (MSDN)

Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).

Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.

Fastest Convert from Collection to List<T>

What version of the framework? With 3.5 you could presumably use:

List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();

(edited to remove simpler version; I checked and ManagementObjectCollection only implements the non-generic IEnumerable form)

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

How can I exclude multiple folders using Get-ChildItem -exclude?

You could also do this in a single statement:

$j = "Somepath"
$files = Get-ChildItem -Path $j -Include '*.xlsx','*.zip' -Recurse -ErrorAction SilentlyContinue –File | ? {$_.Directory -notlike "$j\donotwantfoldername"}

How to check if a variable is not null?

  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

How to play a notification sound on websites?

Play cross browser compatible notifications

As adviced by @Tim Tisdall from this post , Check Howler.js Plugin.

Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.

  var sound =new Howl({
                     src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
                           '../sounds/rings.aiff'],
                     autoplay: true,
                     loop: true
                    });

               sound.play();

Hope helps someone.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

ADD and COPY both have same functionality of copying files and directories from source to destination but ADD has extra of file extraction and URL file extraction functionality. The best practice is to use COPY in only copy operation only avoid ADD is many areas. The link will explain it with some simple examples difference between COPY and ADD in dockerfile

Command to get time in milliseconds

Nano is 10-9 and milli 10-3. Hence, we can use the three first characters of nanoseconds to get the milliseconds:

date +%s%3N

From man date:

%N nanoseconds (000000000..999999999)

%s seconds since 1970-01-01 00:00:00 UTC

Source: Server Fault's How do I get the current Unix time in milliseconds in Bash?.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

You can use :not(.class) selector as mentioned before.

If you care about Internet explorer compatibility I recommend you to use http://selectivizr.com/.

But remember to run it under apache otherwise you won't see the effect.

Regular expression to match any character being repeated more than 10 times

={10,}

matches = that is repeated 10 or more times.

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

Change background color of selected item on a ListView

I know this is a old question, but i give a simple solution for this need (without loops!):

//On your adapter create a variable:
private View lastSelectedItem;

//Define the folowing method:
private void toggleBackgroundItem(View view) {
    if (lastSelectedItem != null) {
        lastSelectedItem.setBackgroundColor(Color.TRANSPARENT);
    }
    view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    lastSelectedItem = view;

}
//finally invoque the method onItemClick
lvSac.setOnItemClickListener(new AdapterView.OnItemClickListener()

{
    @Override
    public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){

    toggleBackgroundItem(view);
}
}

Inserting a PDF file in LaTeX

\includegraphics{myfig.pdf}

How can I stop a While loop?

I would do it using a for loop as shown below :

def determine_period(universe_array):
    tmp = universe_array
    for period in xrange(1, 13):
        tmp = apply_rules(tmp)
        if numpy.array_equal(tmp, universe_array):
            return period
    return 0

jQuery ajax upload file in asp.net mvc

If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

How can I pass data from Flask to JavaScript in a template?

Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.

Specify a data attribute like so:

<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>

Then access it in a static JavaScript file like so:

// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);

// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));

What are some ways of accessing Microsoft SQL Server from Linux?

I was not confortable with the freetds solution, it's why i coded a class (command history, autocompletion on tables and fields, etc.)

http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){
    // edited at is newer than created at
}

how to read a text file using scanner in Java?

Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.

NOTE: It also works when used with System.err.print("Error Message Here")

@Value annotation type casting to Integer from String

This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:

You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How to convert 'binary string' to normal string in Python3?

Decode it.

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

>>> 'a string'.encode('ascii')
b'a string'

How do I collapse a table row in Bootstrap?

Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.

In 2.3.2 the collapse class wasn't getting replaced by the in class. The in class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse class correctly is removed, and the <tr> collapses.

Use @Chad's solution for the html, and try using these links for referencing Bootstrap:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>

Newline character in StringBuilder

It will append \n in Linux instead \r\n.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Minimal solution that worked for me for current project

  • A create-react-app project
  • Ubuntu / *nix
  • 2020
  • Node 14.7

delete node_modules/browserslist directory in the project

now

npm run build

no longer generates that message

make div's height expand with its content

Very simple way

On parent DIV:

height: 100%;

This work for me every time

How to convert a Bitmap to Drawable in android?

1) bitmap to Drawable :

Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);

2) drawable to Bitmap :

Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_resource);
// mImageView.setImageBitmap(mIcon);

How to make a loop in x86 assembly language?

Yet another method is using the LOOP instruction:

mov  cx, 3

myloop:
    ; Your loop content

    loop myloop

The loop instruction automatically decrements cx, and only jumps if cx != 0. There are also LOOPE, and LOOPNE variants, if you want to do some additional check for your loop to break out early.

If you want to modify cx during your loop, make sure to push it onto the stack before the loop content, and pop it off after:

mov  cx, 3

myloop:
    push cx
    ; Your loop content
    pop  cx

    loop myloop

Maintain/Save/Restore scroll position when returning to a ListView

I found something interesting about this.

I tried setSelection and scrolltoXY but it did not work at all, the list remained in the same position, after some trial and error I got the following code that does work

final ListView list = (ListView) findViewById(R.id.list);
list.post(new Runnable() {            
    @Override
    public void run() {
        list.setSelection(0);
    }
});

If instead of posting the Runnable you try runOnUiThread it does not work either (at least on some devices)

This is a very strange workaround for something that should be straight forward.

What does the return keyword do in a void method in Java?

It functions the same as a return for function with a specified parameter, except it returns nothing, as there is nothing to return and control is passed back to the calling method.

Convert an integer to a float number

intutils.ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)
}

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)
}

Chart.js v2 - hiding grid lines

The code below removes remove grid lines from chart area only not the ones in x&y axis labels

Chart.defaults.scale.gridLines.drawOnChartArea = false;

Common CSS Media Queries Break Points

Instead of using pixels should use em or percentage as it is more adaptive and fluid, better not target devices target your content:

HTML5 rockrs read, mobile first

View's SELECT contains a subquery in the FROM clause

create view view_clients_credit_usage as
    select client_id, sum(credits_used) as credits_used 
    from credit_usage 
    group by client_id

create view view_credit_status as 
    select 
        credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased, 
        ifnull(t1.credits_used,0) as used 
    from credit_orders
    left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
    where credit_orders.payment_status='Paid'
    group by credit_orders.client_id)

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

HTML5 - mp4 video does not play in IE9

I have a base profile .mp4 video which plays on one server, and does not on another.

The only difference is:
one gives a header "Content-Length: ..."
the other "Trasfer-Encoding: chunked".

I found out that Content-Length is not needed, it is only important, that there should be NO chunked header. This can be done by turning off compression (deflate or gzip) for .mp4 files. How this can be done is another issue and another topic: How to disable Apache gzip compression for some media files in .htaccess file?

There can be another server issue:
it has to give "Content-Type: video/mp4"
and NOT "Content-Type: text/plain"

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

A long bigger than Long.MAX_VALUE

Firstly, the below method doesn't compile as it is missing the return type and it should be Long.MAX_VALUE in place of Long.Max_value.

public static boolean isBiggerThanMaxLong(long value) {
      return value > Long.Max_value;
}

The above method can never return true as you are comparing a long value with Long.MAX_VALUE , see the method signature you can pass only long there.Any long can be as big as the Long.MAX_VALUE, it can't be bigger than that.

You can try something like this with BigInteger class :

public static boolean isBiggerThanMaxLong(BigInteger l){
    return l.compareTo(BigInteger.valueOf(Long.MAX_VALUE))==1?true:false;
}

The below code will return true :

BigInteger big3 = BigInteger.valueOf(Long.MAX_VALUE).
                  add(BigInteger.valueOf(Long.MAX_VALUE));
System.out.println(isBiggerThanMaxLong(big3)); // prints true

encrypt and decrypt md5

/* you  can match the exact string with table value*/

if(md5("string to match") == $res["hashstring"])
 echo "login correct";

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

How to get phpmyadmin username and password

Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.

Disable future dates after today in Jquery Ui Datepicker

Change maxDate to current date

maxDate: new Date()

It will set current date as maximum value.

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

What about of

import java.util.Collections;

List<A> abc = Collections.synchronizedList(new ArrayList<>());

javascript password generator

here is a simply smart code :

function generate(l) {
    if (typeof l==='undefined'){var l=8;}
    /* c : alphanumeric character string */
    var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
    n=c.length,
    /* p : special character string */
    p='!@#$+-*&_',
    o=p.length,
    r='',
    n=c.length,
    /* s : determinate the position of the special character */
    s=Math.floor(Math.random() * (p.length-1));

    for(var i=0; i<l; ++i){
        if(s == i){
            /* special charact insertion (random position s) */
            r += p.charAt(Math.floor(Math.random() * o));
        }else{
            /* alphanumeric insertion */
            r += c.charAt(Math.floor(Math.random() * n));
        }
    }
    return r;
}

Simply call generate(), and it do key containing one special character (!@#$+-*&_) for security.

Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_

There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/

What is the best way to detect a mobile device?

Depending on what for you want to detect mobile (meaning this suggestion won't suit everyone's needs), you might be able to achieve a distinction by looking at the onmouseenter-to-onclick millisecond difference, like I described in this answer.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

How to pass the button value into my onclick event function?

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

Generic htaccess redirect www to non-www

Added if localhost, ignore redirection (for development purpose in local environment). If not localhost AND (not https OR it’s www), redirect to https and non-www.

RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} !localhost [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

If you want examples of Algorithms/Group of Statements with Time complexity as given in the question, here is a small list -

O(1) time

  • Accessing Array Index (int a = ARR[5];)
  • Inserting a node in Linked List
  • Pushing and Poping on Stack
  • Insertion and Removal from Queue
  • Finding out the parent or left/right child of a node in a tree stored in Array
  • Jumping to Next/Previous element in Doubly Linked List

O(n) time

In a nutshell, all Brute Force Algorithms, or Noob ones which require linearity, are based on O(n) time complexity

  • Traversing an array
  • Traversing a linked list
  • Linear Search
  • Deletion of a specific element in a Linked List (Not sorted)
  • Comparing two strings
  • Checking for Palindrome
  • Counting/Bucket Sort and here too you can find a million more such examples....

O(log n) time

  • Binary Search
  • Finding largest/smallest number in a binary search tree
  • Certain Divide and Conquer Algorithms based on Linear functionality
  • Calculating Fibonacci Numbers - Best Method The basic premise here is NOT using the complete data, and reducing the problem size with every iteration

O(n log n) time

The factor of 'log n' is introduced by bringing into consideration Divide and Conquer. Some of these algorithms are the best optimized ones and used frequently.

  • Merge Sort
  • Heap Sort
  • Quick Sort
  • Certain Divide and Conquer Algorithms based on optimizing O(n^2) algorithms

O(n^2) time

These ones are supposed to be the less efficient algorithms if their O(nlogn) counterparts are present. The general application may be Brute Force here.

  • Bubble Sort
  • Insertion Sort
  • Selection Sort
  • Traversing a simple 2D array

Omitting the first line from any Linux command output

ls -lart | tail -n +2 #argument means starting with line 2

Who sets response content-type in Spring MVC (@ResponseBody)

Simple declaration of the StringHttpMessageConverter bean is not enough, you need to inject it into AnnotationMethodHandlerAdapter:

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </array>
    </property>
</bean>

However, using this method you have to redefine all HttpMessageConverters, and also it doesn't work with <mvc:annotation-driven />.

So, perhaps the most convenient but ugly method is to intercept instantiation of the AnnotationMethodHandlerAdapter with BeanPostProcessor:

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}

-

<bean class = "EncodingPostProcessor " />

How to Force New Google Spreadsheets to refresh and recalculate?

None of the existing answers worked for me, but this approach did.

The problem

I was seeing lots of cells say #REF!. These are cells in a sheet that I copied from another Google Sheet doc using "Copy to > Existing Worksheet". If I press Enter in any cell, it recalculates correctly, But I don't want to do that for millions of cells.

My answer

I ran this recalcSheet() script. It takes almost 0.5 seconds per cell, which is very slow but is faster than manually fixing each cell.

function recalcSheet(){  
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = spreadsheet.getSheetByName("put_your_sheet_name_here");  // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename
  // var range = sheet.getSelection().getActiveRange();
  // var range = sheet.getRange('A6:D6');
  var range = sheet.getDataRange();  
  recalcRange(range, spreadsheet);
}

function recalcRange(range, spreadsheet){
  // following structure of https://stackoverflow.com/a/52123839/470749
  Logger.log('Range: ' + range.getA1Notation());
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var startRow = range.getRow();
  var startCol = range.getColumn();
  Logger.log('row: ' + startRow);
  Logger.log('col: ' + startCol);
  Logger.log('numRows: ' + numRows);
  Logger.log('numCols: ' + numCols);

  for (var r = 1; r <= numRows; r+=1) {
    for (var c = 1; c <= numCols; c+=1) {
      var originalFormula = range.getCell(r, c).getFormula(); // https://developers.google.com/apps-script/reference/spreadsheet/range#getFormula()
      Logger.log(`r,c ${r}, ${c}; originalFormula: ${originalFormula}`);
      if(originalFormula){
        range.getCell(r, c).setFormula('');
        //SpreadsheetApp.flush(); // https://webapps.stackexchange.com/a/35970/27487
        range.getCell(r, c).setFormula(originalFormula);
      }
    }
  }
  spreadsheet.toast('Each cell in the range has been recalculated.', "Finished!"); // https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#toast(String)
}

Handling Enter Key in Vue.js

This event works to me:

@keyup.enter.native="onEnter".

How to get the command line args passed to a running process on unix/linux systems?

You can use pgrep with -f (full command line) and -l (long description):

pgrep -l -f PatternOfProcess

This method has a crucial difference with any of the other responses: it works on CygWin, so you can use it to obtain the full command line of any process running under Windows (execute as elevated if you want data about any elevated/admin process). Any other method for doing this on Windows is more awkward ( for example ).
Furthermore: in my tests, the pgrep way has been the only system that worked to obtain the full path for scripts running inside CygWin's python.

OnItemCLickListener not working in listview

I had the same problem and I just saw I had accidentally set:

@Override
public boolean isEnabled(int position)
{
    return false;
}

on my CustomListViewAdapter class.

By changing this to:

return true;

I've managed to fix the problem. Just in case if someone has done the same mistake...

How to correctly set Http Request Header in Angular 2

Angular 4 >

You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.


Manually

Setting a header:

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

Setting headers:

this.http
.post('api/items/add', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe()

Local variable (immutable instantiate again)

let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');

this.http
  .post('api/items/add', body, { headers: headers })
  .subscribe()

The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

From the Angular docs.


HTTP interceptor

A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

From the Angular docs.

Make sure you use @angular/common/http throughout your application. That way your requests will be catched by the interceptor.

Step 1, create the service:

import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (true) { // e.g. if token exists, otherwise use incomming request.
            return next.handle(req.clone({
                setHeaders: {
                    'AuthenticationToken': localStorage.getItem('TOKEN'),
                    'Tenant': localStorage.getItem('TENANT')
                }
            }));
        }
        else {
            return next.handle(req);
        }
    }
}

Step 2, add it to your module:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HeaderInterceptor,
      multi: true // Add this line when using multiple interceptors.
    },
    // ...
  ]

Useful links:

milliseconds to time in javascript

Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:

function msToTime(s) {
  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return hrs + ':' + mins + ':' + secs + '.' + ms;
}

If you want it formatted as hh:mm:ss.sss then use:

_x000D_
_x000D_
function msToTime(s) {_x000D_
_x000D_
  // Pad to 2 or 3 digits, default is 2_x000D_
  function pad(n, z) {_x000D_
    z = z || 2;_x000D_
    return ('00' + n).slice(-z);_x000D_
  }_x000D_
_x000D_
  var ms = s % 1000;_x000D_
  s = (s - ms) / 1000;_x000D_
  var secs = s % 60;_x000D_
  s = (s - secs) / 60;_x000D_
  var mins = s % 60;_x000D_
  var hrs = (s - mins) / 60;_x000D_
_x000D_
  return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);_x000D_
}_x000D_
_x000D_
console.log(msToTime(55018))
_x000D_
_x000D_
_x000D_

Using some recently added language features, the pad function can be more concise:

_x000D_
_x000D_
function msToTime(s) {_x000D_
    // Pad to 2 or 3 digits, default is 2_x000D_
  var pad = (n, z = 2) => ('00' + n).slice(-z);_x000D_
  return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);_x000D_
}_x000D_
_x000D_
// Current hh:mm:ss.sss UTC_x000D_
console.log(msToTime(new Date() % 8.64e7))
_x000D_
_x000D_
_x000D_

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

It could be related with your Java version. Go ahead and download the Database version which includes Java.

However, if you are configuring a local development workstation I recommend you to download the Express Edition.

Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html

or google this: OracleXE112_Win64

Good luck!

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

How to convert int to float in C?

This can give you the correct Answer

#include <stdio.h>
int main()
{
    float total=100, number=50;
    float percentage;
    percentage=(number/total)*100;
    printf("%0.2f",percentage);
    return 0;
}

How do you check whether a number is divisible by another number (Python)?

This code appears to do what you are asking for.

for value in range(1,1000):
    if value % 3 == 0 or value % 5 == 0:
        print(value)

Or something like

for value in range(1,1000):
    if value % 3 == 0 or value % 5 == 0:
        some_list.append(value)

Or any number of things.

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

How to get the MD5 hash of a file in C++?

For anyone redirected from "https://stackoverflow.com/questions/4393017/md5-implementation-in-c" because it's been incorrectly labelled a duplicate.

The example located here works:

http://www.zedwood.com/article/cpp-md5-function

If you are compiling in VC++2010 then you will need to change his main.cpp to this:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    std::string Temp =  md5("The quick brown fox jumps over the lazy dog");
    cout << Temp.c_str() << endl;

    return 0;
}

You will have to change the MD5 class slightly if you are to read in a char * array instead of a string to answer the question on this page here.

EDIT:

Apparently modifying the MD5 library isn't clear, well a Full VC++2010 solution is here for your convenience to include char *'s:

https://github.com/alm4096/MD5-Hash-Example-VS

A bit of an explanation is here:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    //Start opening your file
    ifstream inBigArrayfile;
    inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);

    //Find length of file
    inBigArrayfile.seekg (0, std::ios::end);
    long Length = inBigArrayfile.tellg();
    inBigArrayfile.seekg (0, std::ios::beg);    

    //read in the data from your file
    char * InFileData = new char[Length];
    inBigArrayfile.read(InFileData,Length);

    //Calculate MD5 hash
    std::string Temp =  md5(InFileData,Length);
    cout << Temp.c_str() << endl;

    //Clean up
    delete [] InFileData;

    return 0;
}

I have simply added the following into the MD5 library:

MD5.cpp:

MD5::MD5(char * Input, long length)
{
  init();
  update(Input, length);
  finalize();
}

MD5.h:

std::string md5(char * Input, long length);

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

UITableview: How to Disable Selection for Some Rows but Not Others

I found this handy as it works with both static and dynamic tables. I only set the disclosure indicator on those cells I want to allow selection.

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator) {
        return nil;
    }
    return indexPath;
}

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

Add days to JavaScript Date

Try

var someDate = new Date();
var duration = 2; //In Days
someDate.setTime(someDate.getTime() +  (duration * 24 * 60 * 60 * 1000));

Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

How do I get the time of day in javascript/Node.js?

You should checkout the Date object.

In particular, you can look at the getHours() method for the Date object.

getHours() return the time from 0 - 23, so make sure to deal with it accordingly. I think 0-23 is a bit more intuitive since military time runs from 0 - 23, but it's up to you.

With that in mind, the code would be something along the lines of:

var date = new Date();
var current_hour = date.getHours();

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

I had the similar issue......to solve this what I did was to uninstall the ODP. Net and re-install in the same directory as oracle server......with server option you will notice that most of the products are already installed (while 12c database installation) so just select the other features and finally finish the installation....

Please note that this workaround works only if you have installed 12c on the same machine i.e. on your laptop............

If your database is located on the server machine other than your laptop then please select client option and not the server and then include TNS_ADMIN in your app.config and do not forget to specify the version...

since my installation is on my laptop so my App.config is as below:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
</configuration>


 /////////the below code is a sample from oracle company////////////////


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;

///copy these lines in a button click event 
    string constr = "User Id=system; Password=manager; Data Source=orcl;";
// Click here and then press F9 to insert a breakpoint
        DbProviderFactory factory =
    DbProviderFactories.GetFactory("Oracle.ManagedDataAccess.Client");
            using (DbConnection conn = factory.CreateConnection())
            {
                conn.ConnectionString = constr;
                try
                {
                    conn.Open();
                    OracleCommand cmd = (OracleCommand)factory.CreateCommand();
                    cmd.Connection = (OracleConnection)conn;

//to gain access to ROWIDs of the table
//cmd.AddRowid = true;
                    cmd.CommandText = "select * from all_users";

                    OracleDataReader reader = cmd.ExecuteReader();

                    int visFC = reader.VisibleFieldCount; //Results in 2
                    int hidFC = reader.HiddenFieldCount;  // Results in 1

                    MessageBox.Show(" Visible field count: " + visFC);

                    MessageBox.Show(" Hidden field count: " + hidFC);


                    reader.Dispose();
                    cmd.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                      MessageBox.Show(ex.StackTrace);
                }
            }

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

Set Radiobuttonlist Selected from Codebehind

You could do:

radio1.SelectedIndex = 1;

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:

//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;

Create component to specific module with Angular-CLI

1.- Create your feature module as usual.

ng generate module dirlevel1/module-name

2.- You can specify the ROOT PATH of your project in --module ( only in --module, (/) root points to your PROJECT ROOT and IS NOT THE SYSTEM ROOT!!!)

ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts

Real Example:

ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts 

Output:

CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!

Tested with Angular CLI: 9.1.4

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

Python "\n" tag extra line

Add , after the print "\n" line

so that it reads print "\n",

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

BUILDING Again on Nathan and JB's Answer:

How To Launch App From url w/o Extra Click If you prefer a solution that does not include the interim step of clicking a link, the following can be used. With this javascript, I was able to return a Httpresponse object from Django/Python that successfully launches an app if it is installed or alternatively launches the app store in the case of a time out. Note I also needed to adjust the timeout period from 500 to 100 in order for this to work on an iPhone 4S. Test and tweak to get it right for your situation.

<html>
<head>
   <meta name="viewport" content="width=device-width" />
</head>
<body>

<script type="text/javascript">

// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";

var loadedAt = +new Date;
setTimeout(
  function(){
    if (+new Date - loadedAt < 2000){
      window.location = appstorefail;
    }
  }
,100);

function LaunchApp(){
  window.open("unknown://nowhere","_self");
};
LaunchApp()
</script>
</body>
</html>

StringBuilder vs String concatenation in toString() in Java

Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.

So for the sake of code readability, use "+".

2 exceptions :

  • multithreaded environment : StringBuffer
  • concatenation in loops : StringBuilder/StringBuffer

Get height of div with no height set in css

jQuery .height will return you the height of the element. It doesn't need CSS definition as it determines the computed height.

DEMO

You can use .height(), .innerHeight() or outerHeight() based on what you need.

enter image description here

.height() - returns the height of element excludes padding, border and margin.

.innerHeight() - returns the height of element includes padding but excludes border and margin.

.outerHeight() - returns the height of the div including border but excludes margin.

.outerHeight(true) - returns the height of the div including margin.

Check below code snippet for live demo. :)

_x000D_
_x000D_
$(function() {_x000D_
  var $heightTest = $('#heightTest');_x000D_
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Combining two lists and removing duplicates, without removing duplicates in original list

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]

    newList=[]
    for i in first_list:
        newList.append(i)
    for z in second_list:
        if z not in newList:
            newList.append(z)
    newList.sort()
    print newList

[1, 2, 2, 5, 7, 9]

pg_config executable not found

I got fixed this by running the following command.

env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2

Reference : https://stackoverflow.com/a/39800677/4270698

Unable to copy ~/.ssh/id_rsa.pub

Try this and it will work like a charm. I was having the same error but this approach did the trick for me:

ssh USER@REMOTE "cat file"|xclip -i

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

How to Lock the data in a cell in excel using vba

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.

How to create Java gradle project

Finally after comparing all solution, I think starting from build.gradle file can be convenient.

Gradle distribution has samples folder with a lot of examples, and there is gradle init --type basic comand see Chapter 47. Build Init Plugin. But they all needs some editing.

You can use template below as well, then run gradle initSourceFolders eclipse

/*
* Nodeclipse/Enide build.gradle template for basic Java project
*   https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
*   http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
*   1. create folder (or general Eclipse project) and put this file inside
*   2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest; 
* based on `gradle init --type basic`, that does not create source folders 
*/

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

task initSourceFolders { // add << before { to prevent executing during configuration phase
   sourceSets*.java.srcDirs*.each { it.mkdirs() }
   sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use Maven Central for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    //compile fileTree(dir: 'libs', include: '*.jar')
    // The production code uses the SLF4J logging API at compile time
    //compile 'org.slf4j:slf4j-api:1.7.5'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile "junit:junit:4.11"
}

The result is like below.

overview

That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse

editbox

How do I use $rootScope in Angular to store variables?

angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
   var a = //something in the scope
   //put it in the root scope
    $rootScope.test = "TEST";
 });

angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
   var b = //get var a from root scope somehow
   //use var b

   $scope.value = $rootScope.test;
   alert($scope.value);

 //    var b = $rootScope.test;
 //  alert(b);
 });

DEMO

setOnItemClickListener on custom ListView

If above answers don't work maybe you didn't add return value into getItem method in the custom adapter see this question and check out first answer.

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

DECLARE @dayNumber INT;
SET @dayNumber = DATEPART(DW, GETDATE());

--Sunday = 1, Saturday = 7.
IF(@dayNumber = 1 OR @dayNumber = 7) 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

This may generate wrong results, because the number produced by the weekday datepart depends on the value set by SET DATEFIRST. This sets the first day of the week. So another way is:

DECLARE @dayName VARCHAR(9);
SET @dayName = DATEName(DW, GETDATE());

IF(@dayName = 'Saturday' OR @dayName = 'Sunday') 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

Bootstrap: add margin/padding space between columns

Just add 'justify-content-around' class. that would automatically add gap between 2 divs.

Documentation: https://getbootstrap.com/docs/4.1/layout/grid/#horizontal-alignment

Sample:

<div class="row justify-content-around">
    <div class="col-4">
      One of two columns
    </div>
    <div class="col-4">
      One of two columns
    </div>
</div>

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

TL;DR

>>> import pandas as pd
>>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
>>> dict(sorted(df.values.tolist())) # Sort of sorted... 
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> from collections import OrderedDict
>>> OrderedDict(df.values.tolist())
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

In Long

Explaining solution: dict(sorted(df.values.tolist()))

Given:

df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})

[out]:

 Letter Position
0   a   1
1   b   2
2   c   3
3   d   4
4   e   5

Try:

# Get the values out to a 2-D numpy array, 
df.values

[out]:

array([['a', 1],
       ['b', 2],
       ['c', 3],
       ['d', 4],
       ['e', 5]], dtype=object)

Then optionally:

# Dump it into a list so that you can sort it using `sorted()`
sorted(df.values.tolist()) # Sort by key

Or:

# Sort by value:
from operator import itemgetter
sorted(df.values.tolist(), key=itemgetter(1))

[out]:

[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]

Lastly, cast the list of list of 2 elements into a dict.

dict(sorted(df.values.tolist())) 

[out]:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Related

Answering @sbradbio comment:

If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is:

from collections import defaultdict
import pandas as pd

multivalue_dict = defaultdict(list)

df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']})

for idx,row in df.iterrows():
    multivalue_dict[row['Position']].append(row['Letter'])

[out]:

>>> print(multivalue_dict)
defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']})

SQL Server: Get data for only the past year

For some reason none of the results above worked for me.

This selects the last 365 days.

 SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()