Programs & Examples On #Qizmt

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;


var hdr = null ;

What's the difference between SoftReference and WeakReference in Java?

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

Reliable and fast FFT in Java

I'm looking into using SSTJ for FFTs in Java. It can redirect via JNI to FFTW if the library is available or will use a pure Java implementation if not.

How to access the ith column of a NumPy multidimensional array?

And if you want to access more than one column at a time you could do:

>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
       [3, 5],
       [6, 8]])

Turn a number into star rating display using jQuery and CSS

Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?

For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.

Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).

Download history stock prices automatically from yahoo finance in python

It's trivial when you know how:

import yfinance as yf
df ='CVS', '2015-01-01')

If you wish to plot it:

import finplot as fplt

enter image description here

How to enable production mode?

ng build --prod replaces environment.ts with

ng build --prod

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

How can I scroll a div to be visible in ReactJS?

With reacts Hooks:

  1. Import
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
  1. Make new hook:
const divRef = useRef<HTMLDivElement>(null);
  1. Add new Div
<div ref={divRef}/>
  1. Scroll function:
const scrollToDivRef  = () => {
    let node = ReactDOM.findDOMNode(divRef.current) as Element;
    node.scrollIntoView({block: 'start', behavior: 'smooth'});

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

jQuery - hashchange event

Here is updated version of @johnny.rodgers

Hope helps someone.

// ie9 ve ie7 return true but never fire, lets remove ie less then 10
if(("onhashchange" in window) && navigator.userAgent.toLowerCase().indexOf('msie') == -1){ // event supported?
    window.onhashchange = function(){
        var url = window.location.hash.substring(1);
else{ // event not supported:
    var storedhash = window.location.hash;
        if(window.location.hash != storedhash){
            storedhash = window.location.hash;
    }, 100);

Timeout on a function call

Another solution with asyncio :

If you want to cancel the background task and not just timeout on the running main code, then you need an explicit communication from main thread to ask the code of the task to cancel , like a threading.Event()

import asyncio
import functools
import multiprocessing
from concurrent.futures.thread import ThreadPoolExecutor

class SingletonTimeOut:
    pool = None

    def run(cls, to_run: functools.partial, timeout: float):
        pool = cls.get_pool()
        loop = cls.get_loop()
            task = loop.run_in_executor(pool, to_run)
            return loop.run_until_complete(asyncio.wait_for(task, timeout=timeout))
        except asyncio.TimeoutError as e:
            error_type = type(e).__name__ #TODO
            raise e

    def get_pool(cls):
        if cls.pool is None:
            cls.pool = ThreadPoolExecutor(multiprocessing.cpu_count())
        return cls.pool

    def get_loop(cls):
            return asyncio.get_event_loop()
        except RuntimeError:
            # print("NEW LOOP" + str(threading.current_thread().ident))
            return asyncio.get_event_loop()

# ---------------

TIME_OUT = float('0.2')  # seconds

def toto(input_items,nb_predictions):
    return 1

to_run = functools.partial(toto,

results =, TIME_OUT)

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Java String declaration

String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Either use the style attribute to add CSS inline on your divs, e.g.:

<div style="color:red"> ... </div>

... or create your own style sheet and reference it after the existing stylesheet then your style sheet should take precedence.

... or add a <style> element in the <head> of your HTML with the CSS you need, this will take precedence over an external style sheet.

You can also add !important after your style values to override other styles on the same element.


Use one of my suggestions above and target the span of class style21, rather than the containing div. The style you are applying on the containing div will not be inherited by the span as it's color is set in the style sheet.

How do you add a JToken to an JObject?

Just adding .First to your bananaToken should do it:
foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
.First basically moves past the { to make it a JProperty instead of a JToken.

@Brian Rogers, Thanks I forgot the .Parent. Edited

How to export table as CSV with headings on Postgresql?

This works

psql dbname -F , --no-align -c "SELECT * FROM TABLE"

Running Python from Atom

Follow the steps:

  1. Install Python
  2. Install Atom
  3. Install and configure Atom package for Python
  4. Install and configure Python Linter
  5. Install Script Package in Atom
  6. Download and install Syntax Highlighter for Python
  7. Install Version control package Run Python file

More details for each step Click Here

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android=""
<item android:id="@+id/item_one"
      android:title="Item One"
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
            isItemOneSelected = true;
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            return true;
            return false;

This is the easiest way to display menus in action bar.

Base64 encoding and decoding in client-side Javascript

Modern browsers have built-in javascript functions for Base64 encoding btoa() and decoding atob(). More info about support in older browser versions:

However, be aware that atob and btoa functions work only for ASCII charset. If you need Base64 functions for UTF-8 charset, you can do it with:

function base64_encode(s) {      
    return btoa(unescape(encodeURIComponent(s)));
function base64_decode(s) {      
    return decodeURIComponent(escape(atob(s)));

jQuery - prevent default, then continue default

I would just do:

     //do your stuff.

Call preventDefault at first and use submit() function later, if you just need to submit the form

jQuery how to bind onclick event to dynamically added HTML element

Consider this:

  var close_link = $('<a class="" href="#">Click here to see an alert</a>');
        $(this).click(function() {
            alert('hello from binded function call');
            //do stuff here...

It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.

The best way will probably be - as suggested - to bind it to a specific class via the live method.

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use


Try this. It's helpful for you.

Blurry text after using CSS transform: scale(); in Chrome

This must be a bug with Chrome (Version 56.0.2924.87), but the below fixes the bluriness for me when changing css properties in the console('.0'). I'll report it.

filter: blur(.0px)

android - save image into gallery

According to this course, the correct way to do this is:


This will give you the root path for the gallery directory.

Get current date/time in seconds

To get today's total seconds of the day:

    let date = new Date();        
    return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();

I have add + in return which return in int. This may help to other developers. :)

How to easily initialize a list of Tuples?

C# 6 adds a new feature just for this: extension Add methods. This has always been possible for but is now available in C#.

Now you don't have to add Add() methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add() method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.

public static class TupleListExtensions
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
            T1 item1, T2 item2)
        list.Add(Tuple.Create(item1, item2));

    public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
            T1 item1, T2 item2, T3 item3)
        list.Add(Tuple.Create(item1, item2, item3));

    // and so on...

This will allow you to do this on any class that implements IList<>:

var numbers = new List<Tuple<int, string>>
    { 1, "one" },
    { 2, "two" },
    { 3, "three" },
    { 4, "four" },
    { 5, "five" },
var points = new ObservableCollection<Tuple<double, double, double>>
    { 0, 0, 0 },
    { 1, 2, 3 },
    { -4, -2, 42 },

Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.

public static class BigIntegerListExtensions
    public static void Add(this IList<BigInteger> list,
        params byte[] value)
        list.Add(new BigInteger(value));

    public static void Add(this IList<BigInteger> list,
        string value)

var bigNumbers = new List<BigInteger>
    new BigInteger(1), // constructor BigInteger(int)
    2222222222L,       // implicit operator BigInteger(long)
    3333333333UL,      // implicit operator BigInteger(ulong)
    { 4, 4, 4, 4, 4, 4, 4, 4 },               // extension Add(byte[])
    "55555555555555555555555555555555555555", // extension Add(string)

C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.

public static class ValueTupleListExtensions
    public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
        ValueTuple<T1, T2> item) => list.Add(item.ToTuple());

This way the list initialization will look even nicer.

var points = new List<Tuple<int, int, int>>
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),

But instead of going through all this trouble, it might just be better to switch to using ValueTuple exclusively.

var points = new List<(int, int, int)>
    (0, 0, 0),
    (1, 2, 3),
    (-1, 12, -73),

Can't use System.Windows.Forms

may be necesssary, unreference and reference again.

How can I make PHP display the error instead of giving me 500 Internal Server Error

It's worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you'll still see the 500 internal server error.

Scala: what is the best way to append an element to an Array?

You can use :+ to append element to array and +: to prepend it:

0 +: array :+ 4

should produce:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

It's the same as with any other implementation of Seq.

How to position two elements side by side using CSS

Use either float or inline elements:

Example JSBIN


<!DOCTYPE html>
<meta charset=utf-8 />
<title>JS Bin</title>
  <div>float example</div>
  <div><div style="float:left">Floating left content</div><div>Some content</div></div>
  <div>inline block example</div>
  <div><div style="display:inline-block">Some content</div><div style="display:inline-block">Next content</div></div>

How to check if a process id (PID) exists

You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/ /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 

BTW: whats wrong with kill -9 $PID || true ?


After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

how to play video from url

I also got stuck with this issue. I got correct response from server, but couldn`t play video. After long time I found a solution here. Maybe, in future this link will be invalid. So, here is my correct code

    Uri video = Uri.parse("Your link should be in this place "); 

   mVideoView.setZOrderOnTop(true); //Very important line, add it to Your code
    mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
        public void onPrepared(MediaPlayer mediaPlayer) {
  // here write another part of code, which provides starting the video

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.


Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software


Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

  <p id="holyCow"> This is the first paragraph.</p>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]


The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

JFrame Exit on close Java

You need the line


Because the default behaviour for the JFrame when you press the X button is the equivalent to


So almost all the times you'll need to add that line manually when creating your JFrame

I am currently referring to constants in WindowConstants like WindowConstants.EXIT_ON_CLOSE instead of the same constants declared directly in JFrame as the prior reflect better the intent.

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.


<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>


    background: #ccc;
} .btn:focus{
    background: red;


SQLite3 database or disk is full / the database disk image is malformed

Cloning the current database from the sqlite3 commandline worked for me.

.open /path/to/database/corrupted_database.sqlite3
.clone /path/to/database/new_database.sqlite3

In the Django setting file change the database name

'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'new_database.sqlite3'),

Ajax request returns 200 OK, but an error event is fired instead of success

I have the similar problem but when I tried to remove the datatype:'json' I still have the problem. My error is executing instead of the Success

function cmd(){
    var data = JSON.stringify(display1());
        type: 'POST',
        url: '/cmd',
        contentType:'application/json; charset=utf-8',
        data: data,
        success: function(res){
                  console.log('Success in running run_id ajax')
                   //   type: "GET",
                   //   url: "/runid",
                   //   contentType:"application/json; charset=utf-8",
                   //   dataType:"json",
                   //   data: data,
                   //  success:function display_runid(){}
                  // });
        error: function(req, err){ console.log('my message: ' + err); }

How to know function return type and argument types?

I attended a coursera course, there was lesson in which, we were taught about design recipe.

Below docstring format I found preety useful.

def area(base, height):
    '''(number, number ) -> number    #**TypeContract**
    Return the area of a tring with dimensions base   #**Description**
    and height

    >>>area(10,5)          #**Example **
    return (base * height) /2 

I think if docstrings are written in this way, it might help a lot to developers.

Link to video [Do watch the video] :

Remove warning messages in PHP

Not exactly answering the question, but I think this is a better compromise in some situations:

I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was - a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:

printf('<div style="display:none">');
    ...Third-party stuff here...

Warning was still in page source as a reminder to me, but invisible to the client.

UICollectionView current visible cell index

Swift 3.0

Simplest solution which will give you indexPath for visible cells..


will return the array of indexpath.

Just take the first object from array like this.


I guess it should work fine with Objective - C as well.

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just need to change one letter:), rename 640x360.ogv to 640x360.ogg, it will work for all the 3 browers.

How to align td elements in center

What worked for me is the following (in view of the confusion in other answers):

<td style="text-align:center;">
    <input type="radio" name="ageneral" value="male">

The proposed solution (text-align) works but must be used in a style attribute.

What are valid values for the id attribute in HTML?

jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write

var name = 'O'Hara';

Selectors in jQuery API (see bottom note)

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

Javascript select onchange='this.form.submit()'

You should be able to use something similar to:

         /* or:

git push says "everything up-to-date" even though I have local changes

Another very simple yet noobish mistake of mine: I simply forgot to add a message -m modifier in my commit. So I wrote:

git commit 'My message'

Instead of correct:

git commit -m 'My message'

NOTE: It does NOT throw any errors! But you will not be able to push your commits and always get Everything up to date instead

How to read a file without newlines?

temp = open(filename,'r').read().splitlines()

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Thanks to Don Branson,I solve my problem.I think next time i should use this code when i build my repo on server:

root@localhost:~#mkdir foldername
root@localhost:~#cd foldername
root@localhost:~#git init --bare
root@localhost:~#cd ../
root@localhost:~#chown -R usergroup:username foldername

And on client,i user this

$ git remote add origin git@servername:/var/git/foldername
$ git push origin master

Execution failed for task :':app:mergeDebugResources'. Android Studio

This issue can be resolved by trying multiple solutions like:

  1. Clean the project OR delete build folder and rebuild.
  2. Downgrading gradle version
  3. Check for the generated build file path, as it may be exceeding the windows max path length of 255 characters. Try using short names to make sure your project path is not too long.
  4. You may have a corrupted .9.png in your drawables directory

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

How to activate virtualenv?

Windows 10

In Windows these directories are created :

Windows 10 Virtual Environment directories

To activate Virtual Environment in Windows 10.


\scripts directory contain activate file.

Linux Ubuntu

In Ubuntu these directories are created :

Linux Ubuntu Virtual Environment directories

To activate Virtual Environment in Linux Ubuntu.

source ./bin/activate

/bin directory contain activate file.

Virtual Environment copied from Windows to Linux Ubuntu vice versa

If Virtual environment folder copied from Windows to Linux Ubuntu then according to directories:

source ./down/Scripts/activate

mysql data directory location

If the software is Sequel pro the default install mysql on Mac OSX has data located here:


Simple way to get element by id within a div tag?

Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.

When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.

You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.

What is EOF in the C programming language?

int c;

while((c = getchar())!= 10)
    if( getchar() == EOF )

     printf(" %d\n", c);

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Using DirectoryIterator and recursion correctly:

function deleteFilesThenSelf($folder) {
    foreach(new DirectoryIterator($folder) as $f) {
        if($f->isDot()) continue; // skip . and ..
        if ($f->isFile()) {
        } else if($f->isDir()) {

Set Radiobuttonlist Selected from Codebehind

Try this option:

radio1.Items.FindByValue("1").Selected = true;

How to create radio buttons and checkbox in swift (iOS)?

A very simple checkbox control.

 @IBAction func btn_box(sender: UIButton) {
    if (btn_box.selected == true)
        btn_box.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal)

            btn_box.selected = false;
        btn_box.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal)

        btn_box.selected = true;

Box shadow in IE7 and IE8

Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.

It supports box-shadow (except for the inset keyword).

How do I display images from Google Drive on a website?

i supposed you uploaded your photo in your drive all what you need to do is while you are opening your google drive just open your dev tools in chrome and head to your img tag and copy the link beside the src attribute and use it

How to show current user name in a cell?

Based on the instructions at the link below, do the following.

In VBA insert a new module and paste in this code:

Public Function UserName()
    UserName = Environ$("UserName")
End Function

Call the function using the formula:


Based on instructions at:

How to check if a Docker image with a specific tag exist locally?

In bash script I do this to check if image exists by tag :


if docker image ls -a "$IMAGE_NAME" | grep -Fq "$IMAGE_NAME" 1>/dev/null; then
echo "could found image $IMAGE_NAME..."

Example script above checks if mysql image with 5.6 tag exists. If you want just check if any mysql image exists without specific version then just pass repository name without tag as this :


Regular Expression to reformat a US phone number in Javascript

Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.

Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:

//format text input as phone number (nnn) nnn-nnnn
$('.myPhoneField').on('input', function (e){
    var $phoneField =;
    var cursorPosition = $phoneField.selectionStart;
    var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);

    // let user backspace over the '-'
    if (cursorPosition === 9 && numericString.length > 6) return;

    // let user backspace over the ') '
    if (cursorPosition === 5 && numericString.length > 3) return;
    if (cursorPosition === 4 && numericString.length > 3) return;

    var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
    if (match) {
        var newVal = '(' + match[1];
        newVal += match[2] ? ') ' + match[2] : '';
        newVal += match[3] ? '-' + match[3] : '';

        // to help us put the cursor back in the right place
        var delta = newVal.length - Math.min($phoneField.value.length, 14);      
        $phoneField.value = newVal;
        $phoneField.selectionEnd = cursorPosition + delta;
    } else {
        $phoneField.value = '';        

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>

Easy way to dismiss keyboard?

the easist way is to call the method

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    if(![txtfld resignFirstResponder])
        [txtfld resignFirstResponder];

    [super touchesBegan:touches withEvent:event];

Initialize a byte array to a certain value, other than the default null?

You can use a collection initializer:

UserCode = new byte[]{0x20,0x20,0x20,0x20,0x20,0x20};

This will work better than Repeat if the values are not identical.

In a javascript array, how do I get the last 5 elements, excluding the first element?

ES6 way:

I use destructuring assignment for array to get first and remaining rest elements and then I'll take last five of the rest with slice method:

const cutOffFirstAndLastFive = (array) => {_x000D_
  const [first,] = array;_x000D_
  return rest.slice(-5);_x000D_
cutOffFirstAndLastFive([1, 55, 77, 88]);_x000D_
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),_x000D_
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),_x000D_

Why can't radio buttons be "readonly"?

A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.

Insert some string into given string at given index in Python

Answer for Insert characters of string in other string al located positions

str1 = "ibuprofen"
str2 = "MEDICAL"
Value = 2
result=[str1[i:i+Value] for i in range(0, len(str1), Value)]
count = 0

for letter in result:
    if count < len(result)-1:
        final_string = letter + str2[count]
    elif ((len(result)-1)==count):
        list2.append(letter + str2[count:len(str2)])
    count += 1


Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

How to remove \xa0 from string in Python?

\xa0 is actually non-breaking space in Latin1 (ISO 8859-1), also chr(160). You should replace it with a space.

string = string.replace(u'\xa0', u' ')

When .encode('utf-8'), it will encode the unicode to utf-8, that means every unicode could be represented by 1 to 4 bytes. For this case, \xa0 is represented by 2 bytes \xc2\xa0.

Read up on

Please note: this answer in from 2012, Python has moved on, you should be able to use unicodedata.normalize now

Convert string to datetime in

You can try with ParseExact method


Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

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

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

This will add ONE class or MULTIPLE classes :

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

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

How to get number of rows using SqlDataReader in C#

If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:

using (var sqlCon = new SqlConnection("Server=;Database=MyDb;User Id=Me;Password=glop;"))

        var com = sqlCon.CreateCommand();
        com.CommandText = "select * from BigTable";
        using (var reader = com.ExecuteReader())
            //here you retrieve what you need

        com.CommandText = "select @@ROWCOUNT";
        var totalRow = com.ExecuteScalar();


You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

Using /proc/tty/drivers only indicates which tty drivers are loaded. If you're looking for a list of the serial ports check out /dev/serial, it will have two subdirectories: by-id and by-path.


# find . -type l

Thanks to this post:

Maximum filename length in NTFS (Windows XP and Windows Vista)?

199 on Windows XP NTFS, I just checked.

This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.

Is there some other setting limiting this, I wonder? Try it for yourself.

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

For..In loops in JavaScript - key value pairs

why not simply this

var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];

donuts.forEach(v => {console.log(v["type"]+ " donuts cost $"+v["cost"]+" each")});

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).

INSERT INTO beautiful (name, age)
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    AS new
    age = new.age

For earlier versions use the keyword VALUES (see reference, deprecated with MySQL 8.0.20).

INSERT INTO beautiful (name, age)
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    age = VALUES(age),

creating a table in ionic

This should probably be a comment, however, I don't have enough reputation to comment.

I suggest you really use the table (HTML) instead of ion-row and ion-col. Things will not look nice when one of the cell's content is too long.

One worse case looks like this:

| 10 | 20 | 30 | 40 |
| 1 | 2 | 3100 | 41 |

Higher fidelity example fork from @jpoveda

Converting an array to a function arguments list

A very readable example from another post on similar topic:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...

// Calling the function using the array with apply()
call_me.apply(this, args);

And here a link to the original post that I personally liked for its readability

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

The simple way is to, Edit your migration file (cascadeDelete: true) into (cascadeDelete: false) then after assign the Update-Database command in your Package Manager Console.if it's problem with your last migration then all right. Otherwise check your earlier migration history, copy those things, paste into your last migration file, after that do it the same thing. it perfectly works for me.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
      <img src={props.src}/>

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

render () {
  return (
    <div className='container'>
      <Picture key={} src={picture.src}>
          //what is placed here is passed as props.children  

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

For a decimal, use the ToString method, and specify the Invariant culture to get a period as decimal separator:

value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)

The long type is an integer, so there is no fraction part. You can just format it into a string and add some zeros afterwards:

value.ToString() + ".00"

Limit number of characters allowed in form input text field

Use maxlenght="number of charcters"

<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />

PDF to image using Java

You will need a PDF renderer. There are a few more or less good ones on the market (ICEPdf, pdfrenderer), but without, you will have to rely on external tools. The free PDF renderers also cannot render embedded fonts, and so will only be good for creating thumbnails (what you eventually want).

My favorite external tool is Ghostscript, which can convert PDFs to images with a single command line invocation.

This converts Postscript (and PDF?) files to bmp for us, just as a guide to modify for your needs (Know you need the env vars for gs to work!):


Set BIN_DIR=C:\Program Files\IKOffice_ACME\bin
Set GS=C:\Program Files\IKOffice_ACME\gs
Set GS_DLL=%GS%\gs8.54\bin\gsdll32.dll
Set GS_LIB=%GS%\gs8.54\lib;%GS%\gs8.54\Resource;%GS%\fonts
Set Path=%Path%;%GS%\gs8.54\bin
Set Path=%Path%;%GS%\gs8.54\lib

call "%GS%\gs8.54\bin\gswin32c.exe" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE#bmpmono -r600x600 -sOutputFile#%2 -f %1


UPDATE: pdfbox is now able to embed fonts, so no need for Ghostscript anymore.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Or simple try:

> sudo easy_install MySQL-python

If it gives a error like below:

EnvironmentError: mysql_config not found

, then just run this

> export PATH=$PATH:/usr/local/mysql/bin

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
| Level   | Code | Message                                  |
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
| pdd        |
| 0000-00-00 |
1 row in set (0.00 sec)

Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
| pdd        |
| 0000-00-00 |
| NULL       |
2 rows in set (0.00 sec)

How can I pretty-print JSON in a shell script?

If you don't mind using a third-party tool, you can simply curl to This is for the case where you can't install packages on the machine.

curl -XPOST -d '{"user" : 1}'

LINQ: "contains" and a Lambda query

I'm not sure precisely what you're looking for, but this program:

    public class Building
        public enum StatusType

        public string Name { get; set; }
        public StatusType Status { get; set; }

    public static List <Building> buildingList = new List<Building> ()
        new Building () { Name = "one", Status = },
        new Building () { Name = "two", Status = Building.StatusType.closed },
        new Building () { Name = "three", Status = Building.StatusType.weird },

        new Building () { Name = "four", Status = },
        new Building () { Name = "five", Status = Building.StatusType.closed },
        new Building () { Name = "six", Status = Building.StatusType.weird },

    static void Main (string [] args)
        var statusList = new List<Building.StatusType> () {, Building.StatusType.closed };

        var q = from building in buildingList
                where statusList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);

produces the expected output:

one: open
two: closed
four: open
five: closed

This program compares a string representation of the enum and produces the same output:

    public class Building
        public enum StatusType

        public string Name { get; set; }
        public string Status { get; set; }

    public static List <Building> buildingList = new List<Building> ()
        new Building () { Name = "one", Status = "open" },
        new Building () { Name = "two", Status = "closed" },
        new Building () { Name = "three", Status = "weird" },

        new Building () { Name = "four", Status = "open" },
        new Building () { Name = "five", Status = "closed" },
        new Building () { Name = "six", Status = "weird" },

    static void Main (string [] args)
        var statusList = new List<Building.StatusType> () {, Building.StatusType.closed };
        var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());

        var q = from building in buildingList
                where statusStringList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);

        Console.ReadKey ();

I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.

public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
    foreach ( TSource source in sources )
        yield return convert (source);

Then you can change the where clause to:

where statusList.ConvertEach <string> (status => status.GetCharValue()).
    Contains (v.Status)

and skip creating the List<string> with ConvertAll () at the beginning.

Reading large text files with streams in C#

You can improve read speed by using a BufferedStream, like this:

using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
    string line;
    while ((line = sr.ReadLine()) != null)


March 2013 UPDATE

I recently wrote code for reading and processing (searching for text in) 1 GB-ish text files (much larger than the files involved here) and achieved a significant performance gain by using a producer/consumer pattern. The producer task read in lines of text using the BufferedStream and handed them off to a separate consumer task that did the searching.

I used this as an opportunity to learn TPL Dataflow, which is very well suited for quickly coding this pattern.

Why BufferedStream is faster

A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers improve read and write performance. A buffer can be used for either reading or writing, but never both simultaneously. The Read and Write methods of BufferedStream automatically maintain the buffer.

December 2014 UPDATE: Your Mileage May Vary

Based on the comments, FileStream should be using a BufferedStream internally. At the time this answer was first provided, I measured a significant performance boost by adding a BufferedStream. At the time I was targeting .NET 3.x on a 32-bit platform. Today, targeting .NET 4.5 on a 64-bit platform, I do not see any improvement.


I came across a case where streaming a large, generated CSV file to the Response stream from an ASP.Net MVC action was very slow. Adding a BufferedStream improved performance by 100x in this instance. For more see Unbuffered Output Very Slow

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.

What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

How do I convert a String object into a Hash object?

The string created by calling Hash#inspect can be turned back into a hash by calling eval on it. However, this requires the same to be true of all of the objects in the hash.

If I start with the hash {:a =>}, then its string representation is "{:a=>#<Object:0x7f66b65cf4d0>}", and I can't use eval to turn it back into a hash because #<Object:0x7f66b65cf4d0> isn't valid Ruby syntax.

However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.

How to change an image on click using CSS alone?

some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:

<a href="" class="off" onclick="this.className='on';return false;">Foo</a>

using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.

Good Luck

How to use nan and inf in C?

double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);

Permutations between two lists of unequal length

Without itertools as a flattened list:

[(list1[i], list2[j]) for i in range(len(list1)) for j in range(len(list2))]

or in Python 2:

[(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))]

Changing the highlight color when selecting text in an HTML text input

I realise this is an old question but for anyone who does come across it this can be done using contenteditable as shown in this JSFiddle.

Kudos to Alex who mentioned this in the comments (I didn't see that until now!)

How to get the height of a body element

I believe that the body height being returned is the visible height. If you need the total page height, you could wrap your div tags in a containing div and get the height of that.

PHP Redirect with POST data

Here there is another approach that works for me:

if you need to redirect to another web page (user.php) and includes a PHP variable ($user[0]):




How to Kill A Session or Session ID (ASP.NET/C#)

Session["YourItem"] = "";

Works great in .net razor web pages.

How to save as a new file and keep working on the original one in Vim?

Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.

Assumed that I'm editing hello.txt.

  • :w world.txt will write hello.txt's content to the file world.txt while keeping hello.txt as the opened buffer in vim.
  • :sav world.txt will first write hello.txt's content to the file world.txt, then close buffer hello.txt, finally open world.txt as the current buffer.

Display exact matches only with grep

try this:

grep -P '^(tomcat!?)' tst1.txt

It will search for specific word in txt file. Here we are trying to search word tomcat

WPF: Create a dialog / prompt

You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin, Height, Width properties set in the XAML, but should be enough to show how to get this done at a basic level.

Build a Window page like you would normally and add your fields to it, say a Label and TextBox control inside a StackPanel:

<StackPanel Orientation="Horizontal">
    <Label Name="lblUser" Content="User Name:" />
    <TextBox Name="txtUser" />

Then create a standard Button for Submission ("OK" or "Submit") and a "Cancel" button if you like:

<StackPanel Orientation="Horizontal">
    <Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
    <Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />

You'll add the Click event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:

public static string strUserName = String.Empty;

Then, for the event handler functions (right-click the Click function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
    if (!String.IsNullOrEmpty(txtUser.Text))
        strUserName = txtUser.Text;
        MessageBox.Show("Must provide a user name in the textbox.");

Calling It From Another Page
You're thinking, if I close my window with that this.Close() up there, my value is gone, right? NO!! I found this out from another site:

They had a similar example to this (I cleaned it up a bit) of how to open your Window from another and retrieve the values:

public partial class MainWindow : Window
    public MainWindow()

    private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
        MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page

        //ShowDialog means you can't focus the parent window, only the popup
        popup.ShowDialog(); //execution will block here in this method until the popup closes

        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page

Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:

public static bool cancelled = false;

And let's include our btnCancel_Click event handler, and make one change to btnSubmit_Click:

private void btnCancel_Click(object sender, RoutedEventArgs e)
    cancelled = true;
    strUserName = String.Empty;

private void btnSubmit_Click(object sender, RoutedEventArgs e)
    if (!String.IsNullOrEmpty(txtUser.Text))
        strUserName = txtUser.Text;
        cancelled = false;  // <-- I add this in here, just in case
        MessageBox.Show("Must provide a user name in the textbox.");

And then we just read that variable in our MainWindow btnOpenPopup_Click event:

private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
    MyPopupWindow popup = new MyPopupWindow();  // this is the class of your other page
    //ShowDialog means you can't focus the parent window, only the popup
    popup.ShowDialog(); //execution will block here in this method until the popup closes

    // **Here we find out if we cancelled or not**
    if (popup.cancelled == true)
        string result = popup.strUserName;
        UserNameTextBlock.Text = result;  // should show what was input on the other page

Long response, but I wanted to show how easy this is using public static variables. No DialogResult, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
      return false

And import in any file where you want to use it '@/path/to/String+Extension'

Git says remote ref does not exist when I delete remote branch

For windows

git branch --remotes| %{ $_.Trim().Split("/")[1] }| ?{ $_ -ne 'master' } | | ?{ $_ -ne 'otherBranch' } | %{ git push origin --delete $_ }

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;


enter image description here

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

"Z" doesn't stand for "Zulu"

I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I'm using Linux Mint 18.2 of this writing. I had a similar issue; when trying to load myphpadmin, it said: "1045 - Access denied for user 'root'@'localhost' (using password: NO)"

I found the file in the /opt/lampp/phpmyadmin directory. I opened the file with my text editor and typed in the correct password. Saved it, and launched it successfully. Profit!

I was having problems with modifying folders and files, I had to change permission to access all my files in /opt/lampp/ directory. I hope this helps someone in the future.

Perform commands over ssh with Python

Below example, incase if you want user inputs for hostname,username,password and port no.

  import paramiko

  ssh = paramiko.SSHClient()


  def details():

  Host = input("Enter the Hostname: ")

  Port = input("Enter the Port: ")

  User = input("Enter the Username: ")

  Pass = input("Enter the Password: ")

  ssh.connect(Host, Port, User, Pass, timeout=2)


  stdin, stdout, stderr = ssh.exec_command("")

  stdin.write('xcommand SystemUnit Boot Action: Restart\n')



Convert double to string C++?

Use std::stringstream. Its operator << is overloaded for all built-in types.

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();

This works like you'd expect - the same way you print to the screen with std::cout. You're simply "printing" to a string instead. The internals of operator << take care of making sure there's enough space and doing any necessary conversions (e.g., double to string).

Also, if you have the Boost library available, you might consider looking into lexical_cast. The syntax looks much like the normal C++-style casts:

#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;

storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
                       "," + lexical_cast<std::string>(c2) + ")";

Under the hood, boost::lexical_cast is basically doing the same thing we did with std::stringstream. A key advantage to using the Boost library is you can go the other way (e.g., string to double) just as easily. No more messing with atof() or strtod() and raw C-style strings.

C++ terminate called without an active exception

As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.

int main(){

std::thread t(thread,1);


return 0;}

It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.

Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code. Third thread sleep for 8 seconds but main will die in 5 seconds.

void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}

int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);

return 0;}

jQuery: Scroll down page a set increment (in pixels) on click?

You might be after something that the scrollTo plugin from Ariel Flesler does really well.

Python List vs. Array - when to use?

For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see docs), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.

Why can't static methods be abstract in Java?

Because 'abstract' means the method is meant to be overridden and one can't override 'static' methods.

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.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

When using Java8 it would be more easier and a single liner only.

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));

For each row return the column name of the largest value

A dplyr solution:


  • add rowids as a column
  • reshape to long format
  • filter for max in each group


DF = data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
DF %>% 
  rownames_to_column() %>%
  gather(column, value, -rowname) %>%
  group_by(rowname) %>% 
  filter(rank(-value) == 1) 


# A tibble: 3 x 3
# Groups:   rowname [3]
  rowname column value
  <chr>   <chr>  <dbl>
1 2       V1         8
2 3       V2         5
3 1       V3         9

This approach can be easily extended to get the top n columns. Example for n=2:

DF %>% 
  rownames_to_column() %>%
  gather(column, value, -rowname) %>%
  group_by(rowname) %>% 
  mutate(rk = rank(-value)) %>%
  filter(rk <= 2) %>% 
  arrange(rowname, rk) 


# A tibble: 6 x 4
# Groups:   rowname [3]
  rowname column value    rk
  <chr>   <chr>  <dbl> <dbl>
1 1       V3         9     1
2 1       V2         7     2
3 2       V1         8     1
4 2       V3         6     2
5 3       V2         5     1
6 3       V3         4     2

How do I check for vowels in JavaScript?

  //function to find vowel
const vowel = (str)=>{
  //these are vowels we want to check for
  const check = ['a','e','i','o','u'];
  //keep track of vowels
  var count = 0;
  for(let char of str.toLowerCase())
    //check if each character in string is in vowel array
    if(check.includes(char)) count++;
  return count;

console.log(vowel("hello there"));

JPA and Hibernate - Criteria vs. JPQL or HQL

There is another way. I ended up with creating a HQL parser based on hibernate original syntax so it first parse the HQL then it could dynamically inject dynamic parameters or automatically adding some common filters for the HQL queries. It works great!

Count the frequency that a value occurs in a dataframe column

your data:

cat a
cat b
cat a


 df['freq'] = df.groupby('category')['category'].transform('count')
 df =  df.drop_duplicates()

Javascript "Not a Constructor" Exception while creating objects

It is happening because you must have used another variable named "project" in your code. Something like var project = {}

For you to make the code work, change as follows:

var project = {} into var project1 = {}

What is the reason for a red exclamation mark next to my project in Eclipse?

Isn´t it a strange behavior? In my case, the mistake was that I added a jar-lib. But this lib was faulty, so I removed the lib. But, no matter what I´ve done, the error still exists. I removed the jar-file, even with the eclipse option "remove from build-path", deleted it on my project-folders and cleaned my project, but nothing worked. Only after I´ve done the way Qwert has described, it worked. But sould an IDE not independent from error messages? The error was fixed, only the messages caused the problem. Thanks to Qwert (if I got enough reputations, I will vote your answer. But now I am not able to, sorry).

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.


Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        contentView = view

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here

For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    override init(frame: CGRect) {
        super.init(frame: frame)


NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Are HTTP headers case-sensitive?

HTTP header names are case-insensitive, according to RFC 2616:


Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

(Field values may or may not be case-sensitive.)

If you trust the major browsers to abide by this, you're all set.

BTW, unlike most of HTTP, methods (verbs) are case sensitive:

5.1.1 Method

The Method token indicates the method to be performed on the
resource identified by the Request-URI. The method is case-sensitive.

   Method         = "OPTIONS"                ; Section 9.2
                  | "GET"                    ; Section 9.3
                  | "HEAD"                   ; Section 9.4
                  | "POST"                   ; Section 9.5
                  | "PUT"                    ; Section 9.6
                  | "DELETE"                 ; Section 9.7
                  | "TRACE"                  ; Section 9.8
                  | "CONNECT"                ; Section 9.9
                  | extension-method
   extension-method = token

Android Recyclerview vs ListView with Viewholder

The other plus of using RecycleView is animation, it can be done in two lines of code

RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();

But the widget is still raw, e.g you can't create header and footer.

Convert string to decimal, keeping fractions

Hello i was have the same issue, but it is easly, just do this:

string cadena="96.23";

decimal NoDecimal=decimal.parse(cadena.replace(".",","))

I think this is beacuse the notation that accept C# on decimal numbers are with a ","

psql: FATAL: role "postgres" does not exist

createuser postgres --interactive

or make a superuser postgresl just with

createuser postgres -s

How to change the display name for LabelFor in razor in mvc3?

You can change the labels' text by adorning the property with the DisplayName attribute.

[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }

Or, you could write the raw HTML explicitly:

<label for="SomekingStatus" class="control-label">Someking Status</label>

Interview question: Check if one string is a rotation of other string

Fist, make sure the 2 strings have the same length. Then in C, you can do this with a simple pointer iteration.

int is_rotation(char* s1, char* s2)
  char *tmp1;
  char *tmp2;
  char *ref2;

  assert(s1 && s2);
  if ((s1 == s2) || (strcmp(s1, s2) == 0))
    return (1);
  if (strlen(s1) != strlen(s2))
    return (0);

  while (*s2)
      tmp1 = s1;
      if ((ref2 = strchr(s2, *s1)) == NULL)
        return (0);
      tmp2 = ref2;
      while (*tmp1 && (*tmp1 == *tmp2))
          if (*tmp2 == '\0')
            tmp2 = s2;
      if (*tmp1 == '\0')
        return (1);
  return (0);

Mismatch Detected for 'RuntimeLibrary'

I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.

The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.

Any ideas how to fix this?

To resolve your issues, you should download if you want static C/C++ runtime linking (/MT or /MTd), or if you want dynamic C/C++ runtime linking (/MT or /MTd). Both fix the latent, silent failures produced by VCUpgrade., and are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.

There are two minor problems I am aware. First is a rename of bench.cpp to bench1.cpp. Its error is either:

  • C1083: Cannot open source file: 'bench1.cpp': No such file or directory
  • LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)

The fix is to either (1) open cryptest.vcxproj in notepad, find bench1.cpp, and then rename it to bench.cpp. Or (2) rename bench.cpp to bench1.cpp on the filesystem. Please don't delete this file.

The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.

The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.

Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h, cpu.h and cpu.cpp. The "subtlety" is you won't realize you are getting an under-performing class.

An example of under-performing class is BLAKE2. config.h adds compile time ARM-32 and ARM-64 detection. cpu.h and cpu.cpp adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Follow these steps to run your application on the device connected. 1. Change directories to the root of your Android project and execute: ant debug 2. Make sure the Android SDK platform-tools/ directory is included in your PATH environment variable, then execute: adb install bin/<*your app name*>-debug.apk On your device, locate <*your app name*> and open it.

Refer Running App

Including a css file in a blade template?

<link rel="stylesheet" href="{{ URL::asset('css/styles.css') }}">

It will search for the file in your project public folder

Set and Get Methods in java?

just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.

how to disable DIV element and everything inside

You can't use "disable" to disable a click event. I don't know how or if it worked in IE6-9, but it didn't work on Chrome, and it shouldn't work on IE10 like that.

You can disable the onclick event, too, by attaching an event that cancels:

;(function () {
    function cancel () { return false; };
    document.getElementById("test").disabled = true;
    var nodes = document.getElementById("test").getElementsByTagName('*');
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].setAttribute('disabled', true);
        nodes[i].onclick = cancel;

Furthermore, setting "disabled" on a node directly doesn't necessarily add the attribute- using setAttribute does.

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)


What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

Simple calculations for working with lat/lon and km distance?

Why not use properly formulated geospatial queries???

Here is the SQL server reference page on the STContains geospatial function:

or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:

DECLARE @CurrentLocation geography; 
SET @CurrentLocation  = geography::Point(12.822222, 80.222222, 4326)

SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km

There should be similar functionality for almost any database out there.

If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using

Get time of specific timezone

You could use Intl.DateTimeFormat.

let options = {_x000D_
    timeZone: 'Europe/London',_x000D_
    year: 'numeric',_x000D_
    month: 'numeric',_x000D_
    day: 'numeric',_x000D_
    hour: 'numeric',_x000D_
    minute: 'numeric',_x000D_
    second: 'numeric',_x000D_
  formatter = new Intl.DateTimeFormat([], options);_x000D_
console.log(formatter.format(new Date()));

Alternatively, if you're formatting just once instead of bulk use Date.prototype.toLocaleDateString().

(new Date()).toLocaleString([], options)

Unfortunately browsers are not required to understand timezones other than UTC, so try these blocks and figure out an alternative in case it fails, for example fetch the timezone offset from a server.

How to change active class while click to another link in bootstrap use jquery?

guys try this is a perfect answer for this question:

        $('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
        $('.nav li a').click(function(){

SQL - Update multiple records in one query

Try either multi-table update syntax

UPDATE config t1 JOIN config t2
    ON t1.config_name = 'name1' AND t2.config_name = 'name2'
   SET t1.config_value = 'value',
       t2.config_value = 'value2';

Here is SQLFiddle demo

or conditional update

UPDATE config
   SET config_value = CASE config_name 
                      WHEN 'name1' THEN 'value' 
                      WHEN 'name2' THEN 'value2' 
                      ELSE config_value
 WHERE config_name IN('name1', 'name2');

Here is SQLFiddle demo

Get first and last day of month using threeten, LocalDate

Try this:

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);         
LocalDate end = initial.withDayOfMonth(initial.getMonthOfYear().getLastDayOfMonth(false));

you can find the desire output but need to take care of parameter true/false for getLastDayOfMonth method

that parameter denotes leap year

warning: incompatible implicit declaration of built-in function ‘xyz’

Here is some C code that produces the above mentioned error:

int main(int argc, char **argv) {

Compiled like this on Fedora 17 Linux 64 bit with gcc:

el@defiant ~/foo2 $ gcc -o n n2.c                                                               
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in 
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n 
el@defiant ~/foo2 $ 

To make the warning go away, add this declaration to the top of the file:

#include <stdlib.h>

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
Exponent: 65537 (0x10001)


It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.

(You can use BouncyCastle similarly in C# too.)

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

What is the difference between require() and library()?

Always use library. Never use require.

In a nutshell, this is because, when using require, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:


x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require throws an error here, signalling clearly that something is wrong. This is good.

It also makes debugging all other failures more difficult: If you require a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.

The only acceptable use case of require is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […] You never need to use require() (requireNamespace() is almost always better)

Specifying and saving a figure with exact size in pixels

This solution works for matplotlib versions 3.0.1, 3.0.3 and 3.2.1.

def save_inp_as_output(_img, c_name, dpi=100):
    h, w, _ = _img.shape
    fig, axes = plt.subplots(figsize=(h/dpi, w/dpi))
    fig.subplots_adjust(top=1.0, bottom=0, right=1.0, left=0, hspace=0, wspace=0) 
    plt.savefig(c_name, dpi=dpi, format='jpeg') 

Because the subplots_adjust setting makes the axis fill the figure, you don't want to specify a bbox_inches='tight', as it actually creates whitespace padding in this case. This solution works when you have more than 1 subplot also.

6 digits regular expression

You can use range quantifier {min,max} to specify minimum of 1 digit and maximum of 6 digits as:



^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$     : End anchor

Why did your regex not work ?

You were almost close on the regex:


Since you had escaped the ? by preceding it with the \, the ? was no more acting as a regex meta-character ( for 0 or 1 repetitions) but was being treated literally.

To fix it just remove the \ and you are there.

See it on rubular.

The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.

Your second regex:


is equivalent to:


which matches strings with exactly one digit. They are equivalent because a character class [aaaab] is same as [ab].

Redirect in Spring MVC

Axtavt answer is correct.

This is how your resolver should look like (annotations based):

UrlBasedViewResolver resolver(){
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();


    return resolver;

Obviously the name of your views directory should change based on your project.

Is nested function a good approach when required by only one function?

>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()

Is this what you were looking for? It's called a closure.

What's the difference between Instant and LocalDateTime?

You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.

Generic htaccess redirect www to non-www

This is updated to work on Apache 2.4:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

The only change vs Michael's is to remove the [NC], which produces the "AH00665" error:

NoCase option for non-regex pattern '-f' is not supported and will be ignored

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]


Y = X == False

would give you

Y = [False, True, False]

What is path of JDK on Mac ?

Have a look and see if the the JDK is at:

Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/

Check this earlier SO post: JDK on OSX 10.7 Lion

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

.fa-flag:hover {_x000D_
    color: red;_x000D_
<link href="" rel="stylesheet"/>_x000D_
<i class="fa fa-flag fa-3x"></i>

MySQL Error 1264: out of range value for column

You can also change the data type to bigInt and it will solve your problem, it's not a good practice to keep integers as strings unless needed. :)


Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

Integrity constraint violation: 1452 Cannot add or update a child row:

I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:

$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent

Then when I called my child class to insert children, I passed this var value:


Hope that helps.

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

How to persist a property of type List<String> in JPA?

According to Java Persistence with Hibernate

mapping collections of value types with annotations [...]. At the time of writing it isn't part of the Java Persistence standard

If you were using Hibernate, you could do something like:

    targetElement = java.lang.String.class
    name = "foo",
    joinColumns = @JoinColumn(name = "foo_id")
    name = "POSITION", base = 1
@Column(name = "baz", nullable = false)
private List<String> arguments = new ArrayList<String>();

Update: Note, this is now available in JPA2.

XSLT equivalent for JSON

As yet another new answer to an old question, I'd suggest a look at DefiantJS. It's not an XSLT equivalent for JSON, it is XSLT for JSON. The "Templating" section of the documentation includes this example:

<!-- Defiant template -->
<script type="defiant/xsl-template">
    <xsl:template name="books_template">
        <xsl:for-each select="//movie">
            <xsl:value-of select="title"/><br/>

<script type="text/javascript">

var data = {
        "movie": [
            {"title": "The Usual Suspects"},
            {"title": "Pulp Fiction"},
            {"title": "Independence Day"}
    htm = Defiant.render('books_template', data);

// The Usual Suspects<br>
// Pulp Fiction<br>
// Independence Day<br>

Drawing circles with System.Drawing

if you want to draw circle on button then this code might be use full. else if you want to draw a circle on other control just change the name of control and also event. like here event button is called. if you want to draw this circle in group box call the Groupbox event. regards

    public Form1()


    private void Form1_Load(object sender, EventArgs e)
        this.button1.Location = new Point(108, 12);
       // this.Paint += new PaintEventHandler(Form1_Paint);
        this.button1.Paint += new PaintEventHandler(button1_Paint);
    void button1_Paint(object sender, PaintEventArgs e)
        Graphics g = this.button1.CreateGraphics();
        Pen pen = new Pen(Color.Red);
        g.DrawEllipse(pen, 10, 10, 20, 20);



Getting time and date from timestamp with php

You can try this:

For Date:

$date = new DateTime($from_date);
$date = $date->format('d-m-Y');

For Time:

$time = new DateTime($from_date);
$time = $time->format('H:i:s');

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

        type="my_package.MyListener" />

        android:onClick="@{() -> listener.onClick()}"
        app:layout_constraintRight_toRightOf="parent" />
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment

    override fun onClick() {
        TODO("Not yet implemented")


interface MyListener{
    fun onClick()

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
    echo 'Less than';



 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
    echo 'Less than';


Getting list of tables, and fields in each, in a database

Is this what you are looking for:


 SELECT AS Table_Name , AS Column_Name , AS Data_Type ,
       P.max_length AS Size ,
       CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM   sys.objects AS T
       JOIN sys.columns AS C ON T.object_id = C.object_id
       JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE  T.type_desc = 'USER_TABLE';


       TABLE_NAME ,
       COLUMN_NAME ,
       DATA_TYPE ,

Reference : My Blog -

Oracle Add 1 hour in SQL

The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

select sysdate + 1/24 from dual; 

if you want 1 day to add

select sysdate + 24/24 from dual; 


select sysdate + 1 from dual; 

same as for 2, 3 , 4 day

For static date you have the answer below.

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:


<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;

To see how the project turns out, here is a JSFiddle for the above code:

Linux Shell Script For Each File in a Directory Grab the filename and execute a program


for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

Rename a table in MySQL

For Mysql 5.6.18 use the following command

ALTER TABLE `old_table` RENAME TO `new_table`

Also if there is an error saying ".... near RENAME TO ..." try removing the tick `

Twitter Bootstrap inline input with dropdown

Daniel Farrell's Bootstrap Combobox does the job perfectly. Here's an example from his GitHub repository.

  // bonus: add a placeholder_x000D_
  $('.combobox').attr('placeholder', 'For example, start typing "Pennsylvania"');_x000D_
<link rel="stylesheet" href="">_x000D_
<link rel="stylesheet" href="">_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<select class="combobox form-control">_x000D_
  <option value="PA">Pennsylvania</option>_x000D_
  <option value="CT">Connecticut</option>_x000D_
  <option value="NY">New York</option>_x000D_
  <option value="MD">Maryland</option>_x000D_
  <option value="VA">Virginia</option>_x000D_

As an added bonus, I've included a placeholder in script since applying it to the markup does not hold.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.

Android Dialog: Removing title bar

I'm using next variant:

Activity of my custom Dialog:

public class AlertDialogue extends AppCompatActivity {

    Button btnOk;
    TextView textDialog;

    protected void onCreate(Bundle savedInstanceState) {

        textDialog = (TextView)findViewById( ;
        textDialog.setText("Hello, I'm the dialog text!");

        btnOk = (Button) findViewById(;
        btnOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""

        android:text="Hello, I'm the dialog text!"
        app:layout_constraintTop_toTopOf="parent" />

        app:layout_constraintTop_toBottomOf="@+id/text_dialog" />



<activity android:name=".AlertDialogue"


<style name="AlertDialogNoTitle" parent="Theme.AppCompat.Light.Dialog">
        <item name="android:windowNoTitle">true</item>

Serializing with Jackson (JSON) - getting "No serializer found"?

For Oracle Java applications, add this after the ObjectMapper instantiation:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

Should a function have only one return statement?

I often have several statements at the start of a method to return for "easy" situations. For example, this:

public void DoStuff(Foo foo)
    if (foo != null)

... can be made more readable (IMHO) like this:

public void DoStuff(Foo foo)
    if (foo == null) return;


So yes, I think it's fine to have multiple "exit points" from a function/method.

SQL Server Convert Varchar to Datetime


Fastest JSON reader/writer for C++

Ugliest interface possible, but does what you ask. Zero allocations. Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient


implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

How do I put a variable inside a string?

You just have to cast the num varriable into a string using


Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception


Why can't I have abstract static methods in C#?

This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to type instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.

In this context you may want to do something like this:

void Catch<TAnimal>() where TAnimal : Animal
    string scientificName = TAnimal.ScientificName; // abstract static property
    Console.WriteLine($"Let's catch some {scientificName}");

And here the capacity to express static members that can be specialized by subclasses totally makes sense!

Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.

The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain abstract members (here Animal):

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
    public static SpeciesFor<TAnimal> Instance { get { … } }

    // abstract "static" members

    public abstract string ScientificName { get; }

public abstract class Animal { … }

Now we would like to make this work:

void Catch<TAnimal>() where TAnimal : Animal
    string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
    Console.WriteLine($"Let's catch some {scientificName}");

Of course we have two problems to solve:

  1. How do we allow and force an implementer of a subclass of Animal to associate a specific instance of SpeciesFor<TAnimal> to this subclass?
  2. How does the property SpeciesFor<TAnimal>.Instance retrieve this information?

Here is how we can solve 1:

public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
    private Animal(…) {}
    public abstract class OfSpecies<TSpecies> : Animal<TSelf>
        where TSpecies : SpeciesFor<TSelf>, new()
        protected OfSpecies(…) : base(…) { }

By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.

For 2 we can provide the following implementation:

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
    private static SpeciesFor<TAnimal> _instance;

    public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();

    private static SpeciesFor<TAnimal> MakeInstance()
        Type t = typeof(TAnimal);
        while (true)
            if (t.IsConstructedGenericType
                    && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
                return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
            t = t.BaseType;
            if (t == null)
                throw new InvalidProgramException();

    // abstract "static" members

    public abstract string ScientificName { get; }

How can we be sure that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.

Et voilà:

public class CatSpecies : SpeciesFor<Cat>
    // overriden "static" members

    public override string ScientificName => "Felis catus";
    public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
    public override Cat Clone(Cat a) { … }
    public override Cat Breed(Cat a1, Cat a2) { … }

public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
    // overriden members

    public override string CuteName { get { … } }

public class DogSpecies : SpeciesFor<Dog>
    // overriden "static" members

    public override string ScientificName => "Canis lupus familiaris";
    public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
    public override Dog Clone(Dog a) { … }
    public override Dog Breed(Dog a1, Dog a2) { … }

public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
    // overriden members

    public override string CuteName { get { … } }

public class Program
    public static void Main()
    public static void ConductCrazyScientificExperimentsWith<TAnimal>()
        where TAnimal : Animal<TAnimal>
        // Look Ma! No animal instance polymorphism!
        TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
        TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
        TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
            "The confederation of mad scientists is happy to announce the birth " +
            $"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");

A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            return true

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            return true

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Fragment pressing back button

Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.

One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.

public boolean onBackPressed() {
      // Do something
      return true; //Back press consumed.
   } else {
      // Back-press not consumed. Let Activity handle it
      return false;

Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this

public void onBackPressed() {

This post has this pattern described in detail

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

checking memory_limit in PHP

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

How to join a slice of strings into a single string?

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

How to replace multiple strings in a file using PowerShell

To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'

$original_file = 'path\'
$destination_file =  'path\'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
            $line = $line -replace $_.Key, $_.Value
} | Set-Content -Path $destination_file

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link


CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;

Determine a user's timezone

One possible option is to use the Date header field, which is defined in RFC 7231 and is supposed to include the timezone. Of course, it is not guaranteed that the value is really the client's timezone, but it can be a convenient starting point.

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

Why calling react setState method doesn't mutate the state immediately?

Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.

Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -

Hence -

    console.log(; // will give undefined or unupdated value

as it takes time to update. To achieve the above process -

    this.setState({data:value},function () {