Programs & Examples On #Lvm

lvm (logical volume manager) is a software that allows disk partitionning by hiding the physical limitations of the underlying disks. It can make logical partitions from separate physical partitions even on separate disks, hide mirroring, allow increasing the size of a logical volume while used and so on

resize2fs: Bad magic number in super-block while trying to open

To resize the existing volume mounted

sudo mount -t xfs /dev/sdf /opt/data/

mount: /opt/data: /dev/nvme1n1 already mounted on /opt/data.

sudo xfs_growfs /opt/data/

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)


An alternative Solution could be converting your collection in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString().

Example using Google's Gson:




public static void printJsonString(Object o) {
    GsonBuilder gsonBuilder = new GsonBuilder();
     * Some options for GsonBuilder like setting dateformat or pretty printing
    Gson gson = gsonBuilder.create();
    String json= gson.toJson(o);

Error: Execution failed for task ':app:clean'. Unable to delete file

If you are testing with a local backend (java servlet on local google app engine) the running process blocks some files. So you are not able to live deploy. So in this case you can solve this by stopping the local backend before starting clean or build. You find the option under "Run -> Stop backend".

og:type and valid values : constantly being parsed as og:type=website

As of May 2018, you can find the full list here:

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines This object type represents a single author of a book. This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

Returns no data as of April 4, 2018.

An action representing someone rating a book.

Returns no data as of April 4, 2018.

An action representing someone reading a book.

Returns no data as of April 4, 2018.

An action representing someone wanting to read a book. This object type represents a place of business that has a location, operating hours and contact information.

Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

Returns no data as of April 4, 2018.

An action representing someone running a course.

Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself. This object type represents a single song.

news.publishes An action representing someone publishing a news article.

Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store. This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user. This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items. This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of. This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.
Returns no data as of April 4, 2018.

An action representing someone watching video content.

How to query DATETIME field using only date in Microsoft SQL Server?

Test this query.

SELECT *,DATE(chat_reg_date) AS is_date,TIME(chat_reg_time) AS is_time FROM chat WHERE chat_inbox_key='$chat_key' 
                         ORDER BY is_date DESC, is_time DESC

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $result = curl_exec($ch);
    return $result;

jQuery - how to write 'if not equal to' (opposite of ==)


For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

Get first element from a dictionary

Note that to call First here is actually to call a Linq extension of IEnumerable, which is implemented by Dictionary<TKey,TValue>. But for a Dictionary, "first" doesn't have a defined meaning. According to this answer, the last item added ends up being the "First" (in other words, it behaves like a Stack), but that is implementation specific, it's not the guaranteed behavior. In other words, to assume you're going to get any defined item by calling First would be to beg for trouble -- using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.

Just use the Linq First():

var first = like.First();
string key = first.Key;
Dictionary<string,string> val = first.Value;

Note that using First on a dictionary gives you a KeyValuePair, in this case KeyValuePair<string, Dictionary<string,string>>.

Note also that you could derive a specific meaning from the use of First by combining it with the Linq OrderBy:

var first = like.OrderBy(kvp => kvp.Key).First();

Error: «Could not load type MvcApplication»

I was getting this error because I was running the project despite some compile time errors. This I didn't notice.

go get results in 'terminal prompts disabled' error for github private repo

1st -- go get will refuse to authenticate on the command line. So you need to cache the credentials in git. Because I use osx I can use osxkeychain credential helper.

2nd For me, I have 2FA enabled and thus could not use my password to auth. Instead I had to generate a personal access token to use in place of the password.

  1. setup osxkeychain credential helper
  2. If using TFA instead of using your password, generate a personal access token with repo scope
  3. git clone a private repo just to make it cache the password git clone and used your username for username and the generated personal access token for password.
  4. Removed the just cloned repo and retest to ensure creds were cached -- git clone and this time wasnt asked for creds.

    1. go get will work with any repos that the personal access token can access. You may have to repeat the steps with other accounts / tokens as permissions vary.

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();


And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

How do I remove a comma off the end of a string?

Precede that with:

if(substr($string, -1)==",")

How to get selenium to wait for ajax response?

If using python, you may use this function, which clicks the button and waits for the DOM change:

def click_n_wait(driver, button, timeout=5):
    source = driver.page_source
    def compare_source(driver):
            return source != driver.page_source
        except WebDriverException:
    WebDriverWait(driver, timeout).until(compare_source)

(CREDIT: based on this stack overflow answer)

SQL Server Management Studio missing

I know this is an old question, but I've just had the same frustrating issue for a couple of hours and wanted to share my solution. In my case the option "Managements Tools" wasn't available in the installation menu either. It wasn't just greyed out as disabled or already installed, but instead just missing, it wasn't anywhere on the menu.

So what finally worked for me was to use the Web Platform Installer 4.0, and check this for installation: Products > Database > "Sql Server 2008 R2 Management Objects". Once this is done, you can relaunch the installation and "Management Tools" will appear like previous answers stated.

Note there could also be a "Sql Server 2012 Shared Management Objects", but I think this is for different purposes.

Hope this saves someone the couple of hours I wasted into this.

How to convert an NSString into an NSNumber

I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?

All I pretty much did was:

double myDouble = [myString doubleValue];

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token (leave some overload method)

 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
public final void removeCallbacks(Runnable r, Object token)
    mQueue.removeMessages(this, r, token);

 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);

 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
} do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n =;
            mMessages = n;
            p = n;

        // Remove all messages after front.
        while (p != null) {
            Message n =;
            if (n != null) {
                if ( == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn =;
           = nn;
            p = n;

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n =;
            mMessages = n;
            p = n;

        // Remove all messages after front.
        while (p != null) {
            Message n =;
            if (n != null) {
                if ( == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn =;
           = nn;
            p = n;

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && == h
                && (object == null || p.obj == object)) {
            Message n =;
            mMessages = n;
            p = n;

        // Remove all messages after front.
        while (p != null) {
            Message n =;
            if (n != null) {
                if ( == h && (object == null || n.obj == object)) {
                    Message nn =;
           = nn;
            p = n;

Enabling/installing GD extension? --without-gd

For PHP7.0 use (php7.1-gd, php7.2-gd, php7.3-gd and php7.4-gd are also available):

sudo apt-get install php7.0-gd

and than restart your webserver.

PHP + MySQL transactions examples

Please check which storage engine you are using. If it is MyISAM, then Transaction('COMMIT','ROLLBACK') will not be supported because only the InnoDB storage engine, not MyISAM, supports transactions.

How do I automatically scroll to the bottom of a multiline text box?

I found a simple difference that hasn't been addressed in this thread.

If you're doing all the ScrollToCarat() calls as part of your form's Load() event, it doesn't work. I just added my ScrollToCarat() call to my form's Activated() event, and it works fine.


It's important to only do this scrolling the first time form's Activated event is fired (not on subsequent activations), or it will scroll every time your form is activated, which is something you probably don't want.

So if you're only trapping the Activated() event to scroll your text when your program loads, then you can just unsubscribe to the event inside the event handler itself, thusly:

Activated -= new System.EventHandler(this.Form1_Activated);

If you have other things you need to do each time your form is activated, you can set a bool to true the first time your Activated() event is fired, so you don't scroll on subsequent activations, but can still do the other things you need to do.

Also, if your TextBox is on a tab that isn't the SelectedTab, ScrollToCarat() will have no effect. So you need at least make it the selected tab while you're scrolling. You can wrap the code in a YourTab.SuspendLayout(); and YourTab.ResumeLayout(false); pair if your form flickers when you do this.

End of edit

Hope this helps!

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

Docker is in volume in use, but there aren't any Docker containers

Currently you can use what docker offers now for a general and more complete cleaning:

docker system prune

To additionally remove any stopped containers and all unused images (not just dangling images), add the -a flag to the command:

docker system prune -a

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf"

What does the symbol \0 mean in a string-literal?

Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:

$ cat junk.c
#include <stdio.h>

char* string = "Hello\0";

int main(int argv, char** argc)
    printf("-->%s<--\n", string);
$ gcc -S junk.c
$ cat junk.s

... eliding the unnecessary parts ...

    .string "Hello"
    .string ""


    .string "-->%s<--\n"


Note here how the string I used for printf is just "-->%s<---\n" while the global string is in two parts: "Hello" and "". The GNU assembler also terminates strings with an implicit NUL character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NULs. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S (for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.

How to install Intellij IDEA on Ubuntu?

try simple way to install intellij idea

Install IntelliJ on Ubuntu using Ubuntu Make

You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:

  1. sudo apt install ubuntu-make

Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:

  1. umake ide idea

To install the IntelliJ IDEA Ultimate edition, use the command below:

  1. umake ide idea-ultimate

To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:

  1. umake -r ide idea
  2. umake -r ide idea-ultimate

you may visit for more option.

How to make a window always stay on top in .Net?

I was searching to make my WinForms application "Always on Top" but setting "TopMost" did not do anything for me. I knew it was possible because WinAmp does this (along with a host of other applications).

What I did was make a call to "user32.dll." I had no qualms about doing so and it works great. It's an option, anyway.

First, import the following namespace:

using System.Runtime.InteropServices;

Add a few variables to your class declaration:

private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;

Add prototype for user32.dll function:

[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

Then in your code (I added the call in Form_Load()), add the call:

SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

Hope that helps. Reference

How to set Java SDK path in AndroidStudio?

Generally speaking, it is set in the "Project Structure" dialog.

Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.

enter image description here

To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".

Older Versions

Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.

To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.

How to connect Robomongo to MongoDB

I was able to connect Robomongo to a remote instance of MongoDB running on Mongo Labs using the connection string as follows:

  1. Download the latest version of Robomongo. I downloaded 0.9 RC6 from here.

  2. From the connection string, populate the server address and port numbers as follows.

    Connection settings

  3. Populate DB name and username and password as follows under the authentication tab.

    Authentication settings

  4. Test the connection.

    Test connection

    Enter image description here

Open youtube video in Fancybox jquery

If you wanna add autoplay function to it. Simply replace

this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 


this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',

also you can do the same with vimeo

this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),


this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',

Unit testing click event in Angular

I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52) by using the tick function with the same (or greater) amount of milliseconds as in original setTimeout call.

For example, if I had a setTimeout(() => {...}, 2500); (so it will trigger after 2500 ms), I would call tick(2500), and that would solve the problem.

What I had in my component, as a reaction on a Delete button click:

delete() {
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
          }, 2500); // I wait for 2.5 seconds before redirect

Her is my working test:

it('should delete the entity', fakeAsync(() => { = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    // more expects here..
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;; // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    // more expects here..

P.S. Great explanation on fakeAsync and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)

Why is lock(this) {...} bad?

It is bad form to use this in lock statements because it is generally out of your control who else might be locking on that object.

In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.

A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using this violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on this unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.

Finally, there is the common misconception that lock(this) actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter to lock merely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.

This is why it's bad to use strings as the keys in lock statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an Object instance will do nicely.

Run the following C# code as an example.

public class Person
    public int Age { get; set;  }
    public string Name { get; set; }

    public void LockThis()
        lock (this)

class Program
    static void Main(string[] args)
        var nancy = new Person {Name = "Nancy Drew", Age = 15};
        var a = new Thread(nancy.LockThis);
        var b = new Thread(Timewarp);
        var anotherNancy = new Person { Name = "Nancy Drew", Age = 50 };
        var c = new Thread(NameChange);

    static void Timewarp(object subject)
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // A lock does not make the object read-only.
        lock (person.Name)
            while (person.Age <= 23)
                // There will be a lock on 'person' due to the LockThis method running in another thread
                if (Monitor.TryEnter(person, 10) == false)
                    Console.WriteLine("'this' person is locked!");
                else Monitor.Exit(person);
                if(person.Age == 18)
                    // Changing the 'person.Name' value doesn't change the lock...
                    person.Name = "Nancy Smith";
                Console.WriteLine("{0} is {1} years old.", person.Name, person.Age);

    static void NameChange(object subject)
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // You should avoid locking on strings, since they are immutable.
        if (Monitor.TryEnter(person.Name, 30) == false)
            Console.WriteLine("Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".");
        else Monitor.Exit(person.Name);

        if (Monitor.TryEnter("Nancy Drew", 30) == false)
            Console.WriteLine("Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!");
        else Monitor.Exit("Nancy Drew");
        if (Monitor.TryEnter(person.Name, 10000))
            string oldName = person.Name;
            person.Name = "Nancy Callahan";
            Console.WriteLine("Name changed from '{0}' to '{1}'.", oldName, person.Name);
        else Monitor.Exit(person.Name);

Console output

'this' person is locked!
Nancy Drew is 16 years old.
'this' person is locked!
Nancy Drew is 17 years old.
Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string "Nancy Drew".
'this' person is locked!
Nancy Smith is 18 years old.
'this' person is locked!
Nancy Smith is 19 years old.
'this' person is locked!
Nancy Smith is 20 years old.
Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!
'this' person is locked!
Nancy Smith is 21 years old.
'this' person is locked!
Nancy Smith is 22 years old.
'this' person is locked!
Nancy Smith is 23 years old.
'this' person is locked!
Nancy Smith is 24 years old.
Name changed from 'Nancy Drew' to 'Nancy Callahan'.

How to change DatePicker dialog color for Android 5.0

The reason why Neil's suggestion results in a fullscreen DatePicker is the choice of parent theme:

<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
    <item name="colorAccent">@color/blue_500</item>

Moreover, if you go this route, you have to specify the theme while creating the DatePickerDialog:

new DatePickerDialog(MainActivity.this,, new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //DO SOMETHING
}, 2015, 02, 26).show();

This, in my opinion, is not good. One should try to keep the styling out of java and inside styles.xml/themes.xml.

I do agree that Neil's suggestion, with a bit of change (changing the parent theme to say, Theme.Material.Light.Dialog) will get you the desired result. But, here's the other way:

On first inspection, we come across datePickerStyle which defines things such as: headerBackground(what you are trying to change), dayOfWeekBackground, and a few other text-colors and text-styles.

Overriding this attribute in your app's theme will not work. DatePickerDialog uses a separate theme assignable by the attribute datePickerDialogTheme. So, for our changes to take affect, we must override datePickerStyle inside an overriden datePickerDialogTheme.

Here we go:

Override datePickerDialogTheme inside your app's base theme:

<style name="AppBaseTheme" parent="android:Theme.Material.Light">
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>

Define MyDatePickerDialogTheme. The choice of parent theme will depend on what your app's base theme is: it could be either Theme.Material.Dialog or Theme.Material.Light.Dialog:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>

We have overridden datePickerStyle with the style MyDatePickerStyle. The choice of parent will once again depend on what your app's base theme is: either Widget.Material.DatePicker or Widget.Material.Light.DatePicker. Define it as per your requirements:

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/chosen_header_bg_color</item>

Currently, we are only overriding headerBackground which by default is set to ?attr/colorAccent (this is also why Neil suggestion works in changing the background). But there's quite a lot of customization possible:


If you don't want this much control (customization), you don't need to override datePickerStyle. colorAccent controls most of the DatePicker's colors. So, overriding just colorAccent inside MyDatePickerDialogTheme should work:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:colorAccent">@color/date_picker_accent</item>

    <!-- No need to override 'datePickerStyle' -->
    <!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->

Overriding colorAccent gives you the added benefit of changing OK & CANCEL text colors as well. Not bad.

This way you don't have to provide any styling information to DatePickerDialog's constructor. Everything has been wired properly:

DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

 }, 2015, 5, 22);;

Updating GUI (WPF) using a different thread

You may use a delegate to solve this issue. Here is an example that is showing how to update a textBox using diffrent thread

public delegate void UpdateTextCallback(string message);

private void TestThread()
    for (int i = 0; i <= 1000000000; i++)
            new UpdateTextCallback(this.UpdateText),
            new object[] { i.ToString() }
private void UpdateText(string message)
    richTextBox1.AppendText(message + "\n");

private void button1_Click(object sender, RoutedEventArgs e)
   Thread test = new Thread(new ThreadStart(TestThread));

TestThread method is used by thread named test to update textBox

Bootstrap - Removing padding or margin when screen size is smaller

I have had this problem occur on sites that used similar formatting and code and I have racked my brain over what was the missing detail that made some of my sites work, and some not.

For Bootstrap 3: The answer for me was not in rewriting css for .container-fluid, .row or resetting margins, the consistent pattern that I realized was the length of longer words were throwing off the design and creating margins.

The solution steps:

  1. Test your page by temporarily deleting sections that contain containers and test your site on small browsers. This will identify your problem container.

  2. You may have a div formatting problem. If you do, fix it. If all is well then:

  3. Identify if you have used long words that are not wrapping. If you cannot change the word (like for tag lines or slogans, etc.)

Solution 1: Format the font to smaller size in your media query for smaller screen (I usually find @media (max-width: 767px) to be sufficient).


Solution 2:

@media (max-width: 767px){

h1, h2, h3 {word-wrap: break-word;}

Property 'value' does not exist on type 'EventTarget'

I believe it must work but any ways I'm not able to identify. Other approach can be,

<textarea (keyup)="emitWordCount(myModel)" [(ngModel)]="myModel"></textarea>

export class TextEditorComponent {
   @Output() countUpdate = new EventEmitter<number>();

   emitWordCount(model) {
         (model.match(/\S+/g) || []).length);

Relative frequencies / proportions with dplyr

@Henrik's is better for usability as this will make the column character and no longer numeric but matches what you asked for...

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = paste0(round(100 * n/sum(n), 0), "%"))

##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

EDIT Because Spacedman asked for it :-)

as.rel_freq <- function(x, rel_freq_col = "rel.freq", ...) {
    class(x) <- c("rel_freq", class(x))
    attributes(x)[["rel_freq_col"]] <- rel_freq_col

print.rel_freq <- function(x, ...) {
    freq_col <- attributes(x)[["rel_freq_col"]]
    x[[freq_col]] <- paste0(round(100 * x[[freq_col]], 0), "%")   
    class(x) <- class(x)[!class(x)%in% "rel_freq"]

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = n/sum(n)) %>%

## Source: local data frame [4 x 4]
## Groups: am
##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

Create 3D array using Python

You can also use a nested for loop like shown below

n = 3
arr = []
for x in range(n):
    for y in range(n):
        for z in range(n):

Create a hexadecimal colour based on a string with JavaScript

All you really need is a good hash function. On node, I just use

const crypto = require('crypto');
function strToColor(str) {
    return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);

Firestore Getting documents id from collection gets the UID.

Combine with the rest of the data for one object like so:

Object.assign({ uid: },

On - window.location.hash - Change?

I was using this in a react application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

window.addEventListener('hashchange', doSomethingWithChangeFunction());


doSomethingWithChangeFunction () { 
    // Get new hash value
    let urlParam = window.location.hash;
    // Do something with new hash value

Worked a treat, works with forward and back browser buttons and also in browser history.

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

Conditional Logic on Pandas DataFrame

In this specific example, where the DataFrame is only one column, you can write this elegantly as:

df['desired_output'] = df.le(2.5)

le tests whether elements are less than or equal 2.5, similarly lt for less than, gt and ge.

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

Converting 'ArrayList<String> to 'String[]' in Java

If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:

List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);

There are a few more preallocated empty arrays of different types in ArrayUtils.

Also we can trick JVM to create en empty array for us this way:

String[] array = list.toArray(ArrayUtils.toArray());

// or if using static import
String[] array = list.toArray(toArray());

But there's really no advantage this way, just a matter of taste, IMO.

How to run single test method with phpunit?

Here's the more generic answer:

If you are sure the method name is unique you can only filter by method name (this works for me)

phpunit --filter {TestMethodName}

However it is safer to specify the file path/reference as well

phpunit --filter {TestMethodName} {FilePath}


phpunit --filter testSaveAndDrop reference/to/escalation/EscalationGroupTest.php

Quick note: I've noticed that if I have a function named testSave and another function named testSaveAndDrop using command phpunit --filter testSave will also run testSaveAndDrop and any other function that starts with testSave*, it's weird!!

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:


So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"";

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

How to start MySQL server on windows xp

Here is the ZIP file that I had downloaded:

Here are the steps to start MYSQL Server (mysql-5.7.15-winx64) for the first time on Windows:

  1. Create a new folder named "data" in MYSQL installation directory (i.e. in the same location as where "bin" directory is located. For me it is: C:\programs\mysql-5.7.15-winx64\mysql-5.7.15-winx64. This location will vary as per the location where you have extracted the MYSQL zip file)
  2. From here I will use my MYSQL folder location as reference. Go to: C:\programs\mysql-5.7.15-winx64\mysql-5.7.15-winx64\bin and execute the command: mysqld --initialize-insecure or mysqld --initialize depending on whether you want the server to generate a random initial password for the 'root'@'localhost' account.
  3. To start the DB, go to: C:\programs\mysql-5.7.15-winx64\mysql-5.7.15-winx64\bin and execute mysqld --console You can see the start-up logs being printed.
  4. To connect to DB, go to: C:\programs\mysql-5.7.15-winx64\mysql-5.7.15-winx64\bin and execute mysql -u root -p. When prompted, Enter password if it has been set or else just hit "Enter" button to connect

What Regex would capture everything from ' mark to the end of a line?


I believe you need the option, Multiline.

What is DOM element?

It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.

How to get all files under a specific directory in MATLAB?

This is a handy function for getting filenames, with the specified format (usually .mat) in a root folder!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder,, ...
            filenames, ...
            'UniformOutput', false ...

In your case, you can use the following snippet :)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };

How to get values from selected row in DataGrid for Windows Form Application?


Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.


if (dataGridView1.SelectedRows.Count != 0)
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];

More Information

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

jQuery - Trigger event when an element is removed from the DOM

For those who use jQuery UI:

jQuery UI has overridden some of the jQuery methods to implement a remove event that gets handled not only when you explicitly remove the given element, but also if the element gets removed from the DOM by any self-cleaning jQuery methods (e.g. replace, html, etc.). This basically allows you to put a hook into the same events that get fired when jQuery is "cleaning up" the events and data associated with a DOM element.

John Resig has indicated that he's open to the idea of implementing this event in a future version of jQuery core, but I'm not sure where it stands currently.

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.


Source :

Make Font Awesome icons in a circle?

Font Awesome icons are inserted as a :before. Therefore you can style either your i or a like so:

.i {
   background: #fff;
   border-radius: 50%;
   display: inline-block;
   height: 20px;   
   width: 20px;

<a href="#"><i class="fa fa-facebook fa-lg"></i></a>

Return list using select new in LINQ

public List<Object> GetProjectForCombo()
   using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
     var query = db.Project
                 return new ProjectInfo{Name=p.ProjectName, Id=p.ProjectId);       

     return query.ToList<Object>();


Quickest way to find missing number in an array of numbers

The solution that doesn't involve repetitive additions or maybe the n(n+1)/2 formula doesn't get to you at an interview time for instance.

You have to use an array of 4 ints (32 bits) or 2 ints (64 bits). Initialize the last int with (-1 & ~(1 << 31)) >> 3. (the bits that are above 100 are set to 1) Or you may set the bits above 100 using a for loop.

  1. Go through the array of numbers and set 1 for the bit position corresponding to the number (e.g. 71 would be set on the 3rd int on the 7th bit from left to right)
  2. Go through the array of 4 ints (32 bit version) or 2 ints(64 bit version)

    public int MissingNumber(int a[])
        int bits = sizeof(int) * 8;
        int i = 0;
        int no = 0;
        while(a[i] == -1)//this means a[i]'s bits are all set to 1, the numbers is not inside this 32 numbers section
            no += bits;
        return no + bits - Math.Log(~a[i], 2);//apply NOT (~) operator to a[i] to invert all bits, and get a number with only one bit set (2 at the power of something)

Example: (32 bit version) lets say that the missing number is 58. That means that the 26th bit (left to right) of the second integer is set to 0.

The first int is -1 (all bits are set) so, we go ahead for the second one and add to "no" the number 32. The second int is different from -1 (a bit is not set) so, by applying the NOT (~) operator to the number we get 64. The possible numbers are 2 at the power x and we may compute x by using log on base 2; in this case we get log2(64) = 6 => 32 + 32 - 6 = 58.

Hope this helps.

Fastest way of finding differences between two files in unix?

Another option:

sort file1 file2 | uniq -u > file3

If you want to see just the duplicate entries use "uniq -d" option:

sort file1 file2 | uniq -d > file3

Iterating through list of list in Python

This traverse generator function can be used to iterate over all the values:

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

W3WP.EXE using 100% CPU - where to start?

  1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
  2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
  3. Load testing, using tools such as Visual Studio Team Test or WCAT
  4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
  5. Use logparser to see which requests arrived at the time of the CPU spike
  6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
  7. CPU and memory profiling (can be difficult on a production system)
  8. Process Explorer
  9. Windows Resource Monitor
  10. Detailed error logging
  11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
  12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

How to print pandas DataFrame without index

The line below would hide the index column of DataFrame when you print

Update: tested w Python 3.7

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

Final cannot be applied to non-virtual functions.

error: only virtual member functions can be marked 'final'

It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given

struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo

a->foo() will always call A::foo.

But, if A::foo was virtual, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.

The question is though, why allow final on virtual functions. If you have a deep hierarchy:

struct A            { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };

Then the final puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo, but it a class extends C then it is not allowed.

So it probably doesn't make sense to make the 'top-level' foo final, but it might make sense lower down.

(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)

How to convert hex to ASCII characters in the Linux shell?

Bash one-liner

echo -n "5a" | while read -N2 code; do printf "\x$code"; done

How do I close a tkinter window?

I use below codes for the exit of Tkinter window:

from tkinter import*
root.bind("<Escape>",lambda q:root.destroy())


from tkinter import*


from tkinter import*


from tkinter import*

How to connect to SQL Server from command prompt with Windows authentication

You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:

sqlcmd /S  /d  -E

If you want to use SQL Server authentication you could try this:

sqlcmd /S  /d -U -P 


/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234

Hope this helps!

How can I make SMTP authenticated in C#

How do you send the message?

The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

JavaScript can read the DOM and render a fairly accurate representation of that using canvas. I have been working on a script which converts HTML into a canvas image. Decided today to make an implementation of it into sending feedbacks like you described.

The script allows you to create feedback forms which include a screenshot, created on the client's browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

It does not require any rendering from the server, as the whole image is created on the client's browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.

Still quite limited browser compatibility (not because more couldn't be supported, just haven't had time to make it more cross browser supported).

For more information, have a look at the examples here:

edit The html2canvas script is now available separately here and some examples here.

edit 2 Another confirmation that Google uses a very similar method (in fact, based on the documentation, the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team:

Creating layout constraints programmatically

When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.

Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.

The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero or simply init.

To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:

[self.view addConstraints:[NSLayoutConstraint

[self.view addConstraints:[NSLayoutConstraint

Verbally describing this layout reads as follows starting with the vertical constraint:

myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.

If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748) parameter in the visual format text. If you think that the (>=748) parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|) or bar with space (|-, -|) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.

In regards to your second question:

Using NSDictionaryOfVariableBindings(self.myView) (if you had an property setup for myView) and feeding that into your VFL to use self.myView in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:. See here for a similar question and answer.

How to stop/shut down an elasticsearch node?

If you just want to apply new config you don't need to shut it down.

$ sudo service elasticsearch restart

But if you want to shut it down anyway:

$ sudo service elasticsearch stop


$ sudo systemctl stop elasticsearch.service

$ sudo systemctl restart elasticsearch.service


docker restart <elasticsearch-container-name or id>

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP:

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server:

Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

nvarchar(max) still being truncated

Problem seems to be associated with the SET statement. I think the expression can't be more than 4,000 bytes in size. There is no need to make any changes to any settings if all you are trying to do is to assign a dynamically generated statement that is more than 4,000 characters. What you need to do is to split your assignment. If your statement is 6,000 characters long, find a logical break point and then concatenate second half to the same variable. For example:

SET @Query = 'SELECT ....' [Up To 4,000 characters, then rest of statement as below]

SET @Query = @Query + [rest of statement]

Now run your query as normal i.e. EXEC ( @Query )

What are the differences between numpy arrays and matrices? Which one should I use? recommends that you use arrays:

*'array' or 'matrix'? Which should I use? - Short answer

Use arrays.

  • They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.

  • There is a clear distinction between element-wise operations and linear algebra operations.

  • You can have standard vectors or row/column vectors if you like.

The only disadvantage of using the array type is that you will have to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).

call a function in success of datatable ajax call

Try Following Code.

       var oTable = $('#app-config').dataTable(
            "bAutoWidth": false,                                                
            "bProcessing" : true,
            "bServerSide" : true,
            "sPaginationType" : "full_numbers",
            "sAjaxSource" : url,                    
            "fnServerData" : function(sSource, aoData, fnCallback) {
                alert("sSource"+ sSource);
                alert("aoData"+ aoData);
                    "dataType" : 'json',
                    "type" : "GET",
                    "url" : sSource,
                    "data" : aoData,
                    "success" : fnCallback
                }).success( function(){  alert("This Function will execute after data table loaded");   });

What is the difference between __str__ and __repr__?

On page 358 of the book Python scripting for computational science by Hans Petter Langtangen, it clearly states that

  • The __repr__ aims at a complete string representation of the object;
  • The __str__ is to return a nice string for printing.

So, I prefer to understand them as

  • repr = reproduce
  • str = string (representation)

from the user's point of view although this is a misunderstanding I made when learning python.

A small but good example is also given on the same page as follows:


In [38]: str('s')
Out[38]: 's'

In [39]: repr('s')
Out[39]: "'s'"

In [40]: eval(str('s'))
Traceback (most recent call last):

  File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>

  File "<string>", line 1, in <module>

NameError: name 's' is not defined

In [41]: eval(repr('s'))
Out[41]: 's'

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

How to print a double with two decimals in Android?

You can use a DecimalFormat, or String.format("%.2f", a);

How to read Excel cell having Date with Apache POI?

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;

Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)

 String cellValue=String.valueOf(cell.getNumericCellValue());
          DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
          Date date = cell.getDateCellValue();
          cellValue = df.format(date);

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.


<div id="slider">


var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

In C, how should I read a text file and print all strings

You can use fgets and limit the size of the read string.

char *fgets(char *str, int num, FILE *stream);

You can change the while in your code to:

while (fgets(str, 100, file)) /* printf("%s", str) */;

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

Standard Android menu icons, for example refresh

Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:


Get request URL in JSP which is forwarded by Servlet

Try this instead:

String scheme = req.getScheme();             
String serverName = req.getServerName(); 
int serverPort = req.getServerPort();    
String uri = (String) req.getAttribute("javax.servlet.forward.request_uri");
String prmstr = (String) req.getAttribute("javax.servlet.forward.query_string");
String url = scheme + "://" +serverName + ":" + serverPort + uri + "?" + prmstr;

Note: You can't get HREF anchor from your url. Example, if you have url "toc.html#top" then you can get only "toc.html"

Note: req.getAttribute("javax.servlet.forward.request_uri") work only in JSP. if you run this in controller before JSP then result is null

You can use code for both variant:

public static String getCurrentUrl(HttpServletRequest req) {
    String url = getCurrentUrlWithoutParams(req);
    String prmstr = getCurrentUrlParams(req);
    url += "?" + prmstr;
    return url;

public static String getCurrentUrlParams(HttpServletRequest request) {
    return StringUtil.safeString(request.getQueryString());

public static String getCurrentUrlWithoutParams(HttpServletRequest request) {
    String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
    if (uri == null) {
        return request.getRequestURL().toString();
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String url = scheme + "://" + serverName + ":" + serverPort + uri;
    return url;

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

c# search string in txt file

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

                foreach (var line in File.ReadLines(pathToFile))
                    if (line.Contains("CustomerEN") && current == null)
                        current = new List<string>();
                    else if (line.Contains("CustomerEN") && current != null)
                string s = String.Join(",", current);

Find the version of an installed npm package

You can also view package.json to manually in a text editor, see what packages are dependencies. Use this if npm list isn't working as a manual alternative.

Java: How can I compile an entire directory structure of code ?

With Bash 4+, you can just enable globstar

shopt -s globstar

and then do

javac **/*.java

How to execute a shell script in PHP?

Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.

I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.

I would recommend moving the shell script to outside of the webroot

      $tempFolder = '/tmp';
      $webRootFolder = '/var/www';
      $scriptName = '';
      $moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
      $output = shell_exec($moveCommand);

In regards to the:

i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works

You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.

Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.


sudo su apache (or www-data)
cd /var/www
sh ./myscript

Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file

... voila

You should not use <Link> outside a <Router>

Write router in place of Main in render (last line in the code). Like this ReactDOM.render(router, document.getElementById('root'));

How to get back Lost phpMyAdmin Password, XAMPP

The question may be getting old, but I've struggled with the same issue just now.

After deleting passwords with resetroot.bat, as instructed by Nedshed, you can choose another password by going to http://localhost/security/index.php

Yes or No confirm box using jQuery

You can reuse your confirm:

    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                No: function() {
                param = false;

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);

Why doesn't TFS get latest get the latest?

Team Foundation Server (TFS) keeps track of its local copy in a hidden directory called $TF.When you issue the "get Latest Version", TFS looks into this folder and see weather I have the latest copy or not. If it does it will not download the latest copy. It does not matter if you have the original file or not. In fact you might have deleted the entire folder (as in my case) and TFS won't fetch the latest copy because it does not look into the actual file but the hidden directory where it records changes. The flaw with this design is, anything done outside the system will not be recorded in TFS. For example, you may go into Windows explorer, delete a folder or file and TFS wont recognize it. It will be totally blind. At least I would expect there Windows would not let you delete this file but it does!

One way to enforce the latest copy is to delete the hidden $TF folder manually. To do that, go to command prompt and navigate to the root folder where you project was checked out and issue this command

rd/s $tf                    // remove $TF folder and everything inside it

If you want to just check the hidden folder, you can do it using

dir /ah                    // display hidden files and folders

Note: If you do it, the tf will think you do not have any local copy even though you have it in files and it will sync up everything again.

Caution: Use this method at your own risk. Please do not use it on critical work.

How do I change the title of the "back" button on a Navigation Bar

I've found, that the easiest way to change the name of the back button is to set the view controllers title to the title of the back button, and then replacing the titleView in the view controllers navigation item to a custom label with it's real name.

Like this:


@implementation CustomViewController

- (NSString*)title {
    return @"Back Button Title";

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel* customTitleView = [[UILabel alloc] initWithFrame:CGRectZero];
    customTitleView.text = @"Navigation Bar Title";
    customTitleView.font = [UIFont boldSystemFontOfSize:20];
    customTitleView.backgroundColor = [UIColor clearColor];
    customTitleView.textColor = [UIColor whiteColor];
    customTitleView.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
    customTitleView.shadowOffset = CGSizeMake(0, -1);

    [customTitleView sizeToFit];

    self.navigationItem.titleView = [customTitleView autorelease];


This will make your title in UINavigationBar look as if it was native. Giving the view controller the ability to have seperated title and back button title.

In the case of view controller A and B, A is responsible for telling how it's back button should look, while B is displayed.

EDIT: This also maintains the back button native look (The left arrowed bar button item).

How to handle checkboxes in ASP.NET MVC forms?

In case you're wondering WHY they put a hidden field in with the same name as the checkbox the reason is as follows :

Comment from the sourcecode MVCBetaSource\MVC\src\MvcFutures\Mvc\ButtonsAndLinkExtensions.cs

Render an additional <input type="hidden".../> for checkboxes. This addresses scenarios where unchecked checkboxes are not sent in the request. Sending a hidden input makes it possible to know that the checkbox was present on the page when the request was submitted.

I guess behind the scenes they need to know this for binding to parameters on the controller action methods. You could then have a tri-state boolean I suppose (bound to a nullable bool parameter). I've not tried it but I'm hoping thats what they did.

SQL - Update multiple records in one query

Assuming you have the list of values to update in an Excel spreadsheet with config_value in column A1 and config_name in B1 you can easily write up the query there using an Excel formula like

=CONCAT("UPDATE config SET config_value = ","'",A1,"'", " WHERE config_name = ","'",B1,"'")

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character


Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

Android load from URL to Bitmap

Its Working in Pie OS Use this

    protected void onCreate() {

        if (android.os.Build.VERSION.SDK_INT >= 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();


        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(;
        Menu menu = bottomNavigationView.getMenu();
        MenuItem userImage = menu.findItem(;

        runOnUiThread(new Runnable() {
            public void run() {
                try {

                    URL url = new URL("");
                    Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

                    Log.e("keshav", "Bitmap " + myBitmap);
                    userImage.setIcon(new BitmapDrawable(getResources(), myBitmap));

                } catch (IOException e) {
                    Log.e("keshav", "Exception " + e.getMessage());

how to release localhost from Error: listen EADDRINUSE

To kill node server first run this command in your terminal :

  1. top
  2. open another window then copy the server id from the previous window: PID number -9 kill so now you killed your node server try again to run your app.

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

A very simple solution is to add the database name with your table name like if your DB name is DBMS and table is info then it will be for any query.

If your query is

select * from STUDENTREC where ROLL_NO=1;

it might show an error but

select * from DBMS.STUDENTREC where ROLL_NO=1; 

it doesn't because now actually your table is found.

Handling data in a PHP JSON Object

Just use it like it was an object you defined. i.e.

$trends = $json_output->trends;

Get class list for element with jQuery

$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})

How to get client IP address using jQuery

<html lang="en">
    <title>Jquery - get ip address</title>
    <script type="text/javascript" src="//"></script>

<h1>Your Ip Address : <span class="ip"></span></h1>

<script type="text/javascript">
    $.getJSON("", function (data) {


How to SFTP with PHP?

Install Flysystem:

composer require league/flysystem-sftp


use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;

$filesystem = new Filesystem(new SftpAdapter([
    'host' => '',
    'port' => 22,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',
    'root' => '/path/to/root',
    'timeout' => 10,
$filesystem->listFiles($path); // get file lists
$filesystem->read($path_to_file); // grab file
$filesystem->put($path); // upload file


How can I increase the JVM memory?

If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m

Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini file which is present in your Eclipse home directory.

To get the size of the JVM during Runtime you can use Runtime.totalMemory() which returns the total amount of memory in the Java virtual machine, measured in bytes.

mysqli_fetch_array while loop columns

Try this...

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

Ruby max integer

Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.

If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at

machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1

If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1 (or 2**62 - 1), because one bit is used to mark it as an integer instead of an object reference.

MySQL vs MongoDB 1000 reads

man,,, the answer is that you're basically testing PHP and not a database.

don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.

   foreach ($cursor as $obj)
        //echo $obj["thread_title"] . "<br><Br>";

while the other chunk is spend yacking up a bunch of rand numbers.

function get_15_random_numbers()
    $numbers = array();
        $numbers[] = mt_rand(1, 20000000) ;

    return $numbers;

then theres a major difference b/w implode and in.

and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.

$m = new Mongo();


$db = new AQLDatabase();

so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.


Bogus foreign key constraint fail

Cannot delete or update a parent row: a foreign key constraint fails (table1.user_role, CONSTRAINT FK143BF46A8dsfsfds@#5A6BD60 FOREIGN KEY (user_id) REFERENCES user (id))

What i did in two simple steps . first i delete the child row in child table like

mysql> delete from table2 where role_id = 2 && user_id =20;

Query OK, 1 row affected (0.10 sec)

and second step as deleting the parent

delete from table1 where id = 20;

Query OK, 1 row affected (0.12 sec)

By this i solve the Problem which means Delete Child then Delete parent

i Hope You got it. :)

JQuery - Call the jquery button click event based on name property

    //do stuff

in your case:

    //do stuff

Is there a "between" function in C#?

Here's a complete class.

/// <summary>
/// An extension class for the between operation
/// name pattern IsBetweenXX where X = I -> Inclusive, X = E -> Exclusive
/// <a href=""></a>
/// </summary>
public static class BetweenExtensions

    /// <summary>
    /// Between check <![CDATA[min <= value <= max]]> 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenII<T>(this T value, T min, T max) where T:IComparable<T>
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);

    /// <summary>
    /// Between check <![CDATA[min < value <= max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Inclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenEI<T>(this T value, T min, T max) where T:IComparable<T>
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) <= 0);

    /// <summary>
    /// between check <![CDATA[min <= value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Inclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>
    public static bool IsBetweenIE<T>(this T value, T min, T max) where T:IComparable<T>
        return (min.CompareTo(value) <= 0) && (value.CompareTo(max) < 0);

    /// <summary>
    /// between check <![CDATA[min < value < max]]>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value">the value to check</param>
    /// <param name="min">Exclusive minimum border</param>
    /// <param name="max">Exclusive maximum border</param>
    /// <returns>return true if the value is between the min & max else false</returns>

    public static bool IsBetweenEE<T>(this T value, T min, T max) where T:IComparable<T>
        return (min.CompareTo(value) < 0) && (value.CompareTo(max) < 0);

plus some unit test code

public class UnitTest1
    public void TestMethodIsBeetween()
        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(5.0, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.0));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenIE(4.9, 5.0));
        Assert.IsFalse(5.0.IsBetweenEE(4.9, 5.0));

        Assert.IsTrue(5.0.IsBetweenII(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEI(5.0, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(5.0, 5.1));
        Assert.IsFalse(5.0.IsBetweenEE(5.0, 5.1));

        Assert.IsTrue(5.0.IsBetweenII(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEI(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenIE(4.9, 5.1));
        Assert.IsTrue(5.0.IsBetweenEE(4.9, 5.1));

        Assert.IsFalse(5.0.IsBetweenII(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEI(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenIE(5.1, 4.9));
        Assert.IsFalse(5.0.IsBetweenEE(5.1, 4.9));


Close a MessageBox after several seconds


If you don't mind muddying your references a bit, you can include Microsoft.Visualbasic, and use this very short way.

Display the MessageBox

    (new System.Threading.Thread(CloseIt)).Start();

CloseIt Function:

public void CloseIt()
    System.Windows.Forms.SendKeys.SendWait(" ");

Now go wash your hands!

Where are $_SESSION variables stored?

The location of the $_SESSION variable storage is determined by PHP's session.save_path configuration. Usually this is /tmp on a Linux/Unix system. Use the phpinfo() function to view your particular settings if not 100% sure by creating a file with this content in the DocumentRoot of your domain:


Here is the link to the PHP documentation on this configuration setting:

How do I add the Java API documentation to Eclipse?

For OpenJDK 8 on Linux see:

The way that worked for me is:

  • The default is a symbolic link pointing to a non-existing folder ...
  • sudo apt-get install openjdk-8-source this adds this folder
  • locate ""
  • Eclipse: Window --> Preferences --> Java --> "Installed JREs", edit and point to (or open any JRE class like for example HashMap and attach source)

You should now see the JavaDoc when opening JRE classes via Ctrl+Shift+t, previously this was not possible, Eclipse may have got a docs from the default URL on mouse over methods but this requires a stable internet connection.

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    SELECT id, null some_value, 1 deleteMe
        SELECT id FROM target
        SELECT id FROM source
) source
   ON (target.ID = source.ID)
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
    INSERT (id, some_value, isDeleted) VALUES (, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;

select * from target;

1   new value 1  0
2   old value 2  1
3   new value 3  0

How to set variable from a SQL query?

Select @ModelID =m.modelid 
From   MODELS m
Where  m.areaid = 'South Coast'

In this case if you have two or more results returned then your result is the last record. So be aware of this if you might have two more records returned as you might not see the expected result.

What is the difference between git pull and git fetch + git rebase?


git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."

Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
(the difference between altering the way version history is recorded)

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)

If using javascript and jquery is not a problem I have this solution based on the code of @Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.

function applyResizeCSS(){
    var $i = $('img#imageToResize');
    var $c = $i.parent();
    var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();  
    if(i_ar > c_ar){
        $i.css( "width","100%");
        $i.css( "height","auto");          
        $i.css( "height","100%");
        $i.css( "width","auto");
var Oriwidth,Oriheight;
$(function() {
    $(window).resize(function() {

        Oriwidth  = this.width,
        Oriheight = this.height; 


For an HTML element like:

<img src="images/loading.gif" name="imageToResize" id="imageToResize"/> 

How to set time delay in javascript

you can use of promise

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));


sleep(2000).then(() => { console.log("World!"); });


await sleep(2000);

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK build tools are used to debug, build, run and test an Android application.

Android Build Tools can be used to develop and work from command line or IDE (i.e Eclipse or Android Studio).

Also used to connect Android devices and root them.(fastboot, adb and more..)

Always use the latest.(Recommended)

More Info on Android Build tools and commands

How to capture Curl output to a file?

A tad bit late, but I think the OP was looking for something like:

curl -K myfile.txt --trace-asci output.txt

How to read string from keyboard using C?

When reading input from any file (stdin included) where you do not know the length, it is often better to use getline rather than scanf or fgets because getline will handle memory allocation for your string automatically so long as you provide a null pointer to receive the string entered. This example will illustrate:

#include <stdio.h>
#include <stdlib.h>

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

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");

    free (line);  /* free memory allocated by getline */

    return 0;

The relevant parts being:

char *line = NULL;  /* forces getline to allocate with malloc */
size_t len = 0;     /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);

Setting line to NULL causes getline to allocate memory automatically. Example output:

$ ./getline_example

Enter string below [ctrl + d] to quit
A short string to test getline!

  read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL

  read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

So with getline you do not need to guess how long your user's string will be.

How to find difference between two Joda-Time DateTimes in minutes

DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();

In practice I think this will always give the same result as the answer based on Duration. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years().

In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.

Convert Difference between 2 times into Milliseconds?

You have to convert textbox's values to DateTime (t1,t2), then:

DateTime t1,t2;
t1 = DateTime.Parse(textbox1.Text);
t2 = DateTime.Parse(textbox2.Text);
int diff = ((TimeSpan)(t2 - t1)).TotalMilliseconds;

Or use DateTime.TryParse(textbox1, out t1); Error handling is up to you.

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:


Instead of filtering by the name, I would do this:


How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 


System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;

class MyClass {
    function calc($v) {
        return $v+2;

class MyChildClass extends MyClass{

class MyTraitChildClass extends MyClass{
    use A;

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;

class MyClass {
    function calc($v) {
        return $v+2;

class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;

class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;

    public function calc($v) {
      return $this->trait_calc($v)+.5;

print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at

AndroidStudio: Failed to sync Install build tools

In case you have error regarding 'SDK build-tools failed' while installing Android Studio, Then you can Download build-tools from -

Difference between ref and out parameters in .NET

out has gotten a new more succint syntax in C#7 and even more exciting is the C#7 tuple enhancements that are a more elegant choice than using ref and out IMHO.

How to add text inside the doughnut chart using Chart.js?

Alesana's solution works very nicely for me in general, but like others, I wanted to be able to specify where line breaks occur. I made some simple modifications to wrap lines at '\n' characters, as long as the text is already being wrapped. A more complete solution would force wrapping if there are any '\n' characters in the text, but I don't have time at the moment to make that work with font sizing. The change also centers a little better horizontally when wrapping (avoids trailing spaces). The code's below (I can't post comments yet).

It would be cool if someone put this plug-in on GitHub...

  beforeDraw: function(chart) {
    if ( {
      // Get ctx from string
      var ctx = chart.chart.ctx;

      // Get options from the center object in options
      var centerConfig =;
      var fontStyle = centerConfig.fontStyle || 'Arial';
      var txt = centerConfig.text;
      var color = centerConfig.color || '#000';
      var maxFontSize = centerConfig.maxFontSize || 75;
      var sidePadding = centerConfig.sidePadding || 20;
      var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
      // Start with a base font of 30px
      ctx.font = "30px " + fontStyle;

      // Get the width of the string and also the width of the element minus 10 to give it 5px side padding
      var stringWidth = ctx.measureText(txt).width;
      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      var widthRatio = elementWidth / stringWidth;
      var newFontSize = Math.floor(30 * widthRatio);
      var elementHeight = (chart.innerRadius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
      var minFontSize = centerConfig.minFontSize;
      var lineHeight = centerConfig.lineHeight || 25;
      var wrapText = false;

      if (minFontSize === undefined) {
        minFontSize = 20;

      if (minFontSize && fontSizeToUse < minFontSize) {
        fontSizeToUse = minFontSize;
        wrapText = true;

      // Set font settings to draw it correctly.
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      var centerY = (( + chart.chartArea.bottom) / 2);
      ctx.font = fontSizeToUse + "px " + fontStyle;
      ctx.fillStyle = color;

      if (!wrapText) {
        ctx.fillText(txt, centerX, centerY);

      var lines = [];
      var chunks = txt.split('\n');
      for (var m = 0; m < chunks.length; m++) {
        var words = chunks[m].split(' ');
        var line;

        // Break words up into multiple lines if necessary
        for (var n = 0; n < words.length; n++) {
          var testLine = (n == 0) ? words[n] : line + ' ' + words[n];
          var metrics = ctx.measureText(testLine);
          var testWidth = metrics.width;
          if (testWidth > elementWidth && n > 0) {
            line = words[n];
          } else {
            line = testLine;

      // Move the center up depending on line height and number of lines
      centerY -= ((lines.length-1) / 2) * lineHeight;

      // All but last line
      for (var n = 0; n < lines.length; n++) {
        ctx.fillText(lines[n], centerX, centerY);
        centerY += lineHeight;

Are duplicate keys allowed in the definition of binary search trees?

In a BST, all values descending on the left side of a node are less than (or equal to, see later) the node itself. Similarly, all values descending on the right side of a node are greater than (or equal to) that node value(a).

Some BSTs may choose to allow duplicate values, hence the "or equal to" qualifiers above. The following example may clarify:

    /  \
  13    22
 /     /  \
1    16    29
          /  \
        28    29

This shows a BST that allows duplicates(b) - you can see that to find a value, you start at the root node and go down the left or right subtree depending on whether your search value is less than or greater than the node value.

This can be done recursively with something like:

def hasVal (node, srchval):
    if node == NULL:
         return false
    if node.val == srchval:
        return true
    if node.val > srchval:
        return hasVal (node.left, srchval)
    return hasVal (node.right, srchval)

and calling it with:

foundIt = hasVal (rootNode, valToLookFor)

Duplicates add a little complexity since you may need to keep searching once you've found your value, for other nodes of the same value. Obviously that doesn't matter for hasVal since it doesn't matter how many there are, just whether at least one exists. It will however matter for things like countVal, since it needs to know how many there are.

(a) You could actually sort them in the opposite direction should you so wish provided you adjust how you search for a specific key. A BST need only maintain some sorted order, whether that's ascending or descending (or even some weird multi-layer-sort method like all odd numbers ascending, then all even numbers descending) is not relevant.

(b) Interestingly, if your sorting key uses the entire value stored at a node (so that nodes containing the same key have no other extra information to distinguish them), there can be performance gains from adding a count to each node, rather than allowing duplicate nodes.

The main benefit is that adding or removing a duplicate will simply modify the count rather than inserting or deleting a new node (an action that may require re-balancing the tree).

So, to add an item, you first check if it already exists. If so, just increment the count and exit. If not, you need to insert a new node with a count of one then rebalance.

To remove an item, you find it then decrement the count - only if the resultant count is zero do you then remove the actual node from the tree and rebalance.

Searches are also quicker given there are fewer nodes but that may not be a large impact.

For example, the following two trees (non-counting on the left, and counting on the right) would be equivalent (in the counting tree, i.c means c copies of item i):

     __14__                    ___22.2___
    /      \                  /          \
  14        22             7.1            29.1
 /  \      /  \           /   \          /    \
1    14  22    29      1.1     14.3  28.1      30.1
 \            /  \
  7         28    30

Removing the leaf-node 22 from the left tree would involve rebalancing (since it now has a height differential of two) the resulting 22-29-28-30 subtree such as below (this is one option, there are others that also satisfy the "height differential must be zero or one" rule):

\                      \
 22                     29
   \                   /  \
    29      -->      28    30
   /  \             /
 28    30         22

Doing the same operation on the right tree is a simple modification of the root node from 22.2 to 22.1 (with no rebalancing required).

What exactly does a jar file contain?

JD-GUI is a very handy tool for browsing and decompiling JARs

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.


Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

FormsAuthentication.SignOut() does not log the user out

Be aware that WIF refuses to tell the browser to cleanup the cookies if the wsignoutcleanup message from STS doesn't match the url with the name of the application from IIS, and I mean CASE SENSITIVE. WIF responds with the green OK check, but will not send the command to delete cookies to browser.

So, you need to pay attention to the case sensitivity of your url's.

For example, ThinkTecture Identity Server saves the urls of the visiting RPs in one cookie, but it makes all of them lower case. WIF will receive the wsignoutcleanup message in lower case and will compare it with the application name in IIS. If it doesn't match, it deletes no cookies, but will report OK to the browser. So, for this Identity Server I needed to write all urls in web.config and all application names in IIS in lower case, in order to avoid such problems.

Also don't forget to allow third party cookies in the browser if you have the applications outside of the subdomain of STS, otherwise the browser will not delete the cookies even if WIF tells him so.

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

How to store file name in database, with other info while uploading image to server using PHP?

If you want to input more data into the form, you simply access the submitted data through $_POST.

If you have

<input type="text" name="firstname" />

you access it with

$firstname = $_POST["firstname"];

You could then update your query line to read

mysql_query("INSERT INTO dbProfiles (photo,firstname)

Note: Always filter and sanitize your data.

set date in input type date

to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.

var today = moment().format('YYYY-MM-DD');

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

protected void Page_PreInit(object sender, EventArgs e) 
 if (Membership.GetUser() == null) //check the user weather user is logged in or not
    this.Page.MasterPageFile = "~/General.master";
    this.Page.MasterPageFile = "~/myMaster.master";

Java Pass Method as Parameter

I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.

  1. Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.

    public interface Do {
    void run() throws Exception;

    public interface Return {
        R run() throws Exception;

  1. Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.

    //example - when passed method does not return any value
    public void tx(final Do func) throws Exception {
        try {
        } catch (Exception e) {
            throw e;
        } finally {

    //Invoke code above by 
    tx(() -> api.delete(6));

Another example shows how to pass a method that actually returns something

        public  R tx(final Return func) throws Exception {
    R r=null;
    try {
            } catch (Exception e) {
                throw e;
            } finally {
        return r;
        //Invoke code above by 
        Object x= tx(() -> api.get(id));

best way to get the key of a key/value javascript object

The easiest way is to just use Underscore.js:


_.keys(object) Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]

Yes, you need an extra library, but it's so easy!

How to use multiple @RequestMapping annotations in spring?

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector("") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)


  • Not stable enough if site's structure changes


driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)


  • Not stable enough if site's structure changes
  • Not the native selector's way


// note that By.CssSelector("") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(""));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)


  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector


driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)


  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector


driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)


  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath


driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, '')]]/h5"));

IE and Edge fix for object-fit: cover;

I achieved satisfying results with:

min-height: 100%;
min-width: 100%;

this way you always maintain the aspect ratio.

The complete css for an image that will replace "object-fit: cover;":

width: auto;
height: auto;
min-width: 100%;
min-height: 100%;
position: absolute;
right: 50%;
transform: translate(50%, 0);

What's the canonical way to check for type in Python?

The most Pythonic way to check the type of an object is... not to check it.

Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

No need to uninstall your other java version(s) that's already installed on your machine. Whenever required, you can conveniently use the utility 'update-alternatives' to choose the Java runtime that you wish to activate. It will automagically update the required symbolic links.

You just need to run the below command and select the version of your choice. That's all!

sudo update-alternatives --config java

In Go's http package, how do I get the query string on a POST request?

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

Passing a variable from node.js to html

I found the possible way to write.

Server Side -

app.get('/main', function(req, res) {

  var name = 'hello';

  res.render(__dirname + "/views/layouts/main.html", {name:name});


Client side (main.html) -

<h1><%= name %></h1>

ZIP Code (US Postal Code) validation

If you're doing for Canada remember that not all letters are valid

These letters are invalid: D, F, I, O, Q, or U And the letters W and Z are not used as the first letter. Also some people use an optional space after the 3rd character.

Here is a regular expression for Canadian postal code:

new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)

The last i makes it case insensitive.

How do I return the SQL data types from my query?

Can you get away with recreating the staging table from scratch every time the query is executed? If so you could use SELECT ... INTO syntax and let SQL Server worry about creating the table using the correct column types etc.

INTO your_staging_table
FROM enormous_collection_of_views_tables_etc

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Including non-Python files with

Here is a simpler answer that worked for me.

First, per a Python Dev's comment above, setuptools is not required:

package_data is also available to pure distutils setup scripts 
since 2.3. – Éric Araujo

That's great because putting a setuptools requirement on your package means you will have to install it also. In short:

from distutils.core import setup

    # ...snip...
    packages          = ['pkgname'],
    package_data      = {'pkgname': ['license.txt']},

UITableView, Separator color where to set?

Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.

Swift 3, xcode version 8.3.2

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

another cheap hack, which seems to do the trick:

style="padding-bottom: 250px; margin-bottom: -250px;" on the element where the vertical overflow is getting cutoff, with 250 representing as many pixels as you need for your dropdown, etc.

What do the makefile symbols $@ and $< mean?

in exemple if you want to compile sources but have objects in an different directory :

You need to do :

gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...

but with most of macros the result will be all objects followed by all sources, like :

gcc -c -o <all OBJ path> <all SRC path>

so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(

the solution is to use these special macros

$@ $<

this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)

   gcc -c -o $@ $< $(HEADERS) $(FLAGS)

it means :

    $@ = $(OBJ)
    $< = $(SRC)

but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

How to get all selected values of a multiple select box?

My template helper looks like this:

 'submit #update': function(event) {
    var obj_opts =; //returns HTMLCollection
    var array_opts = Object.values(obj_opts);  //convert to array
    var stray => o.text ); //to filter your bits: text, value or selected
    //do stuff

Where should I put the CSS and Javascript code in an HTML webpage?

In my opinion the best practice is to place the CSS file in the header

  <link rel="stylesheet" href="css/layout.css" type="text/css">

and the Javascript file before the closing </body> tag

  <script type="text/javascript" src="script.js"></script>

Also if you have, like you said two CSS files. The browser would use both. If there were any selectors, ie. .content {} that were the same in both CSS files the browser would overwrite the similar properties of the first one with the second one's properties. If that makes sense.

Is there a wikipedia API just for retrieve content summary?

This code allows you to retrieve the content of the first paragraph of the page in plain text.

Parts of this answer come from here and thus here. See MediaWiki API documentation for more information.

// action=parse: get parsed text
// page=Baseball: from the page Baseball
// format=json: in json format
// prop=text: send the text content of the article
// section=0: top content of the page

$url = '';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);

$json = json_decode($c);

$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)

// pattern for first match of a paragraph
$pattern = '#<p>(.*)</p>#Us'; //
if(preg_match($pattern, $content, $matches))
    // print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
    print strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.

Rails server says port already used, how to kill that process?

Type in:

man lsof

Then look for -w, -n, and -i

-i: internet stuff -n: makes it faster -w: toggles warnings

There are WAY more details on the man pages

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
    return Response(

# Define some heavy function
def my_func():
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>


Install IPA with iTunes 11

For OS X Yosemite and above, and Xcode 6+

Open Xcode > Window > Devices

Choose your device. You can see the installed application list and add a new one by hitting +

screenshot of Xcode Devices

How to temporarily exit Vim and go back

If you are on a Unix system, Ctrl + Z will suspend Vim and give you a shell.

Type fg to go back. Note that Vim creates a swap file while editing, and suspending Vim wouldn't delete that file (you aren't exiting Vim after all). On dumb terminals, this method was pretty standard for edit-compile-edit cycles using vi. I just found out that for me, gVim minimizes on typing Z.

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

How to make a new List in Java

Let me summarize and add something:


1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")


1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

Immutable List

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable List

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

List of Characters

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

List of Integers

Ints.asList(1,2,3);                                             // Guava

Deleting an object in java?

You can remove the reference using null.

Let's say You have class A:

A a = new A();

last statement will remove the reference of the object a and that object will be "garbage collected" by JVM. It is one of the easiest ways to do this.

Can you detect "dragging" in jQuery?

jQuery plugin based on Simen Echholt's answer. I called it single click.

 * jQuery plugin: Configure mouse click that is triggered only when no mouse move was detected in the action.
 * @param callback
jQuery.fn.singleclick = function(callback) {
    return $(this).each(function() {
        var singleClickIsDragging = false;
        var element = $(this);

        // Configure mouse down listener.
        element.mousedown(function() {
            $(window).mousemove(function() {
                singleClickIsDragging = true;

        // Configure mouse up listener.
        element.mouseup(function(event) {
            var wasDragging = singleClickIsDragging;
            singleClickIsDragging = false;
            if(wasDragging) {

            // Since no mouse move was detected then call callback function.
  , event);

In use:

element.singleclick(function(event) {
    alert('Single/simple click!');


Unable instantiate android.gms.maps.MapFragment

This might be of help to some. I had two projects, one which was a copy of the demo from Google and that worked fine. Another I copied into an existing project and I could not get it to run at all. And in the second failing one I was getting the error message described above.

My problem was due to a library not enabled, even though I rebuilt, imported multiple times etc. Right-click on the project -> Properties -> Java Build Path -> Order & Export tab. On the failing project the "Android Private Libraries" tab was unchecked.

Once I enabled it the project worked fine.

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

private Long U_id;

it will handle incrementing id generation for you.

django MultiValueDictKeyError error, how do I deal with it

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”

In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.

The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

You can handle this error by putting :

is_private = request.POST.get('is_private', False);

How to check file MIME type with javascript before upload?

Short answer is no.

As you note the browsers derive type from the file extension. Mac preview also seems to run off the extension. I'm assuming its because its faster reading the file name contained in the pointer, rather than looking up and reading the file on disk.

I made a copy of a jpg renamed with png.

I was able to consistently get the following from both images in chrome (should work in modern browsers).

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90

Which you could hack out a String.indexOf('jpeg') check for image type.

Here is a fiddle to explore

The ambigious line I forgot to comment in the example

console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

  • Splits the base64 encoded img data, leaving on the image
  • Base64 decodes the image
  • Matches only the first line of the image data

The fiddle code uses base64 decode which wont work in IE9, I did find a nice example using VB script that works in IE

The code to load the image was taken from Joel Vardy, who is doing some cool image canvas resizing client side before uploading which may be of interest

Create comma separated strings C#?

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.

Profiling code (of course run in release without debug symbols):

class Program
    static void Main(string[] args)
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

    static string StringJoin(string seperator, params string[] values)
        return string.Join(seperator, values);

    static string StringBuilderAppend(string seperator, params string[] values)
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i < values.Length; i++)
        return builder.ToString();

string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.

how to detect search engine bots with php?

I'm using this code, pretty good. You will very easy to know user-agents visitted your site. This code is opening a file and write the user_agent down the file. You can check each day this file by go to and know about new user_agents and put them in your condition of if clause.

$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!preg_match("/Googlebot|MJ12bot|yandexbot/i", $user_agent)){
    // if not meet the conditions then
    // do what you need

    // here open a file and write the user_agent down the file. You can check each day this file useragent.txt and know about new user_agents and put them in your condition of if clause
        $myfile = fopen("useragent.txt", "a") or die("Unable to open file useragent.txt!");
        fwrite($myfile, $user_agent);
        $user_agent = "\n";
        fwrite($myfile, $user_agent);

This is the content of useragent.txt

Mozilla/5.0 (compatible; Googlebot/2.1; +
Mozilla/5.0 (compatible; MJ12bot/v1.4.6; (compatible; Googlebot/2.1; +
Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; + (compatible; yandexbot/3.0; +
mozilla/5.0 (compatible; yandexbot/3.0; +
mozilla/5.0 (compatible; yandexbot/3.0; +
mozilla/5.0 (compatible; yandexbot/3.0; +
mozilla/5.0 (compatible; yandexbot/3.0; +
mozilla/5.0 (iphone; cpu iphone os 9_3 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13e198 safari/601.1
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; linkdexbot/2.2; +
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; baiduspider/2.0; +
zoombot (linkbot 1.0
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
sogou web spider/4.0(+
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174

href="javascript:" vs. href="javascript:void(0)"

Using 'javascript:void 0' will do cause problem in IE

when you click the link, it will trigger onbeforeunload event of window !

<!doctype html>
<a href="javascript:void(0);" >Click me!</a>
window.onbeforeunload = function() {
    alert( 'oops!' );

How can I clone a JavaScript object except for one key?

I had an object that I wanted to remove after utilizing its method. This is what worked for me.

/* Sample data */
let items = [
    name: 'John',
    doc: {
      set: async (item) => {/*...sets docs on remote server*/}
    name: 'Mary',
    doc: {
      set: async (item) => {/*...sets docs on remote server*/}
    name: 'Jack',
    doc: {
      set: async (item) => {/*...sets docs on remote server*/}

/* mapping to promises */
const promises ={doc, ...item}) => doc.set(item)); 
// utilized doc and utilized `rest` of the items :)

Good Luck :)

How to detect iPhone 5 (widescreen devices)?

CGFloat height = [UIScreen mainScreen].bounds.size.height;

NSLog(@"screen soze is %f",height);

  if (height>550) {

          // 4" screen-do some thing

  else if (height<500) {

        // 3.5 " screen- do some thing


ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.


    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)


@section JavaScript
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>

How to clear radio button in Javascript?

If you have a radio button with same id, then you can clear the selection

Radio Button definition :

<input type="radio" name="paymentType" id="paymentType" value="CASH" /> CASH
<input type="radio" name="paymentType" id="paymentType" value="CHEQUE" /> CHEQUE
<input type="radio" name="paymentType" id="paymentType" value="DD" /> DD

Clearing all values of radio button:

document.formName.paymentType[0].checked = false;
document.formName.paymentType[1].checked = false;
document.formName.paymentType[2].checked = false;

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this

Python strptime() and timezones?

Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)

See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./ myfile.mdb > myfile.sql

(which btw contains more than 1 table)

RecyclerView: Inconsistency detected. Invalid item position

in my case , this solve my issue


PS: my problem ocur when i do seache filter in my recyclerview adapter

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Check out this solution. It worked for me..... Check the id of the button for which the error is may be the same in any one of the other page in your app. If yes, then change the id of them and then the app runs perfectly.

I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!! Hope it works

Converting VS2012 Solution to VS2010

Open the project file and not the solution. The project will be converted by the Wizard, and after converted, when you build the project, a new Solution will be generated as a VS2010 one.

Is there a vr (vertical rule) in html?

There is no tag in HTML, but you can use |.

UnicodeEncodeError: 'charmap' codec can't encode characters


You may or may not need to set that second environment variable PYTHONLEGACYWINDOWSSTDIO.

Alternatively, this can be done in code (although it seems that doing it through env vars is recommended):


Additionally: Reproducing this error was a bit of a pain, so leaving this here too in case you need to reproduce it on your machine:

set PYTHONIOENCODING=windows-1252