Programs & Examples On #Rating system

A system commonly seen on websites that allows users to express their appreciation (or lack there of) of content or what the content is about.

How can I decrease the size of Ratingbar?

You can set it in the XML code for the RatingBar, use scaleX and scaleY to adjust accordingly. "1.0" would be the normal size, and anything in the ".0" will reduce it, also anything greater than "1.0" will increase it.

<RatingBar
  android:id="@+id/ratingBar1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:scaleX="0.5"
  android:scaleY="0.5" />

Integrating CSS star rating into an HTML form

Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):

CSS:

.txt-center {
    text-align: center;
}
.hide {
    display: none;
}

.clear {
    float: none;
    clear: both;
}

.rating {
    width: 90px;
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: center;
    position: relative;
}

.rating > label {
    float: right;
    display: inline;
    padding: 0;
    margin: 0;
    position: relative;
    width: 1.1em;
    cursor: pointer;
    color: #000;
}

.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
    color: transparent;
}

.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
    content: "\2605";
    position: absolute;
    left: 0;
    color: #FFD700;
}

HTML:

<div class="txt-center">
    <form>
        <div class="rating">
            <input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
            <label for="star5">?</label>
            <input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
            <label for="star4">?</label>
            <input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
            <label for="star3">?</label>
            <input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
            <label for="star2">?</label>
            <input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
            <label for="star1">?</label>
            <div class="clear"></div>
        </div>
    </form>
</div>

Please check the demo

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

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

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

Find the number of downloads for a particular app in apple appstore

Updated answer now that xyo.net has been bought and shut down.

appannie.com and similarweb.com are the best options now. Thanks @rinogo for the original suggestion!

Outdated answer:

Site is still buggy, but this is by far the best that I've found. Not sure if it's accurate, but at least they give you numbers that you can guess off of! They have numbers for Android, iOS (iPhone and iPad) and even Windows!

xyo.net

How to convert an array to a string in PHP?

Using implode(), you can turn the array into a string.

$str = implode(',', $array); // 33160,33280,33180,...

How can I change an element's class with JavaScript?

No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.

The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:

Never ever change className on-the-fly !-)

But usually you'll only need to change a property or two, and that is easily implemented:

function highlight(elm){
    elm.style.backgroundColor ="#345";
    elm.style.color = "#fff";
}

file path Windows format to java format

String path = "C:\\Documents and Settings\\Manoj\\Desktop";
path = path.replace("\\", "/");
// or
path = path.replaceAll("\\\\", "/");

Find more details in the Docs

PHP multidimensional array search by value

Here is one liner for the same,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];

installing urllib in Python3.6

yu have to install the correct version for your computer 32 or 63 bits thats all

If you can decode JWT, how are they secure?

You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.

The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.

The logical question is what is the motivation for not concerning itself with encrypted contents?

  1. The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.

  2. This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).

  3. JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.

It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.

Labels for radio buttons in rails form

<% form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email', :checked => true %> 
  <%= label :contactmethod_email, 'Email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= label :contactmethod_sms, 'SMS' %>
<% end %>

jQuery scroll to element

When the user clicks on that input with #subject, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The last item of the page is a submit button with #submit

$('#subject').click(function()
{
    $('#submit').focus();
    $('#subject').focus();
});

This will first scroll down to #submit then restore the cursor back to the input that was clicked, which mimics a scroll down, and works on most browsers. It also doesn't require jQuery as it can be written in pure JavaScript.

Can this fashion of using focus function mimic animation in a better way, through chaining focus calls. I haven't tested this theory, but it would look something like this:

<style>
  #F > *
  {
    width: 100%;
  }
</style>

<form id="F" >
  <div id="child_1"> .. </div>
  <div id="child_2"> .. </div>
  ..
  <div id="child_K"> .. </div>
</form>

<script>
  $('#child_N').click(function()
  {
    $('#child_N').focus();
    $('#child_N+1').focus();
    ..
    $('#child_K').focus();

    $('#child_N').focus();
  });
</script>

How to send email to multiple address using System.Net.Mail

namespace WebForms.Code.Logging {

    public class ObserverLogToEmail: ILog {
        private string from;
        private string to;
        private string subject;
        private string body;
        private SmtpClient smtpClient;
        private MailMessage mailMessage;
        private MailPriority mailPriority;
        private MailAddressCollection mailAddressCollection;
        private MailAddress fromMailAddress, toMailAddress;
        public MailAddressCollection toMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection ccMailAddressCollection {
            get;
            set;
        }
        public MailAddressCollection bccMailAddressCollection {
            get;
            set;
        }

        public ObserverLogToEmail(string from, string to, string subject, string body, SmtpClient smtpClient) {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.body = body;

            this.smtpClient = smtpClient;
        }

        public ObserverLogToEmail(MailAddress fromMailAddress, MailAddress toMailAddress,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.fromMailAddress = fromMailAddress;
                this.toMailAddress = toMailAddress;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

                mailAddressCollection = new MailAddressCollection();

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection fromMailAddressCollection,
        MailAddressCollection toMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }

        public ObserverLogToEmail(MailAddressCollection toMailAddressCollection,
        MailAddressCollection ccMailAddressCollection,
        MailAddressCollection bccMailAddressCollection,
        string subject, string content, SmtpClient smtpClient) {
            try {
                this.toMailAddressCollection = toMailAddressCollection;
                this.ccMailAddressCollection = ccMailAddressCollection;
                this.bccMailAddressCollection = bccMailAddressCollection;

                this.subject = subject;
                this.body = content;

                this.smtpClient = smtpClient;

            } catch {
                throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
            }
        }#region ILog Members

        // sends a log request via email.
        // actual email 'Send' calls are commented out.
        // uncomment if you have the proper email privileges.
        public void Log(object sender, LogEventArgs e) {
            string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
            fromMailAddress = new MailAddress("", "HaNN", System.Text.Encoding.UTF8);
            toMailAddress = new MailAddress("", "XXX", System.Text.Encoding.UTF8);

            mailMessage = new MailMessage(fromMailAddress, toMailAddress);
            mailMessage.Subject = subject;
            mailMessage.Body = body;

            // commented out for now. you need privileges to send email.
            // _smtpClient.Send(from, to, subject, body);
            smtpClient.Send(mailMessage);
        }

        public void LogAllEmails(object sender, LogEventArgs e) {
            try {
                string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;

                mailMessage = new MailMessage();
                mailMessage.Subject = subject;
                mailMessage.Body = body;

                foreach(MailAddress toMailAddress in toMailAddressCollection) {
                    mailMessage.To.Add(toMailAddress);

                }
                foreach(MailAddress ccMailAddress in ccMailAddressCollection) {
                    mailMessage.CC.Add(ccMailAddress);
                }
                foreach(MailAddress bccMailAddress in bccMailAddressCollection) {
                    mailMessage.Bcc.Add(bccMailAddress);
                }
                if (smtpClient == null) {
                    var smtp = new SmtpClient {
                        Host = "smtp.gmail.com",
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential("yourEmailAddress", "yourPassword"),
                        Timeout = 30000
                    };
                } else smtpClient.SendAsync(mailMessage, null);
            } catch (Exception) {

                throw;
            }
        }
    }

MongoDB: Is it possible to make a case-insensitive query?

I'm surprised nobody has warned about the risk of regex injection by using /^bar$/i if bar is a password or an account id search. (I.e. bar => .*@myhackeddomain.com e.g., so here comes my bet: use \Q \E regex special chars! provided in PERL

db.stuff.find( { foo: /^\Qbar\E$/i } );

You should escape bar variable \ chars with \\ to avoid \E exploit again when e.g. bar = '\E.*@myhackeddomain.com\Q'

Another option is to use a regex escape char strategy like the one described here Javascript equivalent of Perl's \Q ... \E or quotemeta()

PHP Date Format to Month Name and Year

if you want same string output then try below else use without double quotes for proper output

$str = '20130814';
  echo date('"F Y"', strtotime($str));

//output  : "August 2013" 

How to concat string + i?

For versions prior to R2014a...

One easy non-loop approach would be to use genvarname to create a cell array of strings:

>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')

f = 

    'f1'    'f2'    'f3'    'f4'    'f5'

For newer versions...

The function genvarname has been deprecated, so matlab.lang.makeUniqueStrings can be used instead in the following way to get the same output:

>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')

 f =
   1×5 cell array

     'f1'    'f2'    'f3'    'f4'    'f5'

Insert value into a string at a certain position?

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

How to run batch file from network share without "UNC path are not supported" message?

I feel cls is the best answer. It hides the UNC message before anyone can see it. I combined it with a @pushd %~dp0 right after so that it would seem like opening the script and map the location in one step, thus preventing further UNC issues.

cls
@pushd %~dp0
:::::::::::::::::::
:: your script code here
:::::::::::::::::::
@popd

Notes:

pushd will change your working directory to the scripts location in the new mapped drive.

popd at the end, to clean up the mapped drive.

SQL Server: Difference between PARTITION BY and GROUP BY

They're used in different places. group by modifies the entire query, like:

select customerId, count(*) as orderCount
from Orders
group by customerId

But partition by just works on a window function, like row_number:

select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

A group by normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by does not affect the number of rows returned, but it changes how a window function's result is calculated.

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

Html.Label - Just creates a label tag with whatever the string passed into the constructor is

Html.LabelFor - Creates a label for that specific property. This is strongly typed. By default, this will just do the name of the property (in the below example, it'll output MyProperty if that Display attribute wasn't there). Another benefit of this is you can set the display property in your model and that's what will be put here:

public class MyModel
{
    [Display(Name="My property title")
    public class MyProperty{get;set;}
}

In your view:

Html.LabelFor(x => x.MyProperty) //Outputs My property title

In the above, LabelFor will display <label for="MyProperty">My property title</label>. This works nicely so you can define in one place what the label for that property will be and have it show everywhere.

How to change the interval time on bootstrap carousel?

       <div class="carousel-inner text-right">
                  <div class="carousel-item active text-center" id="first"  data-interval="1000" >
                    <img src="images/slide-1.gif" alt="slide-1">
                  </div>
                  <div class="carousel-item  text-center" id="second"  data-interval="2000" >
                    <img src="images/slide-2.gif" alt="slide-2">
                  </div>
                  <div class="carousel-item  text-center" id="third"  data-interval="3000" >
                    <img src="images/slide-3.gif" alt="slide-3">
                  </div>
                  <div class="carousel-item text-center" id="four"  data-interval="5000" >
                    <img src="images/slide-4.gif" alt="slide-4">
                  </div>
                </div>

You can also change different slides.

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

Parameter in like clause JPQL

You could use the JPA LOCATE function.

LOCATE(searchString, candidateString [, startIndex]): Returns the first index of searchString in candidateString. Positions are 1-based. If the string is not found, returns 0.

FYI: The documentation on my top google hit had the parameters reversed.

SELECT 
  e
FROM 
  entity e
WHERE
  (0 < LOCATE(:searchStr, e.property))

Using npm behind corporate proxy .pac

I ran into similar issue and found out that my npm config file ( .npmrc) is having wrong registry entry. commented it out and re ran npm install. it worked.

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

Read MS Exchange email in C#

It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.

What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)

If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)

If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

Getter and Setter declaration in .NET

Well, the first and second both generate something like the third in the end. However, don't use the third when you have a syntax for properties.

Finally, if you have no work to do in the get or set, then use the first.

In the end, the first and second are just some form of syntactic sugar, but why code more than what's necessary.

// more code == more bugs

And just to have a little fun, consider this:

public string A { get; private set; }

Now that's a lot more straight forward isn't it? The public modifier is implied on both the get and the set, but it can be overriden. This would of course be the same rule for any modifier used when defining the property itself.

compression and decompression of string data in java

Another example of correct compression and decompression:

@Slf4j
public class GZIPCompression {
    public static byte[] compress(final String stringToCompress) {
        if (isNull(stringToCompress) || stringToCompress.length() == 0) {
            return null;
        }

        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOutput = new GZIPOutputStream(baos)) {
            gzipOutput.write(stringToCompress.getBytes(UTF_8));
            gzipOutput.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while compression!", e);
        }
    }

    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }
}

jQuery multiselect drop down menu

I've used jQuery MultiSelect for implementing multiselect drop down menu with checkbox. You can see the implementation guide from here - Multi-select Dropdown List with Checkbox

Implementation is very simple, need only using the following code.

$('#transactionType').multiselect({
    columns: 1,
    placeholder: 'Select Transaction Type'
});

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

ImportError: No module named 'encodings'

I got this error when try to launch MySql Workbench 8.0 on my macOS Catalina 10.15.3.

I solved this issue by installing Python 3.7 on my system.

I guess in future, when Workbench will have version greater than 8, it will require newer version of Python. Just look at the library path in the error and you will find required version.

HTML5 Form Input Pattern Currency Format

Another answer for this would be

^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$

This will match a string of:

  • one or more numbers with out the decimal place (\d+)
  • any number of commas each of which must be followed by 3 numbers and have upto 3 numbers before it (\d{1,3})(\,\d{3}|)*

Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)

Can Android do peer-to-peer ad-hoc networking?

In addition to Telmo Marques answer: I use Virtual Router for this.

Like connectify it creates an accesspoint on your Windows 8, Windows 7 or 2008 R2 machine, but it's open-source.

how to change directory using Windows command line

The "cd" command changes the directory, but not what drive you are working with. So when you go "cd d:\temp", you are changing the D drive's directory to temp, but staying in the C drive.

Execute these two commands:

D:
cd temp

That will get you the results you want.

Changing ImageView source

Just write a method for changing imageview

public void setImage(final Context mContext, final ImageView imageView, int picture)
{
    if (mContext != null && imageView != null)
    {
        try
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture, mContext.getApplicationContext().getTheme()));
            } else
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture));
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

jQuery table sort

This is a nice way of sorting a table:

_x000D_
_x000D_
$(document).ready(function () {_x000D_
                $('th').each(function (col) {_x000D_
                    $(this).hover(_x000D_
                            function () {_x000D_
                                $(this).addClass('focus');_x000D_
                            },_x000D_
                            function () {_x000D_
                                $(this).removeClass('focus');_x000D_
                            }_x000D_
                    );_x000D_
                    $(this).click(function () {_x000D_
                        if ($(this).is('.asc')) {_x000D_
                            $(this).removeClass('asc');_x000D_
                            $(this).addClass('desc selected');_x000D_
                            sortOrder = -1;_x000D_
                        } else {_x000D_
                            $(this).addClass('asc selected');_x000D_
                            $(this).removeClass('desc');_x000D_
                            sortOrder = 1;_x000D_
                        }_x000D_
                        $(this).siblings().removeClass('asc selected');_x000D_
                        $(this).siblings().removeClass('desc selected');_x000D_
                        var arrData = $('table').find('tbody >tr:has(td)').get();_x000D_
                        arrData.sort(function (a, b) {_x000D_
                            var val1 = $(a).children('td').eq(col).text().toUpperCase();_x000D_
                            var val2 = $(b).children('td').eq(col).text().toUpperCase();_x000D_
                            if ($.isNumeric(val1) && $.isNumeric(val2))_x000D_
                                return sortOrder == 1 ? val1 - val2 : val2 - val1;_x000D_
                            else_x000D_
                                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;_x000D_
                        });_x000D_
                        $.each(arrData, function (index, row) {_x000D_
                            $('tbody').append(row);_x000D_
                        });_x000D_
                    });_x000D_
                });_x000D_
            });
_x000D_
            table, th, td {_x000D_
            border: 1px solid black;_x000D_
        }_x000D_
        th {_x000D_
            cursor: pointer;_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
        <tr><th>id</th><th>name</th><th>age</th></tr>_x000D_
        <tr><td>1</td><td>Julian</td><td>31</td></tr>_x000D_
        <tr><td>2</td><td>Bert</td><td>12</td></tr>_x000D_
        <tr><td>3</td><td>Xavier</td><td>25</td></tr>_x000D_
        <tr><td>4</td><td>Mindy</td><td>32</td></tr>_x000D_
        <tr><td>5</td><td>David</td><td>40</td></tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/

The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code

How to run .NET Core console app from the command line

If it's a framework-dependent application (the default), you run it by dotnet yourapp.dll.

If it's a self-contained application, you run it using yourapp.exe on Windows and ./yourapp on Unix.

For more information about the differences between the two app types, see the .NET Core Application Deployment article on .Net Docs.

How to get the current logged in user Id in ASP.NET Core

As stated somewhere in this post, the GetUserId() method has been moved to the UserManager.

private readonly UserManager<ApplicationUser> _userManager;

public YourController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

public IActionResult MyAction()
{
    var userId = _userManager.GetUserId(HttpContext.User);

    var model = GetSomeModelByUserId(userId);

    return View(model);
}

If you started an empty project you might need to add the UserManger to your services in startup.cs. Otherwise this should already be the case.

Conversion from Long to Double in Java

As already mentioned, you can simply cast long to double. But be careful with long to double conversion because long to double is a narrowing conversion in java.

Conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.

e.g. following program will print 1 not 0

    long number = 499999999000000001L;
    double converted = (double) number;
    System.out.println( number - (long) converted);

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

A good place to start is the IE Standards Support Documentation.

Here is how to target IE10 in JavaScript:

if ("onpropertychange" in document && !!window.matchMedia) {
...
}

Here is how to target IE10 in CSS:

@media all and (-ms-high-contrast: none) {
...
}

In case IE11 needs to be filtered or reset via CSS, see another question: How to write a CSS hack for IE 11?

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Display back button on action bar

In my case; I just had to add android:parentActivityName attr to my activity like this:

<activity
 android:name=".AboutActivity"
 android:label="@string/title_activity_about"
 android:parentActivityName=".MainActivity" />

and the back button appears and works as expected.

Add a new line to a text file in MS-DOS

Maybe this is what you want?

echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt

results in the following within test.txt:

foo

bar

Two models in one view in ASP MVC 3

Another option which doesn't have the need to create a custom Model is to use a Tuple<>.

@model Tuple<Person,Order>

It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.

Nodejs convert string into UTF-8

Use the utf8 module from npm to encode/decode the string.

Installation:

npm install utf8

In a browser:

<script src="utf8.js"></script>

In Node.js:

const utf8 = require('utf8');

API:

Encode:

utf8.encode(string)

Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)

// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// ? '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// ? '\xF0\x90\x80\x81'

Decode:

utf8.decode(byteString)

Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)

utf8.decode('\xC2\xA9');
// ? '\xA9'

utf8.decode('\xF0\x90\x80\x81');
// ? '\uD800\uDC01'
// ? U+10001 LINEAR B SYLLABLE B038 E

Resources

pandas dataframe convert column type to string or categorical

You need astype:

df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)

For converting to categorical:

df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')

Another solution is Categorical:

df['zipcode'] = pd.Categorical(df.zipcode)

Sample with data:

import pandas as pd

df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot  zipcode
722         3.25         4     2.0         4670     51836    98005
2680        0.75         2     1.0         1440      3700    98107
14554       2.50         4     2.0         3180      9603    98155
17384       1.50         2     3.0         1430      1650    98125
18754       1.00         2     1.0         1130      2640    98109

print (df.dtypes)
bathrooms      float64
bedrooms         int64
floors         float64
sqft_living      int64
sqft_lot         int64
zipcode          int64
dtype: object

df['zipcode'] = df.zipcode.astype('category')

print (df)
       bathrooms  bedrooms  floors  sqft_living  sqft_lot zipcode
722         3.25         4     2.0         4670     51836   98005
2680        0.75         2     1.0         1440      3700   98107
14554       2.50         4     2.0         3180      9603   98155
17384       1.50         2     3.0         1430      1650   98125
18754       1.00         2     1.0         1130      2640   98109

print (df.dtypes)
bathrooms       float64
bedrooms          int64
floors          float64
sqft_living       int64
sqft_lot          int64
zipcode        category
dtype: object

What is the proper way to check and uncheck a checkbox in HTML5?

Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery

When getting/setting checkbox state, one may encounter these phenomenons:

.trigger("click");

Does check an unchecked checkbox, but do not add the checked attribute. If you use triggers, do not try to get the state with "checked" attribute.

.attr("checked", "");

Does not uncheck the checkbox...

How to multiply values using SQL

Here it is:

select player_name, player_salary, (player_salary * 1.1) as player_newsalary
from player 
order by player_name, player_salary, player_newsalary desc

You don't need to "group by" if there is only one instance of a player in the table.

How to disable and then enable onclick event on <div> with javascript

To enable use bind() method

$("#id").bind("click",eventhandler);

call this handler

 function  eventhandler(){
      alert("Bind click")
    }

To disable click useunbind()

$("#id").unbind("click");

How to access the contents of a vector from a pointer to the vector in C++?

Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:

#include <iostream>
#include <vector>

using namespace std;

void foo(vector<int>* a)
{
    cout << a->at(0) << a->at(1) << a->at(2) << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(&a);
}

While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.

Here's the references version of the above program:

#include <iostream>
#include <vector>

using namespace std;

void foo(const vector<int>& a)
{
    cout << a[0] << a[1] << a[2] << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(a);
}

As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.

Error handling with PHPMailer

In PHPMailer.php, there are lines as below:

echo $e->getMessage()

Just comment these lines and you will be good to go.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

How do I control how Emacs makes backup files?

Emacs backup/auto-save files can be very helpful. But these features are confusing.

Backup files

Backup files have tildes (~ or ~9~) at the end and shall be written to the user home directory. When make-backup-files is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file.

No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below).

To create backups explicitly use save-buffer (C-x C-s) with prefix arguments.

diff-backup and dired-diff-backup compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file

C:\Users\USERNAME\.emacs.d\backups\!drive_c!Users!USERNAME!.emacs.el.~7~

it has to be manually copied as

C:\Users\USERNAME\.emacs.el

Auto-save files

Auto-save files use hashmarks (#) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience).

  • Before the user presses C-x C-s (save-buffer) to save a file Emacs auto-saves files - based on counting keystrokes (auto-save-interval) or when you stop typing (auto-save-timeout).
  • Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command.

When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist.

Use revert-buffer or recover-file to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named ~/.emacs.d/auto-save-list. The recover-session function will use this information.

The preferred method to recover from an auto-saved filed is M-x revert-buffer RET. Emacs will ask either "Buffer has been auto-saved recently. Revert from auto-save file?" or "Revert buffer from file FILENAME?". In case of the latter there is no auto-save file. For example, because you have saved before typing another auto-save-intervall keystrokes, in which case Emacs had deleted the auto-save file.

Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.

Configuration

Here is a configuration that IMHO works best:

(defvar --backup-directory (concat user-emacs-directory "backups"))
(if (not (file-exists-p --backup-directory))
        (make-directory --backup-directory t))
(setq backup-directory-alist `(("." . ,--backup-directory)))
(setq make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash t
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

Sensitive data

Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use this mode on a per-file basis. As this is a minor mode, for my purposes I renamed it sensitive-minor-mode.

To enable it for all .vcf and .gpg files, in your .emacs use something like:

(setq auto-mode-alist
      (append
       (list
        '("\\.\\(vcf\\|gpg\\)$" . sensitive-minor-mode)
        )
       auto-mode-alist))

Alternatively, to protect only some files, like some .txt files, use a line like

// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-

in the file.

How do you use math.random to generate random ints?

As an alternative, if there's not a specific reason to use Math.random(), use Random.nextInt():

import java.util.Random;

Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.

How to install maven on redhat linux

Installing maven in Amazon Linux / redhat

--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

-->sudo yum install -y apache-maven

--> mvn --version

Output looks like


Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"

*If its thrown error related to java please follow the below step to update java 8 *

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

It's permission problem. It is not "classic" read/write permissions of apache user, but selinux one.

Apache cannot write to files labeled as httpd_sys_content_t they can be only read by apache.

You have 2 possibilities:

  1. label svn repository files as httpd_sys_content_rw_t:

    chcon -R -t httpd_sys_content_rw_t /path/to/your/svn/repo
    
  2. set selinux boolean httpd_unified --> on

    setsebool -P httpd_unified=1
    

I prefer 2nd possibility. You can play also with other selinux booleans connected with httpd:

getsebool -a | grep httpd

Reorder HTML table rows using drag-and-drop

I working well with it

<script>
    $(function () {

        $("#catalog tbody tr").draggable({
            appendTo:"body",
            helper:"clone"
        });
        $("#cart tbody").droppable({
            activeClass:"ui-state-default",
            hoverClass:"ui-state-hover",
            accept:":not(.ui-sortable-helper)",
            drop:function (event, ui) {
                $('.placeholder').remove();
                row = ui.draggable;
                $(this).append(row);
            }
        });
    });
</script>

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

How do I start/stop IIS Express Server?

Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.

using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;

public static class IisExpress
{
  #region Parameters
  public static string SiteFolder = @"C:\temp\UE_Soln_7\Spc.Frm.Imp";
  public static uint Port = 3001;
  public static int ProcessStateChangeDelay = 10 * 1000;
  public static string IisExpressExe = @"C:\Program Files (x86)\IIS Express\iisexpress.exe";
  #endregion

  public static void Start()
  {
    Process.Start(InvocationInfo);
    Thread.Sleep(ProcessStateChangeDelay);
  }
  public static void Stop()
  {
    var p = GetWin32Process();
    if (p == null) return;

    var pp = Process.GetProcessById((int)p.ProcessId);
    if (pp == null) return;

    pp.Kill();
    Thread.Sleep(ProcessStateChangeDelay);
  }
  public static bool IsStarted()
  {
    var p = GetWin32Process();
    return p != null;
  }

  static readonly string ProcessName = Path.GetFileName(IisExpressExe);
  static string Quote(string value) { return "\"" + value.Trim() + "\""; }
  static string CmdLine =
    string.Format(
      @"/path:{0} /port:{1}",
      Quote(SiteFolder),
      Port
      );
  static readonly ProcessStartInfo InvocationInfo =
    new ProcessStartInfo()
      {
        FileName = IisExpressExe,
        Arguments = CmdLine,
        WorkingDirectory = SiteFolder,
        CreateNoWindow = false,
        UseShellExecute = true,
        WindowStyle = ProcessWindowStyle.Minimized
      };
  static Win32Process GetWin32Process()
  {
    //the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
    using (var mo = new ManagementObjectContext())
      foreach (var p in mo.CIMv2.Win32Processes)
        if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
          return p;
    return null;
  }
}

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.

UITableView - change section header color

Here's how to change the text color.

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];

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

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

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

This Works For me !!!

Call a Function without Parameter

$("#CourseSelect").change(function(e1) {
   loadTeachers();
});

Call a Function with Parameter

$("#CourseSelect").change(function(e1) {
    loadTeachers($(e1.target).val());
});

Bootstrap 3: How do you align column content to bottom of row

You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:

.bottom-column
{
    float: none;
    display: table-cell;
    vertical-align: bottom;
}

Working example here.

Also, this might be a possible duplicate question.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

tl;dr

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

Details

I have a java.util.Date in the format yyyy-mm-dd

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.

java.time

The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();

2017-01-23

If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Android notification is not showing

The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:

.setSmallIcon(R.drawable.icon)

Android Oreo (8.0) and above

Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.

private NotificationManager mNotificationManager;

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");

mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);

mNotificationManager =
    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
    String channelId = "Your_channel_id";
    NotificationChannel channel = new NotificationChannel(
                                        channelId,
                                        "Channel human readable title",
                                        NotificationManager.IMPORTANCE_HIGH);
   mNotificationManager.createNotificationChannel(channel);
  mBuilder.setChannelId(channelId);
}

mNotificationManager.notify(0, mBuilder.build());

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

Where could I buy a valid SSL certificate?

Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.

All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.

There are many clients you can use to install a Let's Encrypt certificate:

Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/

Printing leading 0's in C

You place a zero before the minimum field width:

printf("%05d", zipcode);

How to wait until an element is present in Selenium?

FluentWait throws a NoSuchElementException is case of the confusion

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

The import com.google.android.gms cannot be resolved

In my case only after I added gcm.jar to lib folder, it started to work. It was here: C:\adt-bundle-windows-x86_64-20131030\sdk\extras\google\gcm\gcm-client\dist

So the google-play-services.jar didn't work...

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

  • ECB should not be used if encrypting more than one block of data with the same key.

  • CBC, OFB and CFB are similar, however OFB/CFB is better because you only need encryption and not decryption, which can save code space.

  • CTR is used if you want good parallelization (ie. speed), instead of CBC/OFB/CFB.

  • XTS mode is the most common if you are encoding a random accessible data (like a hard disk or RAM).

  • OCB is by far the best mode, as it allows encryption and authentication in a single pass. However there are patents on it in USA.

The only thing you really have to know is that ECB is not to be used unless you are only encrypting 1 block. XTS should be used if you are encrypting randomly accessed data and not a stream.

  • You should ALWAYS use unique IV's every time you encrypt, and they should be random. If you cannot guarantee they are random, use OCB as it only requires a nonce, not an IV, and there is a distinct difference. A nonce does not drop security if people can guess the next one, an IV can cause this problem.

How can I manually generate a .pyc file from a .py file

I would use compileall. It works nicely both from scripts and from the command line. It's a bit higher level module/tool than the already mentioned py_compile that it also uses internally.

Make footer stick to bottom of page correctly

the easiest hack is to set a min-height to your page container at 400px assuming your footer come at the end. you dont even have to put css for the footer or just a width:100% assuming your footer is direct child of your <body>

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

Detect IF hovering over element with jQuery

Original (And Correct) Answer:

You can use is() and check for the selector :hover.

var isHovered = $('#elem').is(":hover"); // returns true or false

Example: http://jsfiddle.net/Meligy/2kyaJ/3/

(This only works when the selector matches ONE element max. See Edit 3 for more)

.

Edit 1 (June 29, 2013): (Applicable to jQuery 1.9.x only, as it works with 1.10+, see next Edit 2)

This answer was the best solution at the time the question was answered. This ':hover' selector was removed with the .hover() method removal in jQuery 1.9.x.

Interestingly a recent answer by "allicarn" shows it's possible to use :hover as CSS selector (vs. Sizzle) when you prefix it with a selector $($(this).selector + ":hover").length > 0, and it seems to work!

Also, hoverIntent plugin mentioned in a another answer looks very nice as well.

Edit 2 (September 21, 2013): .is(":hover") works

Based on another comment I have noticed that the original way I posted, .is(":hover"), actually still works in jQuery, so.

  1. It worked in jQuery 1.7.x.

  2. It stopped working in 1.9.1, when someone reported it to me, and we all thought it was related to jQuery removing the hover alias for event handling in that version.

  3. It worked again in jQuery 1.10.1 and 2.0.2 (maybe 2.0.x), which suggests that the failure in 1.9.x was a bug or so not an intentional behaviour as we thought in the previous point.

If you want to test this in a particular jQuery version, just open the JSFidlle example at the beginning of this answer, change to the desired jQuery version and click "Run". If the colour changes on hover, it works.

.

Edit 3 (March 9, 2014): It only works when the jQuery sequence contains a single element

As shown by @Wilmer in the comments, he has a fiddle which doesn't even work against jQuery versions I and others here tested it against. When I tried to find what's special about his case I noticed that he was trying to check multiple elements at a time. This was throwing Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover.

So, working with his fiddle, this does NOT work:

var isHovered = !!$('#up, #down').filter(":hover").length;

While this DOES work:

var isHovered = !!$('#up,#down').
                    filter(function() { return $(this).is(":hover"); }).length;

It also works with jQuery sequences that contain a single element, like if the original selector matched only one element, or if you called .first() on the results, etc.

This is also referenced at my JavaScript + Web Dev Tips & Resources Newsletter.

How to assign from a function which returns more than one value?

I somehow stumbled on this clever hack on the internet ... I'm not sure if it's nasty or beautiful, but it lets you create a "magical" operator that allows you to unpack multiple return values into their own variable. The := function is defined here, and included below for posterity:

':=' <- function(lhs, rhs) {
  frame <- parent.frame()
  lhs <- as.list(substitute(lhs))
  if (length(lhs) > 1)
    lhs <- lhs[-1]
  if (length(lhs) == 1) {
    do.call(`=`, list(lhs[[1]], rhs), envir=frame)
    return(invisible(NULL)) 
  }
  if (is.function(rhs) || is(rhs, 'formula'))
    rhs <- list(rhs)
  if (length(lhs) > length(rhs))
    rhs <- c(rhs, rep(list(NULL), length(lhs) - length(rhs)))
  for (i in 1:length(lhs))
    do.call(`=`, list(lhs[[i]], rhs[[i]]), envir=frame)
  return(invisible(NULL)) 
}

With that in hand, you can do what you're after:

functionReturningTwoValues <- function() {
  return(list(1, matrix(0, 2, 2)))
}
c(a, b) := functionReturningTwoValues()
a
#[1] 1
b
#     [,1] [,2]
# [1,]    0    0
# [2,]    0    0

I don't know how I feel about that. Perhaps you might find it helpful in your interactive workspace. Using it to build (re-)usable libraries (for mass consumption) might not be the best idea, but I guess that's up to you.

... you know what they say about responsibility and power ...

How to set background color of a View

In kotlin you could do it like this:

val backgroundColor = R.color.whatever_color_you_like
view.setBackgroundColor(getColorCompat(backgroundColor))

Where getColorCompat() is an extension function:

/**
 * Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.
 */

 fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)

Convert List to Pandas Dataframe Column

For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.

There are Different Ways to Perform the Above Operation.

import pandas as pd

  1. pd.DataFrame({'Column_Name':Column_Data})
  • Column_Name : String
  • Column_Data : List Form
  1. Data = pd.DataFrame(Column_Data)

    Data.columns = ['Column_Name']

So, for the above mentioned issue, the code snippet is

import pandas as pd

Content = ['Thanks You',
           'Its fine no problem',
           'Are you sure']

Data = pd.DataFrame({'Text': Content})

How to align input forms in HTML

Well for the very basics you can try aligning them in the table. However the use of table is bad for layout since table is meant for contents.

What you can use is CSS floating techniques.

CSS Code

.styleform label{float:left;}
.styleform input{margin-left:200px;} /* this gives space for the label on the left */
.styleform .clear{clear:both;} /* prevent elements from stacking weirdly */

HTML

<div class="styleform">
<form>
<label>First Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Last Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Email:</label><input type="text" name="first" /><div class="clear"></div>
</form>
</div>

An elaborated article I wrote can be found answering the question of IE7 float problem: IE7 float right problems

Automatically deleting related rows in Laravel (Eloquent ORM)

It is better if you override the delete method for this. That way, you can incorporate DB transactions within the delete method itself. If you use the event way, you will have to cover your call of delete method with a DB transaction every time you call it.

In your User model.

public function delete()
{
    \DB::beginTransaction();

     $this
        ->photo()
        ->delete()
    ;

    $result = parent::delete();

    \DB::commit();

    return $result;
}

Excel formula to reference 'CELL TO THE LEFT'

As this was the only way to answer @zipper

The reason why your formula:

="OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)=""xyz"""

doesn't conditionally format, is because the formula litteraly asks ="THIS PHRASE" is equal to "THAT PHRASE", try writing it like this: =OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())),0,-1)="xyz" where "xyz" is your Text and "-1" is the number of columns to the left you want to search.

How do I create an abstract base class in JavaScript?

Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:

(function(){

    var FLAG_ABSTRACT = function(__class){

        throw "Error: Trying to instantiate an abstract class:"+__class
    }

    var Class = function (){

        Class.prototype.constructor = new FLAG_ABSTRACT("Class");       
    }

    //will throw exception
    var  foo = new Class();

})()

How to create an instance of System.IO.Stream stream

You have to create an instance of one of the subclasses. Stream is an abstract class that can't be instantiated directly.

There are a bunch of choices if you look at the bottom of the reference here:

Stream Class | Microsoft Developer Network

The most common probably being FileStream or MemoryStream. Basically, you need to decide where you wish the data backing your stream to come from, then create an instance of the appropriate subclass.

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

Edit:

$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig'; 

Change into:

$Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

Then https://kamalkaur188.wordpress.com/category/removing-error-1146-table-phpmyadmin-pma_recent-doesnt-exist/ work for me.

What is the difference between "INNER JOIN" and "OUTER JOIN"?

  • Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.

  • Left outer join - A left outer join will give all rows in A, plus any common rows in B.

  • Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versay

How do I change the select box arrow

Working with just one selector:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

fiddler

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

Docker Error bind: address already in use

docker-compose down --rmi all 

and then restart your computer

Extracting text from HTML file using Python

NOTE: NTLK no longer supports clean_html function

Original answer below, and an alternative in the comments sections.


Use NLTK

I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK.
It works magically.

import nltk   
from urllib import urlopen

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"    
html = urlopen(url).read()    
raw = nltk.clean_html(html)  
print(raw)

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

How to use .htaccess in WAMP Server?

click: WAMP icon->Apache->Apache modules->chose rewrite_module

and do restart for all services.

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

Add text at the end of each line

Concise version of the sed command:

sed -i s/$/:80/ file.txt

Explanation:

  • sed stream editor
    • -i in-place (edit file in place)
    • s substitution command
    • /replacement_from_reg_exp/replacement_to_text/ statement
    • $ matches the end of line (replacement_from_reg_exp)
    • :80 text you want to add at the end of every line (replacement_to_text)
  • file.txt the file name

How to git-svn clone the last n revisions from a Subversion repository?

You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD).

For example: git svn clone -s -r1450:HEAD some/svn/repo

Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.

How to create windows service from java jar?

Use nssm.exe but remember to set the AppDirectory or any required libraries or resources will not be accessible. By default nssm set the current working directory to the that of the application, java.exe, not the jar. So do this to create a batch script:

    pushd <path-to-jar>
    nssm.exe install "<service-name>" "<path-to-java.exe>" "-jar <name-of-jar>"
    nssm.exe set "<service-name>" AppDirectory "<path-to-jar>"

This should fix the service paused issue.

How to display a confirmation dialog when clicking an <a> link?

You can also try this:

<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
    Link Text
</a>

Expand a random range from 1–5 to 1–7

There you go, uniform distribution and zero rand5 calls.

def rand7:
    seed += 1
    if seed >= 7:
        seed = 0
    yield seed

Need to set seed beforehand.

Initialize value of 'var' in C# to null

var variables still have a type - and the compiler error message says this type must be established during the declaration.

The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:

var x = (String)null;

Which is still "type inferred" and equivalent to:

String x = null;

The compiler will not accept var x = null because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null would "work" although it is of questionable usefulness.

Generally, when I can't use var's type inference correctly then

  1. I am at a place where it's best to declare the variable explicitly; or
  2. I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

The second approach can be done by moving code into methods or functions.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

This work for me:

 $('#data_compra').daterangepicker({
          singleDatePicker: true,
          locale: {
           format: 'DD/MM/YYYY'
          },
         calender_style: "picker_4", }, 
function(start, end, label) {
          console.log(start.toISOString(), end.toISOString(), label); 
});

pip install access denied on Windows

In my case, it didn't even work with python -m pip install

What I have done is, from a cmd as administrator:

PsExec.exe -i -s -d cmd.exe

In order to spawn a SYSTEM cmd, then pip install mitmproxy

;)

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

Using variable in SQL LIKE statement

DECLARE @SearchLetter2 char(1)

Set this to a longer char.

jQuery send HTML data through POST

_x000D_
_x000D_
jQuery.post(post_url,{ content: "John" } )_x000D_
 .done(function( data ) {_x000D_
   _x000D_
   _x000D_
 });_x000D_
 
_x000D_
_x000D_
_x000D_

I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check

_x000D_
_x000D_
ob_start();_x000D_
        _x000D_
   include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
   $content = ob_get_clean();_x000D_
   _x000D_
  _x000D_
  _x000D_
    $test = $_SESSION['content'] ;_x000D_
  _x000D_
   require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 );   _x000D_
    $html2pdf->setDefaultFont('Arial');_x000D_
    $html2pdf->WriteHTML($test);
_x000D_
_x000D_
_x000D_

Why is __dirname not defined in node REPL?

As @qiao said, you can't use __dirname in the node repl. However, if you need need this value in the console, you can use path.resolve() or path.dirname(). Although, path.dirname() will just give you a "." so, probably not that helpful. Be sure to require('path').

How do I clear only a few specific objects from the workspace?

Use the following command

remove(list=c("data_1", "data_2", "data_3"))

Laravel Checking If a Record Exists

In laravel eloquent, has default exists() method, refer followed example.

if(User::where('id', $user_id )->exists()){ // your code... }

Disable single warning error

Use #pragma warning ( push ), then #pragma warning ( disable ), then put your code, then use #pragma warning ( pop ) as described here:

#pragma warning( push )
#pragma warning( disable : WarningCode)
// code with warning
#pragma warning( pop ) 

Declaring a variable and setting its value from a SELECT query in Oracle

For storing a single row output into a variable from the select into query :

declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';

this will store the value of a single record into the variable v_username.


For storing multiple rows output into a variable from the select into query :

you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;

Get JSON Data from URL Using Android?

    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
}
Gson gson = new Gson();

JSONObject jsonObject = new JSONObject(s.toString());
String link = jsonObject.getString("Result");

In Windows cmd, how do I prompt for user input and use the result in another command?

Try this:

@echo off
set /p id="Enter ID: "

You can then use %id% as a parameter to another batch file like jstack %id%.

For example:

set /P id=Enter id: 
jstack %id% > jstack.txt

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is is identity testing and == is equality testing. This means is is a way to check whether two things are the same things, or just equivalent.

Say you've got a simple person object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23-year-old Jack, but it's not the same person.

class Person(object):
   def __init__(self, name, age):
       self.name = name
       self.age = age

   def __eq__(self, other):
       return self.name == other.name and self.age == other.age

jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)

jack1 == jack2 # True
jack1 is jack2 # False

They're the same age, but they're not the same instance of person. A string might be equivalent to another, but it's not the same object.

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

How do I decode a string with escaped unicode?

Using JSON.decode for this comes with significant drawbacks that you must be aware of:

  • You must wrap the string in double quotes
  • Many characters are not supported and must be escaped themselves. For example, passing any of the following to JSON.decode (after wrapping them in double quotes) will error even though these are all valid: \\n, \n, \\0, a"a
  • It does not support hexadecimal escapes: \\x45
  • It does not support Unicode code point sequences: \\u{045}

There are other caveats as well. Essentially, using JSON.decode for this purpose is a hack and doesn't work the way you might always expect. You should stick with using the JSON library to handle JSON, not for string operations.


I recently ran into this issue myself and wanted a robust decoder, so I ended up writing one myself. It's complete and thoroughly tested and is available here: https://github.com/iansan5653/unraw. It mimics the JavaScript standard as closely as possible.

Explanation:

The source is about 250 lines so I won't include it all here, but essentially it uses the following Regex to find all escape sequences and then parses them using parseInt(string, 16) to decode the base-16 numbers and then String.fromCodePoint(number) to get the corresponding character:

/\\(?:(\\)|x([\s\S]{0,2})|u(\{[^}]*\}?)|u([\s\S]{4})\\u([^{][\s\S]{0,3})|u([\s\S]{0,4})|([0-3]?[0-7]{1,2})|([\s\S])|$)/g

Commented (NOTE: This regex matches all escape sequences, including invalid ones. If the string would throw an error in JS, it throws an error in my library [ie, '\x!!' will error]):

/
\\ # All escape sequences start with a backslash
(?: # Starts a group of 'or' statements
(\\) # If a second backslash is encountered, stop there (it's an escaped slash)
| # or
x([\s\S]{0,2}) # Match valid hexadecimal sequences
| # or
u(\{[^}]*\}?) # Match valid code point sequences
| # or
u([\s\S]{4})\\u([^{][\s\S]{0,3}) # Match surrogate code points which get parsed together
| # or
u([\s\S]{0,4}) # Match non-surrogate Unicode sequences
| # or
([0-3]?[0-7]{1,2}) # Match deprecated octal sequences
| # or
([\s\S]) # Match anything else ('.' doesn't match newlines)
| # or
$ # Match the end of the string
) # End the group of 'or' statements
/g # Match as many instances as there are

Example

Using that library:

import unraw from "unraw";

let step1 = unraw('http\\u00253A\\u00252F\\u00252Fexample.com');
// yields "http%3A%2F%2Fexample.com"
// Then you can use decodeURIComponent to further decode it:
let step2 = decodeURIComponent(step1);
// yields http://example.com

Interview Question: Merge two sorted singly linked lists without creating new nodes

Node mergeList(Node h1, Node h2) {
    if (h1 == null) return h2;
    if (h2 == null) return h1;
    Node head;
    if (h1.data < h2.data) {
        head = h1;
    } else {
        head = h2;
        h2 = h1;
        h1 = head;
    }

    while (h1.next != null && h2 != null) {
        if (h1.next.data < h2.data) {
            h1 = h1.next;
        } else {
            Node afterh2 = h2.next;
            Node afterh1 = h1.next;
            h1.next = h2;
            h2.next = afterh1;

            if (h2.next != null) {
                h2 = afterh2;
            }
        }
    }
    return head;
}

How to format a string as a telephone number in C#

You can try {0: (000) 000-####} if your target number starts with 0.

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.

Wait some seconds without blocking UI execution

In my case I needed to do this because I had passed a method to the thread I was waiting for and that caused the lock becuase the metod was run on the GUI thread and the thread code called that method sometimes.

Task<string> myTask = Task.Run(() => {
    // Your code or method call
    return "Maybe you want to return other datatype, then just change it.";
});
// Some other code maybe...
while (true)
{
    myTask.Wait(10);
    Application.DoEvents();
    if (myTask.IsCompleted) break;
}

How to check if object has been disposed in C#

The reliable solution is catching the ObjectDisposedException.

The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.

Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.

How to kill zombie process

I tried

kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')

and it works for me.

Set value of hidden input with jquery

$('input[name="testing"]').val(theValue);

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

In my case I cloned a git-project where both Java and Kotlin included. Then checked another branch and pressed "Sync Project with Gradle Files". Android Studio 3.0.1.

CSS: fixed to bottom and centered

A jQuery solution

$(function(){
    $(window).resize(function(){
        placeFooter();
    });
    placeFooter();
    // hide it before it's positioned
    $('#footer').css('display','inline');
});

function placeFooter() {    
    var windHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var offset = parseInt(windHeight) - parseInt(footerHeight);
    $('#footer').css('top',offset);
}

<div id='footer' style='position: fixed; display: none;'>I am a footer</div>

Sometimes it's easier to implement JS than to hack old CSS.

http://jsfiddle.net/gLhEZ/

Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

If is VSCode see the workspace. If you are in other workspace this error can rise

How to show full object in Chrome console?

You might get better results if you try:

console.log(JSON.stringify(functor));

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

in my case, the version of wheel/pip/setuptools created by venv is too old. this works:

venv/bin/pip  install --upgrade pip wheel setuptools

Converting a string to an integer on Android

You can use the following to parse a string to an integer:

int value=Integer.parseInt(textView.getText().toString());

(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.

(2) input: "abdul" then it will throw an exception that is NumberFormatException. So to solve this we need to use try catch as I have mention below:

  int tax_amount=20;
  EditText edit=(EditText)findViewById(R.id.editText1);
     try
       {

        int value=Integer.parseInt(edit.getText().toString());
        value=value+tax_amount;
        edit.setText(String.valueOf(value));// to convert integer to string 

       }catch(NumberFormatException ee){
       Log.e(ee.toString());
       }

You may also want to refer to the following link for more information: http://developer.android.com/reference/java/lang/Integer.html

How to upgrade scikit-learn package in anaconda

Updating a Specific Library - scikit-learn:

Anaconda (conda):

conda install scikit-learn

Pip Installs Packages (pip):

pip install --upgrade scikit-learn

Verify Update:

conda list scikit-learn

It should now display the current (and desired) version of the scikit-learn library.

For me personally, I tried using the conda command to update the scikit-learn library and it acted as if it were installing the latest version to then later discover (with an execution of the conda list scikit-learn command) that it was the same version as previously and never updated (or recognized the update?). When I used the pip command, it worked like a charm and correctly updated the scikit-learn library to the latest version!

Hope this helps!

More in-depth details of latest version can be found here (be mindful this applies to the scikit-learn library version of 0.22):

printf with std::string?

Use std::printf and c_str() example:

std::printf("Follow this command: %s", myString.c_str());

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

What is the difference between a JavaBean and a POJO?

POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO

JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.

All Javabeans are POJOs but all POJO are not Javabeans

How do I refresh the page in ASP.NET? (Let it reload itself by code)

Once the page is rendered to the client you have only two ways of forcing a refresh. One is Javascript

setTimeout("location.reload(true);", timeout);

The second is a Meta tag:

<meta http-equiv="refresh" content="600">

You can set the refresh intervals on the server side.

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

How to retrieve JSON Data Array from ExtJS Store

I always use store.proxy.reader.jsonData or store.proxy.reader.rawData

For example - this return the items nested into a root node called 'data':

var some_store = Ext.data.StoreManager.lookup('some_store_id');
Ext.each(some_store.proxy.reader.rawData.data, function(obj, i){
   console.info(obj);
});

This only works immediately after a store read-operation (while not been manipulated yet).

Delete multiple rows by selecting checkboxes using PHP

Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as

$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";

Thats one single query to delete them all.

Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.

Angular routerLink does not navigate to the corresponding component

I was using routerlink instead of routerLink.

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

Yahoo Finance API

You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...

You may use this php library to get historical data / quotes using YQL https://github.com/aygee/php-yql-finance

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

Call to a member function fetch_assoc() on boolean in <path>

Please use if condition with while loop and try.

eg.

if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

    }
    /* free result set */
    $result->free();
}

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

How to print a debug log?

I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).

That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

If anyone does decide to us that code, I made one minor change. After

function debug($name, $var = null, $type = LOG) {

I added

$name = 'PHP: ' . $name;

This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

How can I check if PostgreSQL is installed or not via Linux script?

aptitude show postgresql | grep Version worked for me

What is the purpose of the "final" keyword in C++11 for functions?

The final keyword allows you to declare a virtual method, override it N times, and then mandate that 'this can no longer be overridden'. It would be useful in restricting use of your derived class, so that you can say "I know my super class lets you override this, but if you want to derive from me, you can't!".

struct Foo
{
   virtual void DoStuff();
}

struct Bar : public Foo
{
   void DoStuff() final;
}

struct Babar : public Bar
{
   void DoStuff(); // error!
}

As other posters pointed out, it cannot be applied to non-virtual functions.

One purpose of the final keyword is to prevent accidental overriding of a method. In my example, DoStuff() may have been a helper function that the derived class simply needs to rename to get correct behavior. Without final, the error would not be discovered until testing.

Responsive image align center bootstrap 3

So far the best solution to accept seems to be <img class="center-block" ... />. But no one has mentioned how center-block works.

Take Bootstrap v3.3.6 for example:

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

The default value of dispaly for <img> is inline. Value block will display an element as a block element (like <p>). It starts on a new line, and takes up the whole width. In this way, the two margin settings let the image stay in the middle horizontally.

Class has no objects member

Change your linter to - flake8 and problem will go away.

Default value to a parameter while passing by reference in C++

There still is the old C way of providing optional arguments: a pointer that can be NULL when not present:

void write( int *optional = 0 ) {
    if (optional) *optional = 5;
}

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

Populate a datagridview with sql query results

You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.

Error: Argument is not a function, got undefined

?med's second point was my pitfall but just for the record, maybe it's helping someone somewhere:

I had the same problem and just before I went nuts I discovered that I had forgotten to include my controller script.

As my app is based on ASP.Net MVC I decided to keep myself sane by inserting the following snippet in my App_Start/BundleConfig.cs

bundles.Add(new ScriptBundle("~/app").Include(
                "~/app/app.js",
                "~/app/controllers/*.js",
                "~/app/services/*.js" ));

and in Layout.cshtml

<head>
...
   @Scripts.Render("~/app")
...
</head>

Now I won't have to think about including the files manually ever again. In hindsight I really should have done this when setting up the project...

How to deal with SQL column names that look like SQL keywords?

Your question seems to be well answered here, but I just want to add one more comment to this subject.

Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.

More information:

"Reserved keywords should not be used as object names. Databases upgraded from earlier versions of SQL Server may contain identifiers that include words not reserved in the earlier version, but that are reserved words for the current version of SQL Server. You can refer to the object by using delimited identifiers until the name can be changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

and

"If your database does contain names that match reserved keywords, you must use delimited identifiers when you refer to those objects. For more information, see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx

Detect if HTML5 Video element is playing

Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.

$(document).ready(function() {

    var video = $("video#webcast_video");
    if (video.length <= 0) {
        return;
    }

    window.onbeforeunload = function () {
        var htmlVideo = video[0];
        if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
            return null;
        }

        return "Leaving this page will stop your video.";
    };
}

Bootstrap - How to add a logo to navbar class?

I found a solution on another thread that works - use the pull-left class:

 <a href="#" class="pull-left"><img src="/path/to/image.png"></a> 

Thanks to Michael in this thread:

Bootstrap - How to add a logo to navbar class?

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How to Animate Addition or Removal of Android ListView Rows

Take a look at the Google solution. Here is a deletion method only.

ListViewRemovalAnimation project code and Video demonstration

It needs Android 4.1+ (API 16). But we have 2014 outside.

Mythical man month 10 lines per developer day - how close on large projects?

You should stop using this metric, it is meaningless for the most part. Cohesion, coupling and complexity are more important metrics than lines of code.

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

Constructors in Go

another way is;

package person

type Person struct {
    Name string
    Old  int
}

func New(name string, old int) *Person {
    // set only specific field value with field key
    return &Person{
        Name: name,
    }
}

Visual Studio : short cut Key : Duplicate Line

Ctrl + D is a new shortcut introduced in VS 2017 v15.6 that seems to do the exact thing that Ctrl + E, V

Ctrl + D will duplicate the line the cursor is in and insert it right below the line in focus. If you’d like to duplicate a specific set of code, simply select the portion of code you want to duplicate before invoking the duplicate code command.

It won't affect your clipboard

Source

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

*********** PARSE THE RESULT TO JSON OBJECT: JSON.prase(result.arrayOfObjects) ***********

I came to this page after I faced this issue. So, my issue was that the server is sending array of objects in the form of string. It is something like this:

when I printed result on console after getting from server it is string:

'arrayOfObject': '[
                  {'id': '123', 'designation': 'developer'},
                  {'id': '422', 'designation': 'lead'}
               ]'

So, I have to convert this string to JSON after getting it from server. Use method for parsing the result string that you receive from server:

JSON.parse(result.arrayOfObjects)

VBA Public Array : how to?

Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.

So I put an special sub to declare global variables and arrays, something like:

Global example(10) As Variant

Sub set_values()

example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1

End Sub

And whenever I want to use the array, I call the sub first, just in case

call set_values

Msgbox example(5)

Perhaps is not the most correct way, but I hope it works for you

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

How do I tell Spring Boot which main class to use for the executable jar?

I had renamed my project and it was still finding the old Application class on the build path. I removed it in the 'build' folder and all was fine.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

This error message (SCRIPT5: Access is denied.) can also be encountered if the target page of a .replace method is not found (I had entered the page name incorrectly). I know because it just happened to me, which is why I went searching for some more information about the meaning of the error message.

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

Hive External Table Skip First Row

While you have your answer from Daniel, here are some customizations possible using OpenCSVSerde:

CREATE EXTERNAL TABLE `mydb`.`mytable`(
    `product_name` string,
    `brand_id` string,
    `brand` string,
    `color` string,
    `description` string,
    `sale_price` string)
PARTITIONED BY (
    `seller_id` string)
ROW FORMAT SERDE
    'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    'separatorChar' = '\t',
    'quoteChar' = '"',
    'escapeChar' = '\\')
STORED AS INPUTFORMAT
    'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
    'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
    'hdfs://namenode.com:port/data/mydb/mytable'
TBLPROPERTIES (
    'serialization.null.format' = '',
    'skip.header.line.count' = '1')

With this, you have total control over the separator, quote character, escape character, null handling and header handling.

Look here and here.

How to display list items on console window in C#

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));

Error: Segmentation fault (core dumped)

In my case: I forgot to activate virtualenv

I installed "pip install example" in the wrong virtualenv

Laravel 5 - How to access image uploaded in storage within View?

If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/), then you can use my little dirty hack below :p)

 public static function hackoutFileFromStorageFolder($fullfilePath) {
        if (strpos($fullfilePath, 'storage/app/public/')) {
           $fileParts = explode('storage/app/public/', $fullfilePath);
           if( count($fileParts) > 1){
               return $fileParts[1];
           }
        }

        return '';
    }

Using HTML data-attribute to set CSS background-image url

If you wanted to keep it with just HTML and CSS you can use CSS Variables. Keep in mind, css variables aren't supported in IE.

<div class="thumb" style="--background: url('images/img.jpg')"></div> 
.thumb {
    background-image: var(--background);
}

Codepen: https://codepen.io/bruce13/pen/bJdoZW

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

this resolved this issue by adding namespace to Global.asax.cs file.

using System.Web.Http;

this resolved the issue.

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

parseInt with jQuery

var test = parseInt($("#testid").val());

How to set margin of ImageView using code, not xml

In Kotlin you can write it in more pleasant way

myView.layoutParams = LinearLayout.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(12, 12, 12, 12)
            }

How to get GET (query string) variables in Express.js on Node.js?

In express.js you can get it pretty easy, all you need to do in your controller function is:

app.get('/', (req, res, next) => {
   const {id} = req.query;
   // rest of your code here...
})

And that's all, assuming you are using es6 syntax.

PD. {id} stands for Object destructuring, a new es6 feature.

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

Parsing JSON using C

NXJSON is full-featured yet very small (~400 lines of code) JSON parser, which has easy to use API:

const nx_json* json=nx_json_parse_utf8(code);
printf("hello=%s\n", nx_json_get(json, "hello")->text_value);
const nx_json* arr=nx_json_get(json, "my-array");
int i;
for (i=0; i<arr->length; i++) {
  const nx_json* item=nx_json_item(arr, i);
  printf("arr[%d]=(%d) %ld\n", i, (int)item->type, item->int_value);
}
nx_json_free(json);

Driver executable must be set by the webdriver.ie.driver system property

For spring :

File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());

Create normal zip file programmatically

This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

A sample createZipFile() method may look as following:

public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
        {
            try
            {
                using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                {
                    //using the same file name as entry name
                    za.CreateEntryFromFile(inputfile, inputfile);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid input/output file.");
                Environment.Exit(-1);
            }
}

where

  • inputfile= string with the file name to be compressed (for this example, you have to add the extension)
  • outputfile= string with the destination zip file name

More details about ZipFile Class in MSDN

How to add class active on specific li on user click with jQuery

Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:

<li><a [routerLink]="['Dashboard']">Dashboard</a></li>

You can therefore easily style such links using CSS:

.router-link-active {
    color: red;
}

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Include jQuery in the JavaScript Console

this answer based on @genesis answer, at first I tried the bookmark version @jondavidjohn, and it is not working, so I change it to this (add it to your bookmark):

javascript:(function(){var s = document.createElement('script');s.src = "//code.jquery.com/jquery-2.2.4.min.js";document.getElementsByTagName('head')[0].appendChild(s);console.log('jquery loaded')}());

words of caution, is not tested in chrome but work in firefox, and not tested in conflict environment.

Spring RestTemplate timeout

  1. RestTemplate timeout with SimpleClientHttpRequestFactory To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
  1. RestTemplate timeout with HttpComponentsClientHttpRequestFactory SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

reference: Spring RestTemplate timeout configuration example

How to parse a query string into a NameValueCollection in .NET

Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.