Programs & Examples On #Dtrace

DTrace is a comprehensive dynamic tracing framework for the Solaris Operating Environment, Mac OS X 10.5+ and FreeBSD.

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Installing PIL with pip

For CentOS:

yum install python-imaging

Error: The 'brew link' step did not complete successfully

the ultimate answer: change the owner of that directory to whoever you are

sudo chown -R `whoami` /usr/local/include

which is also recommended by brew if you run brew doctor

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

Getting the difference between two repositories

Once you have both branches in one repository you can do a git diff. And getting them in one repository is as easy as

git fetch /the/other/repo/.git refs/heads/*:refs/remotes/other/*

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

How to list all Git tags?

Also git show-ref is rather useful, so that you can directly associate tags with correspondent commits:

$ git tag
osgeolive-6.5
v8.0
...

$ git show-ref --tags
e7e66977c1f34be5627a268adb4b9b3d59700e40 refs/tags/osgeolive-6.5
8f27e65bddd7d4b8515ce620fb485fdd78fcdf89 refs/tags/v8.0
...

What does 'var that = this;' mean in JavaScript?

The use of that is not really necessary if you make a workaround with the use of call() or apply():

var car = {};
car.starter = {};

car.start = function(){
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to our main object
        this.starter.active = true;
    };

    activateStarter.apply(this);
};

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

Git diff against a stash

If your working tree is dirty, you can compare it to a stash by first committing the dirty working tree, and then comparing it to the stash. Afterwards, you may undo the commit with the dirty working tree (since you might not want to have that dirty commit in your commit log).

You can also use the following approach to compare two stashes with each other (in which case you just pop one of the stashes at first).

  • Commit your dirty working tree:

    git add .
    git commit -m "Dirty commit"
    
  • Diff the stash with that commit:

    git diff HEAD stash@{0}
    
  • Then, afterwards, you may revert the commit, and put it back in the working dir:

    git reset --soft HEAD~1
    git reset .
    

Now you've diffed the dirty working tree with your stash, and are back to where you were initially.

How can I create a keystore?

Use this command to create debug.keystore

keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

Replacing Numpy elements if condition is met

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False,  True,  True,  True],
       [False,  True,  True,  True],
       [ True,  True,  True,  True],
       [False,  True,  True, False],
       [ True,  True,  True,  True]], dtype=bool)
>>> 
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

You can shorten this with:

>>> c = (a < 3).astype(int)

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

how to specify new environment location for conda create

You can create it like this

conda create --prefix C:/tensorflow2 python=3.7

and you don't have to move to that folder to activate it.

# To activate this environment, use:
# > activate C:\tensorflow2

As you see I do it like this.

D:\Development_Avector\PycharmProjects\TensorFlow>activate C:\tensorflow2

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>conda --version
conda 4.5.13

Java Pass Method as Parameter

Use the Observer pattern (sometimes also called Listener pattern):

interface ComponentDelegate {
    void doSomething(Component component);
}

public void setAllComponents(Component[] myComponentArray, ComponentDelegate delegate) {
    // ...
    delegate.doSomething(leaf);
}

setAllComponents(this.getComponents(), new ComponentDelegate() {
                                            void doSomething(Component component) {
                                                changeColor(component); // or do directly what you want
                                            }
                                       });

new ComponentDelegate()... declares an anonymous type implementing the interface.

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

after 2 days searching in web, i found it's related to issue with the new NDIS6 driver, so you can install it to use the old NDIS5 driver

Try installing Old Version of Virtual Box (run as administrator)

VirtualBox-5.x.x

VirtualBox 5.2.6 worked for me Windows 10 , Genymotion 3.0.3

Is there a naming convention for MySQL?

MySQL has a short description of their more or less strict rules:

https://dev.mysql.com/doc/internals/en/coding-style.html

Most common codingstyle for MySQL by Simon Holywell:

http://www.sqlstyle.guide/

See also this question: Are there any published coding style guidelines for SQL?

Create Elasticsearch curl query for not null and not empty("")

On elasticsearch 5.6, I have to use command below to filter out empty string:

    GET /_search
    {
        "query" : {
            "regexp":{
                "<your_field_name_here>": ".+"
            }
        }
    }  

When to use single quotes, double quotes, and backticks in MySQL

Single quotes should be used for string values like in the VALUES() list.

Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.

In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.

Find size and free space of the filesystem containing a given file

The simplest way to find out it.

import os
from collections import namedtuple

DiskUsage = namedtuple('DiskUsage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Will return the namedtuple with attributes: 'total', 'used' and 'free',
    which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return DiskUsage(total, used, free)

How to install SQL Server Management Studio 2008 component only

If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.

As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.

Download SSMS 2008 Express

Looking for a 'cmake clean' command to clear up CMake output

If you have custom defines and want to save them before cleaning, run the following in your build directory:

sed -ne '/variable specified on the command line/{n;s/.*/-D \0 \\/;p}' CMakeCache.txt

Then create a new build directory (or remove the old build directory and recreate it) and finally run cmake with the arguments you'll get with the script above.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case after downgrading from .NET 4.5 to .NET 4.0 project was working fine on a local machine, but was failing on server after publishing.

Turns out that destination had some old assemblies, which were still referencing .NET 4.5.

Fixed it by enabling publishing option "Delete all existing files prior to publish"

Java: Instanceof and Generics

Provided your class extends a class with a generic parameter, you can also get this at runtime via reflection, and then use that for comparison, i.e.

class YourClass extends SomeOtherClass<String>
{

   private Class<?> clazz;

   public Class<?> getParameterizedClass()
   {
      if(clazz == null)
      {
         ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
          clazz = (Class<?>)pt.getActualTypeArguments()[0];
       }
       return clazz;
    }
}

In the case above, at runtime you will get String.class from getParameterizedClass(), and it caches so you don't get any reflection overhead upon multiple checks. Note that you can get the other parameterized types by index from the ParameterizedType.getActualTypeArguments() method.

Predicate Delegates in C#

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

        List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
        return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(i => i > 2);
    }
}

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Find row where values for column is maximal in a pandas DataFrame

You might also try idxmax:

In [5]: df = pandas.DataFrame(np.random.randn(10,3),columns=['A','B','C'])

In [6]: df
Out[6]: 
          A         B         C
0  2.001289  0.482561  1.579985
1 -0.991646 -0.387835  1.320236
2  0.143826 -1.096889  1.486508
3 -0.193056 -0.499020  1.536540
4 -2.083647 -3.074591  0.175772
5 -0.186138 -1.949731  0.287432
6 -0.480790 -1.771560 -0.930234
7  0.227383 -0.278253  2.102004
8 -0.002592  1.434192 -1.624915
9  0.404911 -2.167599 -0.452900

In [7]: df.idxmax()
Out[7]: 
A    0
B    8
C    7

e.g.

In [8]: df.loc[df['A'].idxmax()]
Out[8]: 
A    2.001289
B    0.482561
C    1.579985

How to delete session cookie in Postman?

As @markus said use the "Cookie Manager" and delete the cookie. enter image description here

If you want to learn how to set destroy cookies in postman, You should check the Postman Echo service https://docs.postman-echo.com/

There you will find complete explanation on how to Set, Get and Delete those cookies.

Check it on : https://docs.postman-echo.com/#3de3b135-b3cc-3a68-ba27-b6d373e03c8c

Give it a Try.

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


Use of alloc init instead of new

For a side note, I personally use [Foo new] if I want something in init to be done without using it's return value anywhere. If you do not use the return of [[Foo alloc] init] anywhere then you will get a warning. More or less, I use [Foo new] for eye candy.

Java 8 - Difference between Optional.flatMap and Optional.map

They both take a function from the type of the optional to something.

map() applies the function "as is" on the optional you have:

if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));

What happens if your function is a function from T -> Optional<U>?
Your result is now an Optional<Optional<U>>!

That's what flatMap() is about: if your function already returns an Optional, flatMap() is a bit smarter and doesn't double wrap it, returning Optional<U>.

It's the composition of two functional idioms: map and flatten.

Excel - Combine multiple columns into one column

Try this. Click anywhere in your range of data and then use this macro:

Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer

Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1

For iCol = 2 To rng.Columns.Count
    Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
    ActiveSheet.Paste Destination:=Cells(lastCell, 1)
    lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub

How can I make my own event in C#?

Here's an example of creating and using an event with C#

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

How to pass table value parameters to stored procedure from .net code

Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

As an example, if you have the following table value that is used as a parameter in SQL:

CREATE TYPE NodeFilter AS TABLE (
  ID int not null
  Code nvarchar(10) not null,
);

You would need to order your columns as such in C#:

table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals

If you fail to do this you will get a parse error, failed to convert nvarchar to int.

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

How to print Two-Dimensional Array like table

ALL OF YOU PLEASE LOOT AT IT I Am amazed it need little IQ just get length by arr[0].length and problem solved

   for (int i = 0; i < test.length; i++) {
        for (int j = 0; j < test[0].length; j++) {

        System.out.print(test[i][j]);
    }
        System.out.println();
    }

Is it possible to make a Tree View with Angular?

If you are using Bootstrap CSS...

I have created a simple re-usable tree control (directive) for AngularJS based on a Bootstrap "nav" list. I added extra indentation, icons, and animation. HTML attributes are used for configuration.

It does not use recursion.

I called it angular-bootstrap-nav-tree ( catchy name, don't you think? )

There is an example here, and the source is here.

Why doesn't os.path.join() work in this case?

Try with new_sandbox only

os.path.join('/home/build/test/sandboxes/', todaystr, 'new_sandbox')

How can I change the version of npm using nvm?

EDIT: several years since this question was first answered, as noted in a newer answer, there is now a command for this:

nvm now has a command to update npm. It's nvm install-latest-npm or nvm install --latest-npm.

nvm install-latest-npm: Attempt to upgrade to the latest working npm on the current node version

nvm install --latest-npm: After installing, attempt to upgrade to the latest working npm on the given node version

Below are previous revisions of the correct answer to this question.

Over three years after this question was first asked, it seems like the answer is much simpler now. Just update the version that nvm installed, which lives in ~/.nvm/versions/node/[your-version]/lib/node_modules/npm.

I just installed node 4.2.2, which comes with npm 2.14.7, but I want to use npm 3. So I did:

cd ~/.nvm/versions/node/v4.2.2/lib
npm install npm

Easy!

And yes, this should work for any module, not just npm, that you want to be "global" for a specific version of node.


EDIT 1: In the newest version, npm -g is smart and installs modules into the path above instead of the system global path.


Thanks @philraj for pointing this out in a comment.

Does WhatsApp offer an open API?

WhatsApp does not have a API available for public use. As you put it, it's a closed system.

However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.

See this WhatsApp FAQ article.

Why is the use of alloca() not considered good practice?

One issue is that it isn't standard, although it's widely supported. Other things being equal, I'd always use a standard function rather than a common compiler extension.

How to implement class constructor in Visual Basic?

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

The above solution for the JsonCreationConverter<T> is all over the internet, but has a flaw that manifests itself in rare occasions. The new JsonReader created in the ReadJson method does not inherit any of the original reader's configuration values (Culture, DateParseHandling, DateTimeZoneHandling, FloatParseHandling, etc...). These values should be copied over before using the new JsonReader in serializer.Populate().

This is the best I could come up with to fix some of the problems with the above implementation, but I still think there are some things being overlooked:

Update I updated this to have a more explicit method that makes a copy of an existing reader. This just encapsulates the process of copying over individual JsonReader settings. Ideally this function would be maintained in the Newtonsoft library itself, but for now, you can use the following:

/// <summary>Creates a new reader for the specified jObject by copying the settings
/// from an existing reader.</summary>
/// <param name="reader">The reader whose settings should be copied.</param>
/// <param name="jToken">The jToken to create a new reader for.</param>
/// <returns>The new disposable reader.</returns>
public static JsonReader CopyReaderForObject(JsonReader reader, JToken jToken)
{
    JsonReader jTokenReader = jToken.CreateReader();
    jTokenReader.Culture = reader.Culture;
    jTokenReader.DateFormatString = reader.DateFormatString;
    jTokenReader.DateParseHandling = reader.DateParseHandling;
    jTokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
    jTokenReader.FloatParseHandling = reader.FloatParseHandling;
    jTokenReader.MaxDepth = reader.MaxDepth;
    jTokenReader.SupportMultipleContent = reader.SupportMultipleContent;
    return jTokenReader;
}

This should be used as follows:

public override object ReadJson(JsonReader reader,
                                Type objectType,
                                object existingValue,
                                JsonSerializer serializer)
{
    if (reader.TokenType == JsonToken.Null)
        return null;
    // Load JObject from stream
    JObject jObject = JObject.Load(reader);
    // Create target object based on JObject
    T target = Create(objectType, jObject);
    // Populate the object properties
    using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
    {
        serializer.Populate(jObjectReader, target);
    }
    return target;
}

Older solution follows:

/// <summary>Base Generic JSON Converter that can help quickly define converters for specific types by automatically
/// generating the CanConvert, ReadJson, and WriteJson methods, requiring the implementer only to define a strongly typed Create method.</summary>
public abstract class JsonCreationConverter<T> : JsonConverter
{
    /// <summary>Create an instance of objectType, based properties in the JSON object</summary>
    /// <param name="objectType">type of object expected</param>
    /// <param name="jObject">contents of JSON object that will be deserialized</param>
    protected abstract T Create(Type objectType, JObject jObject);

    /// <summary>Determines if this converted is designed to deserialization to objects of the specified type.</summary>
    /// <param name="objectType">The target type for deserialization.</param>
    /// <returns>True if the type is supported.</returns>
    public override bool CanConvert(Type objectType)
    {
        // FrameWork 4.5
        // return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        // Otherwise
        return typeof(T).IsAssignableFrom(objectType);
    }

    /// <summary>Parses the json to the specified type.</summary>
    /// <param name="reader">Newtonsoft.Json.JsonReader</param>
    /// <param name="objectType">Target type.</param>
    /// <param name="existingValue">Ignored</param>
    /// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
    /// <returns>Deserialized Object</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        //Create a new reader for this jObject, and set all properties to match the original reader.
        JsonReader jObjectReader = jObject.CreateReader();
        jObjectReader.Culture = reader.Culture;
        jObjectReader.DateParseHandling = reader.DateParseHandling;
        jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
        jObjectReader.FloatParseHandling = reader.FloatParseHandling;

        // Populate the object properties
        serializer.Populate(jObjectReader, target);

        return target;
    }

    /// <summary>Serializes to the specified type</summary>
    /// <param name="writer">Newtonsoft.Json.JsonWriter</param>
    /// <param name="value">Object to serialize.</param>
    /// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

Gather multiple sets of columns

It's not at all related to "tidyr" and "dplyr", but here's another option to consider: merged.stack from my "splitstackshape" package, V1.4.0 and above.

library(splitstackshape)
merged.stack(df, id.vars = c("id", "time"), 
             var.stubs = c("Q3.2.", "Q3.3."),
             sep = "var.stubs")
#     id       time .time_1       Q3.2.       Q3.3.
#  1:  1 2009-01-01      1. -0.62645381  1.35867955
#  2:  1 2009-01-01      2.  1.51178117 -0.16452360
#  3:  1 2009-01-01      3.  0.91897737  0.39810588
#  4:  2 2009-01-02      1.  0.18364332 -0.10278773
#  5:  2 2009-01-02      2.  0.38984324 -0.25336168
#  6:  2 2009-01-02      3.  0.78213630 -0.61202639
#  7:  3 2009-01-03      1. -0.83562861  0.38767161
# <<:::SNIP:::>>
# 24:  8 2009-01-08      3. -1.47075238 -1.04413463
# 25:  9 2009-01-09      1.  0.57578135  1.10002537
# 26:  9 2009-01-09      2.  0.82122120 -0.11234621
# 27:  9 2009-01-09      3. -0.47815006  0.56971963
# 28: 10 2009-01-10      1. -0.30538839  0.76317575
# 29: 10 2009-01-10      2.  0.59390132  0.88110773
# 30: 10 2009-01-10      3.  0.41794156 -0.13505460
#     id       time .time_1       Q3.2.       Q3.3.

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

PHP cURL error code 60

i fixed this by modifying php.ini file at C:\wamp\bin\apache\apache2.4.9\bin\

curl.cainfo = "C:/wamp/bin/php/php5.5.12/cacert.pem"

first i was trying by modifying php.ini file at C:\wamp\bin\php\php5.5.12\ and it didn't work.

hope this helps someone who is searching for the right php.ini to modify

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case it was as daft as having registered the new component for DI in my app.module.ts declarations but not in exports.

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

For windows platform, You must check if redis-server is running on given ip:port. you can find redis configuration at installation directory /conf/redis.conf. by default client accept 127.0.0.1:6379.

How to center a WPF app on screen?

var window = new MyWindow();

for center of the screen use:

window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

for center of the parent window use:

window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

How to start debug mode from command prompt for apache tomcat server?

On windows
$ catalina.bat jpda start
On Linux/Unix
$ catalina.sh jpda start

More info ----> https://cwiki.apache.org/confluence/display/TOMCAT/Developing

How would I extract a single file (or changes to a file) from a git stash?

You can get the diff for a stash with "git show stash@{0}" (or whatever the number of the stash is; see "git stash list"). It's easy to extract the section of the diff for a single file.

Node.js getaddrinfo ENOTFOUND

My problem was we were parsing url and generating http_options for http.request();

I was using request_url.host which already had port number with domain name so had to use request_url.hostname.

var request_url = new URL('http://example.org:4444/path');
var http_options = {};

http_options['hostname'] = request_url.hostname;//We were using request_url.host which includes port number
http_options['port'] = request_url.port;
http_options['path'] = request_url.pathname;
http_options['method'] = 'POST';
http_options['timeout'] = 3000;
http_options['rejectUnauthorized'] = false;

Could not load file or assembly '' or one of its dependencies

Following worked for me.

  • Remove Temporary Files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
    • then right click on Temporary Asp.net Files>properties>security and give total control access to IIS and to all user runing my project

Assign static IP to Docker container

Easy with Docker version 1.10.1, build 9e83765.

First you need to create your own docker network (mynet123)

docker network create --subnet=172.18.0.0/16 mynet123

then, simply run the image (I'll take ubuntu as example)

docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash

then in ubuntu shell

ip addr

Additionally you could use

  • --hostname to specify a hostname
  • --add-host to add more entries to /etc/hosts

Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/

Checking letter case (Upper/Lower) within a string in Java

A loop like this one:

else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                   ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                       {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                       }
                     // end if
                } //end for
            }

Has an obvious logical flaw: You enter it if the first character is not lowercase, then test if the second character is not lower case. At that point you throw an error.

Instead, you should do something like this (not full code, just an example):

boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
  ch = password.charAt(ii);
  // check each rule in turn, with code like this:
  if Character.isLowerCase(ch) hasLower = true;
  if Character.isUpperCase(ch) hasUpper = true;
  // ... etc for all the tests you want to do
}

if(hasLower && hasUpper && ...) {
  // password is good
} 
else {
  // password is bad
}

Of course the code snippet you provided, besides the faulty logic, did not have code to test for the other conditions that your "help" option printed out. As was pointed out in one of the other answers, you could consider using regular expressions to help you speed up the process of finding each of these things. For example,

hasNumber  : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"

In code:

hasNumber  = password.matches(".*\\d.*");  // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT   = !password.matches(".*NOT.*");
hasNoAND   = !password.matches(".*AND.*");

It is possible to combine these things in clever ways - but especially when you are a novice regex user, it is much better to be a little bit "slow and tedious", and get code that works first time (plus you will be able to figure out what you did six months from now).

XPath test if node value is number

I've been dealing with 01 - which is a numeric.

string(number($v)) != string($v) makes the segregation

check if a file is open in Python

If all you care about is the current process, an easy way is to use the file object attribute "closed"

f = open('file.py')
if f.closed:
  print 'file is closed'

This will not detect if the file is open by other processes!

source: http://docs.python.org/2.4/lib/bltin-file-objects.html

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

How to launch an EXE from Web page (asp.net)

Are you saying that you are having trouble inserting into a web page a link to a file that happens to have a .exe extension?

If that is the case, then take one step back. Imagine the file has a .htm extension, or a .css extension. How can you make that downloadable? If it is a static link, then the answer is clear: the file needs to be in the docroot for the ASP.NET app. IIS + ASP.NET serves up many kinds of content: .htm files, .css files, .js files, image files, implicitly. All these files are somewhere under the docroot, which by default is c:\inetpub\wwwroot, but for your webapp is surely something different. The fact that the file you want to expose has an .exe extension does not change the basic laws of IIS physics. The exe has to live under the docroot. The network share thing might work for some browsers.

The alternative of course is to dynamically write the content of the file directly to the Response.OutputStream. This way you don't need the .exe to be in your docroot, but it is not a direct download link. In this scenario, the file might be downloaded by a button click.

Something like this:

    Response.Clear(); 
    string FullPathFilename = "\\\\server\\share\\CorpApp1.exe";
    string archiveName= System.IO.Path.GetFileName(FullPathFilename);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("content-disposition", "filename=" + archiveName);
    Response.TransmitFile(FullPathFilename);
    Response.End();

How to schedule a task to run when shutting down windows

In addition to Dan Williams' answer, if you want to add a Startup/Shutdown script, you need to be looking for Windows Settings under Computer Configuration. If you want to add a Logon/Logoff script, you need to be looking for Windows Settings under User Configuration.

So to reiterate what Dan said with this information included,

For Startup/Shutdown:

  1. Run gpedit.msc (Local Policies)
  2. Computer Configuration -> Windows Settings -> Scripts -> Startup or Shutdown -> Properties -> Add

For Logon/Logoff:

  1. Run gpedit.msc (Local Policies)
  2. User Configuration -> Windows Settings -> Scripts -> Logon or Logoff -> Properties -> Add

Source: http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx

Python date string to date object

Directly related question:

What if you have

datetime.datetime.strptime("2015-02-24T13:00:00-08:00", "%Y-%B-%dT%H:%M:%S-%H:%M").date()

and you get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/_strptime.py", line 308, in _strptime
    format_regex = _TimeRE_cache.compile(format)
  File "/usr/local/lib/python2.7/_strptime.py", line 265, in compile
    return re_compile(self.pattern(format), IGNORECASE)
  File "/usr/local/lib/python2.7/re.py", line 194, in compile
    return _compile(pattern, flags)
  File "/usr/local/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: redefinition of group name 'H' as group 7; was group 4

and you tried:

<-24T13:00:00-08:00", "%Y-%B-%dT%HH:%MM:%SS-%HH:%MM").date()

but you still get the traceback above.

Answer:

>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> parse("2015-02-24T13:00:00-08:00")
datetime.datetime(2015, 2, 24, 13, 0, tzinfo=tzoffset(None, -28800))

CSS hover vs. JavaScript mouseover

In Internet Explorer, there must be declared a <!DOCTYPE> for the :hover selector to work on other elements than the <a> element.

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

At the end of the ~.profile file add::

export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/go/bin"
export PATH="$PATH:$GOPATH/bin"

How to sort a list of strings?

Suppose s = "ZWzaAd"

To sort above string the simple solution will be below one.

print ''.join(sorted(s))

Use tab to indent in textarea

Based on all that people had to say here on the answers, its just a combination of keydown(not keyup) + preventDefault() + insert a tab character at the caret. Something like:

var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
   e.preventDefault();
   insertAtCaret('txt', '\t')
}

The earlier answer had a working jsfiddle but it used an alert() on keydown. If you remove this alert, then it didnt work. I ve just added a function to insert a tab at the current cursor position in the textarea.

Here s a working jsfiddle for the same: http://jsfiddle.net/nsHGZ/

How to export SQL Server 2005 query to CSV

If you can not use Management studio i use sqlcmd.

sqlcmd -q "select col1,col2,col3 from table" -oc:\myfile.csv -h-1 -s","

That is the fast way to do it from command line.

Android failed to load JS bundle

In new React Native (for sure 0.59) debug config is inside android/app/src/debug/res/xml/react_native_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
  </domain-config>
</network-security-config>

SQL Server 2008: How to query all databases sizes?

I recently came across this page looking for something like this. Just in case someone comes across this and is interested in only the core user databases, you can use something like this which excludes Master, msdb...

SELECT
DB_NAME(db.database_id) DatabaseName,
(CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,
(CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB
FROM sys.databases db
LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id
LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id
where DB_NAME(db.database_id) not like 'master'
and DB_NAME(db.database_id) not like 'msdb'
and DB_NAME(db.database_id) not like 'model'
and DB_NAME(db.database_id) not like 'tempdb'
and DB_NAME(db.database_id) not like 'Northwind'
and DB_NAME(db.database_id) not like 'ReportServer'
order by DB_NAME(db.database_id)

Reading file using relative path in python project

try

with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:

Difference between document.addEventListener and window.addEventListener?

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

How do you install Boost on MacOS?

Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile.

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

String comparison using '==' vs. 'strcmp()'

You can use strcmp() if you wish to order/compare strings lexicographically. If you just wish to check for equality then == is just fine.

How to get ASCII value of string in C#

Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.

  string s = "\ta£\x0394\x221A";   // tab; lower case a; pound sign; Greek delta;
                                   // square root  
  Debug.Print(s);
  char c = s[0];
  int i = (int)c;
  string x = i.ToString("X");
  c = s[1];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[2];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[3];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[4];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);

The above code outputs the following to the immediate window:

a£?v

a 97 61

£ 163 A3

? 916 394

v 8730 221A

How to get absolute path to file in /resources folder of your project

To return a file or filepath

URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();  // return file path

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

How to fill Matrix with zeros in OpenCV?

Because the last parameter is optional and also the data pointer should point somewhere appropriate:

//inline Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step)
double mydata[1];
Mat m1 = Mat(1,1, CV_64F, mydata); 
m1.at<double>(0,0) = 0;

But better do it directly with this template-based constructor:

//inline Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s)
Mat m1 = Mat(1,1, CV_64F, cvScalar(0.));

//or even
Mat m1 = Mat(1,1, CV_64F, double(0));

Client to send SOAP request and receive response

The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Pad with leading zeros

There's no such concept as an integer with padding. How many legs do you have - 2, 02 or 002? They're the same number. Indeed, even the "2" part isn't really part of the number, it's only relevant in the decimal representation.

If you need padding, that suggests you're talking about the textual representation of a number... i.e. a string.

You can achieve that using string formatting options, e.g.

string text = value.ToString("0000000");

or

string text = value.ToString("D7");

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

Setting a checkbox as checked with Vue.js

To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.

The following code will bind the checkbox with that property:

<input type="checkbox" v-model="module.checked" v-bind:id="module.id">

Notice that I removed v-bind:value="module.id". You shouldn't use v-model and v-bind:value on the same element. From the vue docs:

<input v-model="something">

is just syntactic sugar for:

<input v-bind:value="something" v-on:input="something = $event.target.value">

So, by using v-model and v-bind:value, you actually end up having v-bind:value twice, which could lead to undefined behavior.

MySQL: determine which database is selected?

Another way for filtering the database with specific word.

SHOW DATABASES WHERE `Database` LIKE '<yourDatabasePrefixHere>%'
or
SHOW DATABASES LIKE '<yourDatabasePrefixHere>%';

Example:

SHOW DATABASES WHERE `Database` LIKE 'foobar%'
foobar_animal
foobar_humans_gender
foobar_objects

simple vba code gives me run time error 91 object variable or with block not set

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Insert variable into Header Location PHP

like this?

<?php
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];

header('Location: http://linkhere.com/'. $url_endpoint);

?>

Add a column to existing table and uniquely number them on MS SQL Server

This will depend on the database but for SQL Server, this could be achieved as follows:

alter table Example
add NewColumn int identity(1,1)

Swift: Reload a View Controller

You shouldn't call viewDidLoad method manually, Instead if you want to reload any data or any UI, you can use this:

override func viewDidLoad() {
    super.viewDidLoad();

    let myButton = UIButton()

    // When user touch myButton, we're going to call loadData method
    myButton.addTarget(self, action: #selector(self.loadData), forControlEvents: .TouchUpInside)

    // Load the data
    self.loadData();
}

func loadData() {
    // code to load data from network, and refresh the interface
    tableView.reloadData()
}

Whenever you want to reload the data and refresh the interface, you can call self.loadData()

Getting time and date from timestamp with php

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function

What is the best way to delete a component with CLI

  1. Delete the folder containing this component.
  2. In the app.module.ts remove the import statement for this component and remove its name from the declaration section of @NgModule
  3. Remove the line with the export statement for this component from index.ts.

Find in Files: Search all code in Team Foundation Server

In my case, writing a small utility in C# helped. Links that helped me - http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html

How to list files of a team project using tfs api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;

namespace TFSSearch
{
class Program
{
    static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" };  //Text to search
    static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html", 
                                           "*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions

    static void Main(string[] args)
    {
        try
        {
            var tfs = TfsTeamProjectCollectionFactory
             .GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)

            tfs.EnsureAuthenticated();

            var versionControl = tfs.GetService<VersionControlServer>();


            StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
            var allProjs = versionControl.GetAllTeamProjects(true);
            foreach (var teamProj in allProjs)
            {
                foreach (var filePattern in filePatterns)
                {
                    var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
                                .Where(i => !i.ServerItem.Contains("_ReSharper"));  //skipping resharper stuff
                    foreach (var item in items)
                    {
                        List<string> lines = SearchInFile(item);
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine("FILE:" + item.ServerItem);
                            outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
                            outputFile.WriteLine();
                        }
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine();
                        }
                    }
                }
                outputFile.Flush();
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }
        Console.WriteLine("========");
        Console.Read();
    }

    // Define other methods and classes here
    private static List<string> SearchInFile(Item file)
    {
        var result = new List<string>();

        try
        {
            var stream = new StreamReader(file.DownloadFile(), Encoding.Default);

            var line = stream.ReadLine();
            var lineIndex = 0;

            while (!stream.EndOfStream)
            {
                if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
                    result.Add("=== Line " + lineIndex + ": " + line.Trim());

                line = stream.ReadLine();
                lineIndex++;
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }

        return result;
    }
}
}

MSSQL Regular expression

Thank you all for your help.

This is what I have used in the end:

SELECT *, 
  CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' 
    THEN 'Valid' 
    ELSE 'No valid' 
  END [Validate]
FROM 
  *table*
  ORDER BY [Validate]

Align items in a stack panel?

Yo can set FlowDirection of Stack panel to RightToLeft, and then all items will be aligned to the right side.

How to add a new object (key-value pair) to an array in javascript?

Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.

Therefore, if you are setting a variable equal to the result, use .concat().

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})

In this case, newArray will return 5 (the length of the array).

newArray = items.concat({'id': 5})

However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].

How to display an unordered list in two columns?

I was looking at @jaider's solution which worked but I'm offering a slightly different approach that I think is more easy to work with and which I've seen to be good across browsers.

ul{
    list-style-type: disc;
    -webkit-columns: 2;
    -moz-columns: 2;
    columns: 2;
    list-style-position: inside;//this is important addition
}

By default un-ordered list display the bullet position outside but then in some browsers it would cause some display problems based on the browser's way of laying out your website.

To get it to display in the format:

A B
C D
E

etc. use the following:

ul li{
    float: left;
    width: 50%;//helps to determine number of columns, for instance 33.3% displays 3 columns
}
ul{
    list-style-type: disc;
}

This should solve all your problems with displaying columns. All the best and thanks @jaider as your response helped to guide me to discover this.

jQuery get the rendered height of an element?

I made a simple code that doesn't even need JQuery and probably gonna help some people. It gets the total height of 'ID1' after loaded and use it on 'ID2'

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

Then just set the body to load it

<body onload='anyName()'>

Delete rows containing specific strings in R

You could use dplyr::filter() and negate a grepl() match:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))

Or with dplyr::filter() and negating a stringr::str_detect() match:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

Generating statistics from Git repository

I'm doing a git repository statistics generator in ruby, it's called git_stats.

You can find examples generated for some repositories on project page.

Here is a list of what it can do:

  • General statistics
    • Total files (text and binary)
    • Total lines (added and deleted)
    • Total commits
    • Authors
  • Activity (total and per author)
    • Commits by date
    • Commits by hour of day
    • Commits by day of week
    • Commits by hour of week
    • Commits by month of year
    • Commits by year
    • Commits by year and month
  • Authors
    • Commits by author
    • Lines added by author
    • Lines deleted by author
    • Lines changed by author
  • Files and lines
    • By date
    • By extension

If you have any idea what to add or improve please let me know, I would appreciate any feedback.

while EOF in JAVA?

The problem is that you're reading nextLine() on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:

File:

Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something

On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah, printed to the System.

The process will repeat with Sincerely, being consumed and Capnstank printing out.

Finally the while will consume the "PS" line while the String line = fileReader.nextLine() retreives an exception from the file because there's nothing further to read.

To resolve the issue:

String line = fileReader.nextLine();

while (line != null) {
  System.out.println(line);
  line = fileReader.nextLine();
}

How do you make a div follow as you scroll?

You can use the fixed CSS position property to accomplish this. There is a basic tutorial on this here.

EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.

There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?

Android Spinner: Get the selected item change event

By default, you will get the first item of the spinner array through

value = spinner.getSelectedItem().toString();

whenever you selected the value in the spinner this will give you the selected value

if you want the position of the selected item then do it like that

pos = spinner.getSelectedItemPosition();

the above two answers are for without applying listener

No grammar constraints (DTD or XML schema) detected for the document

The Real Solution:

add <!DOCTYPE something> to the begining of each problematic XML,

after the xml tag <?xml version="1.0" encoding="utf-8"?>

you can write anything for doctype, but basically it's supposed to be manifest, activity, etc. from what I understand

Find the IP address of the client in an SSH session

Linux: who am i | awk '{print $5}' | sed 's/[()]//g'

AIX: who am i | awk '{print $6}' | sed 's/[()]//g'

program cant start because php5.dll is missing

For Wamp x86+Phalcon users (with same error):

Take care of download the right version of Phalcon:

Phalcon 1.3.2 - Windows x86 for PHP 5.5.0 (VC11)

Single huge .css file vs. multiple smaller specific .css files?

here is the best way:

  1. create a general css file with all shared code
  2. insert all specific page css code into the same page, on the tag or using the attribute style="" for each page

on this way you have only one css with all shared code and an html page. by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.

How can I de-install a Perl module installed via `cpan`?

Since at the time of installing of any module it mainly put corresponding .pm files in respective directories. So if you want to remove module only for some testing purpose or temporarily best is to find the path where module is stored using perldoc -l <MODULE> and then simply move the module from there to some other location. This approach can also be tried as a more permanent solution but i am not aware of any negative consequences as i do it mainly for testing.

MS Access: how to compact current database in VBA

For Access 2013, you could just do

Sendkeys "%fic"

This is the same as typing ALT, F, I, C on your keyboard.

It's probably a different sequence of letters for different versions, but the "%" symbol means "ALT", so keep that in the code. you may just need to change the letters, depending on what letters appear when you press ALT

Letters that appear when pressing ALT in Access 2013

How to "log in" to a website using Python's Requests module?

Find out the name of the inputs used on the websites form for usernames <...name=username.../> and passwords <...name=password../> and replace them in the script below. Also replace the URL to point at the desired site to log into.

login.py

#!/usr/bin/env python

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
url = 'https://website.com/login.html'
requests.post(url, data=payload, verify=False)

The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.

Extra:

To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

# Custom scripts
export CUSTOM_SCRIPTS=home/scripts
export PATH=$CUSTOM_SCRIPTS:$PATH

Then create a link to this python script inside home/scripts/login.py

ln -s ~/home/scripts/login.py ~/home/scripts/login

Close your terminal, start a new one, run login

Which MySQL datatype to use for an IP address?

For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED. You can use MySQL's INET_ATON() function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN queries

INET_ATON() MySQL function

Format ints into string of hex

''.join('%02x'%i for i in input)

How to pass a parameter like title, summary and image in a Facebook sharer URL

On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php), makes me believe it was a bug that was going to be resolved. Am I right?

https://developers.facebook.com/x/bugs/357750474364812/

Ibrahim Faour · · Facebook Platform Team

Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!

Changing Underline color

I think the easiest way to do this is in your css, use:

text-decoration-color: red;

This will change the color of the underline without changing the color of your text. Good luck!

load scripts asynchronously

You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript

It explains how and when to use such technique.

Print a variable in hexadecimal in Python

You can try something like this I guess:

new_str = ""
str_value = "rojbasr"
for i in str_value:
    new_str += "0x%s " % (i.encode('hex'))
print new_str

Your output would be something like this:

0x72 0x6f 0x6a 0x62 0x61 0x73 0x72

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

Installing J2EE into existing eclipse IDE

Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..

Android Material Design Button Styles

you can give aviation to the view by adding z axis to it and can have default shadow to it. this feature was provided in L preview and will be available after it release. For now you can simply add a image the gives this look for button background

Importing a GitHub project into Eclipse

It can be done in two ways:

1.Use clone Git

2.You can set it up manually by rearranging folders given in it. make a two separate folder 'src' and 'res' and place appropriate classes and xml file given by library. and then import project from eclipse and make it as library, that's it.

C# 4.0 optional out/ref arguments

ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

Why is php not running?

You need to add the semicolon to the end of all php things like echo, functions, etc.

change <?php phpinfo() ?> to <?php phpinfo(); ?>

If that does not work, use php's function ini_set to show errors: ini_set('display_errors', 1);

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

Entity framework linq query Include() multiple children entities

Use extension methods. Replace NameOfContext with the name of your object context.

public static class Extensions{
   public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country") ;
     }

     public static Company CompanyById(this NameOfContext context, int companyID){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country")
             .FirstOrDefault(c => c.Id == companyID) ;
      }

}

Then your code becomes

     Company company = 
          context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);

     //or if you want even more
     Company company = 
          context.CompanyById(companyID);

Python import csv to list

Extending your requirements a bit and assuming you do not care about the order of lines and want to get them grouped under categories, the following solution may work for you:

>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
...     for line in f:
...         text, cat = line.rstrip("\n").split(",", 1)
...         dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})

This way you get all relevant lines available in the dictionary under key being the category.

How to get href value using jQuery?

if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

Python: Removing list element while iterating over list

You could always iterate over a copy of the list, leaving you free to modify the original:

for item in list(somelist):
  ...
  somelist.remove(item)

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

How do I create a master branch in a bare Git repository?

You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

Prepare a dummy directory:

$ rm -rf /tmp/empty_directory
$ mkdir  /tmp/empty_directory

Create the master branch without a parent (works even on a completely empty repo):

$ cd your-bare-repository.git

$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master'                  <--- abort if "master" already exists

Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 

$ git branch
* master

Clean up the directory, it is still empty.

$ rmdir  /tmp/empty_directory

Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

Match linebreaks - \n or \r\n?

In PCRE \R matches \n, \r and \r\n.

Enabling HTTPS on express.js

This is my working code for express 4.0.

express 4.0 is very different from 3.0 and others.

4.0 you have /bin/www file, which you are going to add https here.

"npm start" is standard way you start express 4.0 server.

readFileSync() function should use __dirname get current directory

while require() use ./ refer to current directory.

First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.

How to set layout_gravity programmatically?

Modify the existing layout params and set layout params again

//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams

How long is the SHA256 hash?

It will be fixed 64 chars, so use char(64)

CSS ''background-color" attribute not working on checkbox inside <div>

After so much trouble i got it.

.purple_checkbox:after {
  content: " ";
  background-color: #5C2799;
  display: inline-block;
  visibility: visible;
}

.purple_checkbox:checked:after {
  content: "\2714";
  box-shadow: 0px 2px 4px rgba(155, 155, 155, 0.15);
  border-radius: 3px;
  height: 12px;
  display: block;
  width: 12px;
  text-align: center;
  font-size: 9px;
  color: white;
}

It will be like this when checked with this code. enter image description here

how to set the background color of the whole page in css

I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white to the HTML element. I overwrote that and everything was easy to handle from there.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

I'm going to add to the answer given before.

It's not a bug in your code or the browser's code. It's the JavaScript code inside the YouTube iframe polls for the extensions it could interoperate with in case they were installed (likely to determine if the extension is installed).

Look at the source of www-embed-player.js (loaded from s.ytimg.com, it's YouTube static files CDN). You'll find the following:

function Wj(a){return"chrome-extension://"+a+"/cast_sender.js"}

Parse JSON in C#

I tried to use the code above but didn't work. The JSON structure returned by Google is so different and there is a very important miss in the helper function: a call to DataContractJsonSerializer.ReadObject() that actually deserializes the JSON data into the object.

Here is the code that WORKS in 2011:

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace <YOUR_NAMESPACE>
{
    public class JSONHelper
    {
        public static T Deserialise<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serialiser.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }

    public class Result
    {
        public string GsearchResultClass { get; set; }
        public string unescapedUrl { get; set; }
        public string url { get; set; }
        public string visibleUrl { get; set; }
        public string cacheUrl { get; set; }
        public string title { get; set; }
        public string titleNoFormatting { get; set; }
        public string content { get; set; }
    }

    public class Page
    {
        public string start { get; set; }
        public int label { get; set; }
    }

    public class Cursor
    {
        public string resultCount { get; set; }
        public Page[] pages { get; set; }
        public string estimatedResultCount { get; set; }
        public int currentPageIndex { get; set; }
        public string moreResultsUrl { get; set; }
        public string searchResultTime { get; set; }
    }

    public class ResponseData
    {
        public Result[] results { get; set; }
        public Cursor cursor { get; set; }
    }

    public class GoogleSearchResults
    {
        public ResponseData responseData { get; set; }
        public object responseDetails { get; set; }
        public int responseStatus { get; set; }
    }
}

To get the content of the first result, do:

GoogleSearchResults googleResults = new GoogleSearchResults();
googleResults = JSONHelper.Deserialise<GoogleSearchResults>(jsonData);
string contentOfFirstResult = googleResults.responseData.results[0].content;

Calling remove in foreach loop in Java

Make sure this is not code smell. Is it possible to reverse the logic and be 'inclusive' rather than 'exclusive'?

List<String> names = ....
List<String> reducedNames = ....
for (String name : names) {
   // Do something
   if (conditionToIncludeMet)
       reducedNames.add(name);
}
return reducedNames;

The situation that led me to this page involved old code that looped through a List using indecies to remove elements from the List. I wanted to refactor it to use the foreach style.

It looped through an entire list of elements to verify which ones the user had permission to access, and removed the ones that didn't have permission from the list.

List<Service> services = ...
for (int i=0; i<services.size(); i++) {
    if (!isServicePermitted(user, services.get(i)))
         services.remove(i);
}

To reverse this and not use the remove:

List<Service> services = ...
List<Service> permittedServices = ...
for (Service service:services) {
    if (isServicePermitted(user, service))
         permittedServices.add(service);
}
return permittedServices;

When would "remove" be preferred? One consideration is if gien a large list or expensive "add", combined with only a few removed compared to the list size. It might be more efficient to only do a few removes rather than a great many adds. But in my case the situation did not merit such an optimization.

How can I get the ID of an element using jQuery?

This is an old question, but as of 2015 this may actually work:

$('#test').id;

And you can also make assignments:

$('#test').id = "abc";

As long as you define the following JQuery plugin:

Object.defineProperty($.fn, 'id', {
    get: function () { return this.attr("id"); },
    set: function (newValue) { this.attr("id", newValue); }
});

Interestingly, if element is a DOM element, then:

element.id === $(element).id; // Is true!

jQuery or CSS selector to select all IDs that start with some string

Normally you would select IDs using the ID selector #, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):

div[id^="player_"]

If you are able to modify that HTML, however, you should add a class to your player divs then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.

split string only on first instance - java

As many other answers suggest the limit approach, This can be another way

You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output

String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));

C# difference between == and Equals()

==

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

int a = 3;
byte b = 3;
if (a == b) { // true }

Note : there are more zeroes on the left side of the int but we don't care about that here.

int a (00000011) == byte b (00000011)

Remember == operator cares only about the pattern of the bits in the variable.

Use == If two references (primitives) refers to the same object on the heap.

Rules are same whether the variable is a reference or primitive.

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;

if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }

a == c is true a == b is false

the bit pattern are the same for a and c, so they are equal using ==.

Equal():

Use the equals() method to see if two different objects are equal.

Such as two different String objects that both represent the characters in "Jane"

How to pass parameters to ThreadStart method in Thread?

Look at this example:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(new Parameter());
}

public void WorkerMethod(object parameterObj)
{
    var parameter = (Parameter)parameterObj;
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

So in your case you should use it like this:

    Thread thread = new Thread(download);
    thread.Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

Check Whether a User Exists

Late answer but finger also shows more information on user

  sudo apt-get finger 
  finger "$username"

Android Studio doesn't recognize my device

For me, this ended up being because I had the wrong SDK level installed (new version of Android Studio installed the SDK for Android 10, whereas I have a device that runs only Android 8.1). While Android Studio would "recognize" the device and display a string in the "devices" menu instead of just saying that no device was connected, installing the right SDK level for my device ended up changing the string to something recognizable (my device's model name) and allowed me to actually run my app over ADB.

How to test REST API using Chrome's extension "Advanced Rest Client"

Add authorization header and click pencil button to enter username and passwords

enter image description here

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

Mongoose: Get full list of users

My Solution

User.find()
        .exec()
        .then(users => {
            const response = {
                count: users.length,
                users: users.map(user => {

                    return {
                        _id: user._id,
                        // other property
                    }

                })

            };
            res.status(200).json(response);
        }).catch(err => {
        console.log(err);
        res.status(500).json({
            success: false
        })
    })

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

How to create a batch file to run cmd as administrator

You can use a shortcut that links to the batch file. Just go into properties for the shortcut and select advanced, then "run as administrator".

Then just make the batch file hidden, and run the shortcut.

This way, you can even set your own icon for the shortcut.

RESTful URL design for search

I use two approaches to implement searches.

1) Simplest case, to query associated elements, and for navigation.

    /cars?q.garage.id.eq=1

This means, query cars that have garage ID equal to 1.

It is also possible to create more complex searches:

    /cars?q.garage.street.eq=FirstStreet&q.color.ne=red&offset=300&max=100

Cars in all garages in FirstStreet that are not red (3rd page, 100 elements per page).

2) Complex queries are considered as regular resources that are created and can be recovered.

    POST /searches  => Create
    GET  /searches/1  => Recover search
    GET  /searches/1?offset=300&max=100  => pagination in search

The POST body for search creation is as follows:

    {  
       "$class":"test.Car",
       "$q":{
          "$eq" : { "color" : "red" },
          "garage" : {
             "$ne" : { "street" : "FirstStreet" }
          }
       }
    }

It is based in Grails (criteria DSL): http://grails.org/doc/2.4.3/ref/Domain%20Classes/createCriteria.html

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

SQL Server Group By Month

Restrict the dimension of the NVARCHAR to 7, supplied to CONVERT to show only "YYYY-MM"

SELECT CONVERT(NVARCHAR(7),PaymentDate,120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(7),PaymentDate,120)
ORDER BY [Month]

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

C# DLL config file

Seems like this config files are really confusing to clarify as their behaviour changes from the dev environment to deployment. Apparently a DLL can have its own config file, but once you copy and paste the dll (together with their config file) elsewhere, the whole thing stopped working. The only solution is to manually merge the app.config files into a single file, which will only be used by the exec. For e.g. myapp.exe will have a myapp.exe.config file that contains all settings for all dlls used by myapp.exe. I'm using VS 2008.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

Unidirectional. Just add the inversedBy:(Foreign Column Name) to make it Bidirectional.

# config/yaml/ProductStore.dcm.yml
ProductStore:
  type: entity
  id:
    product:
      associationKey: true
    store:
      associationKey: true
  fields:
    status:
      type: integer(1)
    createdAt:
      type: datetime
    updatedAt:
      type: datetime
  manyToOne:
    product:
      targetEntity: Product
      joinColumn:
        name: product_id
        referencedColumnName: id
    store:
      targetEntity: Store
      joinColumn:
        name: store_id
        referencedColumnName: id

I hope it helps. See you.

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

If by "going crazy" you mean that each window keeps stealing focus from the other, TopMost will not solve the problem.

Instead, try:

CalledForm.Owner = CallerForm;
CalledForm.Show();

This will show the 'child' form without it stealing focus. The child form will also stay on top of its parent even if the parent is activated or focused. This code only works easily if you've created an instance of the child form from within the owner form. Otherwise, you might have to set the owner using the API.

Password hash function for Excel VBA

Here is the MD5 code inserted in an Excel Module with the name "module_md5":

    Private Const BITS_TO_A_BYTE = 8
    Private Const BYTES_TO_A_WORD = 4
    Private Const BITS_TO_A_WORD = 32

    Private m_lOnBits(30)
    Private m_l2Power(30)

    Sub SetUpArrays()
        m_lOnBits(0) = CLng(1)
        m_lOnBits(1) = CLng(3)
        m_lOnBits(2) = CLng(7)
        m_lOnBits(3) = CLng(15)
        m_lOnBits(4) = CLng(31)
        m_lOnBits(5) = CLng(63)
        m_lOnBits(6) = CLng(127)
        m_lOnBits(7) = CLng(255)
        m_lOnBits(8) = CLng(511)
        m_lOnBits(9) = CLng(1023)
        m_lOnBits(10) = CLng(2047)
        m_lOnBits(11) = CLng(4095)
        m_lOnBits(12) = CLng(8191)
        m_lOnBits(13) = CLng(16383)
        m_lOnBits(14) = CLng(32767)
        m_lOnBits(15) = CLng(65535)
        m_lOnBits(16) = CLng(131071)
        m_lOnBits(17) = CLng(262143)
        m_lOnBits(18) = CLng(524287)
        m_lOnBits(19) = CLng(1048575)
        m_lOnBits(20) = CLng(2097151)
        m_lOnBits(21) = CLng(4194303)
        m_lOnBits(22) = CLng(8388607)
        m_lOnBits(23) = CLng(16777215)
        m_lOnBits(24) = CLng(33554431)
        m_lOnBits(25) = CLng(67108863)
        m_lOnBits(26) = CLng(134217727)
        m_lOnBits(27) = CLng(268435455)
        m_lOnBits(28) = CLng(536870911)
        m_lOnBits(29) = CLng(1073741823)
        m_lOnBits(30) = CLng(2147483647)

        m_l2Power(0) = CLng(1)
        m_l2Power(1) = CLng(2)
        m_l2Power(2) = CLng(4)
        m_l2Power(3) = CLng(8)
        m_l2Power(4) = CLng(16)
        m_l2Power(5) = CLng(32)
        m_l2Power(6) = CLng(64)
        m_l2Power(7) = CLng(128)
        m_l2Power(8) = CLng(256)
        m_l2Power(9) = CLng(512)
        m_l2Power(10) = CLng(1024)
        m_l2Power(11) = CLng(2048)
        m_l2Power(12) = CLng(4096)
        m_l2Power(13) = CLng(8192)
        m_l2Power(14) = CLng(16384)
        m_l2Power(15) = CLng(32768)
        m_l2Power(16) = CLng(65536)
        m_l2Power(17) = CLng(131072)
        m_l2Power(18) = CLng(262144)
        m_l2Power(19) = CLng(524288)
        m_l2Power(20) = CLng(1048576)
        m_l2Power(21) = CLng(2097152)
        m_l2Power(22) = CLng(4194304)
        m_l2Power(23) = CLng(8388608)
        m_l2Power(24) = CLng(16777216)
        m_l2Power(25) = CLng(33554432)
        m_l2Power(26) = CLng(67108864)
        m_l2Power(27) = CLng(134217728)
        m_l2Power(28) = CLng(268435456)
        m_l2Power(29) = CLng(536870912)
        m_l2Power(30) = CLng(1073741824)
    End Sub

    Private Function LShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            LShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And 1 Then
                LShift = &H80000000
            Else
                LShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        If (lValue And m_l2Power(31 - iShiftBits)) Then
            LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
        Else
            LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
        End If
    End Function

    Private Function RShift(lValue, iShiftBits)
        If iShiftBits = 0 Then
            RShift = lValue
            Exit Function
        ElseIf iShiftBits = 31 Then
            If lValue And &H80000000 Then
                RShift = 1
            Else
                RShift = 0
            End If
            Exit Function
        ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
            Err.Raise 6
        End If

        RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)

        If (lValue And &H80000000) Then
            RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
        End If
    End Function

    Private Function RotateLeft(lValue, iShiftBits)
        RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
    End Function

    Private Function AddUnsigned(lX, lY)
        Dim lX4
        Dim lY4
        Dim lX8
        Dim lY8
        Dim lResult

        lX8 = lX And &H80000000
        lY8 = lY And &H80000000
        lX4 = lX And &H40000000
        lY4 = lY And &H40000000

        lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)

        If lX4 And lY4 Then
            lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
        ElseIf lX4 Or lY4 Then
            If lResult And &H40000000 Then
                lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
            Else
                lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
            End If
        Else
            lResult = lResult Xor lX8 Xor lY8
        End If

        AddUnsigned = lResult
    End Function

    Private Function F(x, y, z)
        F = (x And y) Or ((Not x) And z)
    End Function

    Private Function G(x, y, z)
        G = (x And z) Or (y And (Not z))
    End Function

    Private Function H(x, y, z)
        H = (x Xor y Xor z)
    End Function

    Private Function I(x, y, z)
        I = (y Xor (x Or (Not z)))
    End Function

    Private Sub FF(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub GG(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub HH(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Sub II(a, b, c, d, x, s, ac)
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))
        a = RotateLeft(a, s)
        a = AddUnsigned(a, b)
    End Sub

    Private Function ConvertToWordArray(sMessage)
        Dim lMessageLength
        Dim lNumberOfWords
        Dim lWordArray()
        Dim lBytePosition
        Dim lByteCount
        Dim lWordCount

        Const MODULUS_BITS = 512
        Const CONGRUENT_BITS = 448

        lMessageLength = Len(sMessage)

        lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
        ReDim lWordArray(lNumberOfWords - 1)

        lBytePosition = 0
        lByteCount = 0
        Do Until lByteCount >= lMessageLength
            lWordCount = lByteCount \ BYTES_TO_A_WORD
            lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
            lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
            lByteCount = lByteCount + 1
        Loop

        lWordCount = lByteCount \ BYTES_TO_A_WORD
        lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE

        lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)

        lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
        lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)

        ConvertToWordArray = lWordArray
    End Function

    Private Function WordToHex(lValue)
        Dim lByte
        Dim lCount

        For lCount = 0 To 3
            lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
            WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
        Next
    End Function

    Public Function MD5(sMessage)

        module_md5.SetUpArrays

        Dim x
        Dim k
        Dim AA
        Dim BB
        Dim CC
        Dim DD
        Dim a
        Dim b
        Dim c
        Dim d

        Const S11 = 7
        Const S12 = 12
        Const S13 = 17
        Const S14 = 22
        Const S21 = 5
        Const S22 = 9
        Const S23 = 14
        Const S24 = 20
        Const S31 = 4
        Const S32 = 11
        Const S33 = 16
        Const S34 = 23
        Const S41 = 6
        Const S42 = 10
        Const S43 = 15
        Const S44 = 21

        x = ConvertToWordArray(sMessage)

        a = &H67452301
        b = &HEFCDAB89
        c = &H98BADCFE
        d = &H10325476

        For k = 0 To UBound(x) Step 16
            AA = a
            BB = b
            CC = c
            DD = d

            FF a, b, c, d, x(k + 0), S11, &HD76AA478
            FF d, a, b, c, x(k + 1), S12, &HE8C7B756
            FF c, d, a, b, x(k + 2), S13, &H242070DB
            FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
            FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
            FF d, a, b, c, x(k + 5), S12, &H4787C62A
            FF c, d, a, b, x(k + 6), S13, &HA8304613
            FF b, c, d, a, x(k + 7), S14, &HFD469501
            FF a, b, c, d, x(k + 8), S11, &H698098D8
            FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
            FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
            FF b, c, d, a, x(k + 11), S14, &H895CD7BE
            FF a, b, c, d, x(k + 12), S11, &H6B901122
            FF d, a, b, c, x(k + 13), S12, &HFD987193
            FF c, d, a, b, x(k + 14), S13, &HA679438E
            FF b, c, d, a, x(k + 15), S14, &H49B40821

            GG a, b, c, d, x(k + 1), S21, &HF61E2562
            GG d, a, b, c, x(k + 6), S22, &HC040B340
            GG c, d, a, b, x(k + 11), S23, &H265E5A51
            GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
            GG a, b, c, d, x(k + 5), S21, &HD62F105D
            GG d, a, b, c, x(k + 10), S22, &H2441453
            GG c, d, a, b, x(k + 15), S23, &HD8A1E681
            GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
            GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
            GG d, a, b, c, x(k + 14), S22, &HC33707D6
            GG c, d, a, b, x(k + 3), S23, &HF4D50D87
            GG b, c, d, a, x(k + 8), S24, &H455A14ED
            GG a, b, c, d, x(k + 13), S21, &HA9E3E905
            GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
            GG c, d, a, b, x(k + 7), S23, &H676F02D9
            GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A

            HH a, b, c, d, x(k + 5), S31, &HFFFA3942
            HH d, a, b, c, x(k + 8), S32, &H8771F681
            HH c, d, a, b, x(k + 11), S33, &H6D9D6122
            HH b, c, d, a, x(k + 14), S34, &HFDE5380C
            HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
            HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
            HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
            HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
            HH a, b, c, d, x(k + 13), S31, &H289B7EC6
            HH d, a, b, c, x(k + 0), S32, &HEAA127FA
            HH c, d, a, b, x(k + 3), S33, &HD4EF3085
            HH b, c, d, a, x(k + 6), S34, &H4881D05
            HH a, b, c, d, x(k + 9), S31, &HD9D4D039
            HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
            HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
            HH b, c, d, a, x(k + 2), S34, &HC4AC5665

            II a, b, c, d, x(k + 0), S41, &HF4292244
            II d, a, b, c, x(k + 7), S42, &H432AFF97
            II c, d, a, b, x(k + 14), S43, &HAB9423A7
            II b, c, d, a, x(k + 5), S44, &HFC93A039
            II a, b, c, d, x(k + 12), S41, &H655B59C3
            II d, a, b, c, x(k + 3), S42, &H8F0CCC92
            II c, d, a, b, x(k + 10), S43, &HFFEFF47D
            II b, c, d, a, x(k + 1), S44, &H85845DD1
            II a, b, c, d, x(k + 8), S41, &H6FA87E4F
            II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
            II c, d, a, b, x(k + 6), S43, &HA3014314
            II b, c, d, a, x(k + 13), S44, &H4E0811A1
            II a, b, c, d, x(k + 4), S41, &HF7537E82
            II d, a, b, c, x(k + 11), S42, &HBD3AF235
            II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
            II b, c, d, a, x(k + 9), S44, &HEB86D391

            a = AddUnsigned(a, AA)
            b = AddUnsigned(b, BB)
            c = AddUnsigned(c, CC)
            d = AddUnsigned(d, DD)
        Next

        MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
    End Function

How do I use $scope.$watch and $scope.$apply in AngularJS?

AngularJS extends this events-loop, creating something called AngularJS context.

$watch()

Every time you bind something in the UI you insert a $watch in a $watch list.

User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />

Here we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watches to the $watch list.

When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watches that are needed.

AngularJS provides $watch, $watchcollection and $watch(true). Below is a neat diagram explaining all the three taken from watchers in depth.

Enter image description here

angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
  $scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];

  $scope.$watch("users", function() {
    console.log("**** reference checkers $watch ****")
  });

  $scope.$watchCollection("users", function() {
    console.log("**** Collection  checkers $watchCollection ****")
  });

  $scope.$watch("users", function() {
    console.log("**** equality checkers with $watch(true) ****")
  }, true);

  $timeout(function(){
     console.log("Triggers All ")
     $scope.users = [];
     $scope.$digest();

     console.log("Triggers $watchCollection and $watch(true)")
     $scope.users.push({ name: 'Thalaivar'});
     $scope.$digest();

     console.log("Triggers $watch(true)")
     $scope.users[0].name = 'Superstar';
     $scope.$digest();
  });
}

http://jsfiddle.net/2Lyn0Lkb/

$digest loop

When the browser receives an event that can be managed by the AngularJS context the $digest loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync queue, and the other one processes the $watch list. The $digest will loop through the list of $watch that we have

app.controller('MainCtrl', function() {
  $scope.name = "vinoth";

  $scope.changeFoo = function() {
      $scope.name = "Thalaivar";
  }
});

{{ name }}
<button ng-click="changeFoo()">Change the name</button>

Here we have only one $watch because ng-click doesn’t create any watches.

We press the button.

  1. The browser receives an event which will enter the AngularJS context
  2. The $digest loop will run and will ask every $watch for changes.
  3. Since the $watch which was watching for changes in $scope.name reports a change, it will force another $digest loop.
  4. The new loop reports nothing.
  5. The browser gets the control back and it will update the DOM reflecting the new value of $scope.name
  6. The important thing here is that EVERY event that enters the AngularJS context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.

$apply()

If you call $apply when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply will call the $digest() loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.

The $apply() method will trigger watchers on the entire $scope chain whereas the $digest() method will only trigger watchers on the current $scope and its children. When none of the higher-up $scope objects need to know about the local changes, you can use $digest().

Do you use NULL or 0 (zero) for pointers in C++?

Setting a pointer to 0 is just not that clear. Especially if you come a language other than C++. This includes C as well as Javascript.

I recently delt with some code like so:

virtual void DrawTo(BITMAP *buffer) =0;

for pure virtual function for the first time. I thought it to be some magic jiberjash for a week. When I realized it was just basically setting the function pointer to a null (as virtual functions are just function pointers in most cases for C++) I kicked myself.

virtual void DrawTo(BITMAP *buffer) =null;

would have been less confusing than that basterdation without proper spacing to my new eyes. Actually, I am wondering why C++ doesn't employ lowercase null much like it employes lowercase false and true now.

jQuery hasClass() - check for more than one class

Works for me:

 if ( $("element").hasClass( "class1") || $("element").hasClass("class2") ) {

 //do something here

 }

Why does my Spring Boot App always shutdown immediately after starting?

In my case the problem was introduced when I fixed a static analysis error that the return value of a method was not used.

Old working code in my Application.java was:

    public static void main(String[] args) {        
      SpringApplication.run(Application.class, args);
    }

New code that introduced the problem was:

    public static void main(String[] args) {        
      try (ConfigurableApplicationContext context = 
          SpringApplication.run(Application.class, args)) {
        LOG.trace("context: " + context);
      }
    }

Obviously, the try with resource block will close the context after starting the application which will result in the application exiting with status 0. This was a case where the resource leak error reported by snarqube static analysis should be ignored.

Get item in the list in Scala?

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).

What does += mean in Python?

a += b

is in this case the same as

a = a + b

In this case cnt += 1 means that cnt is increased by one.

Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.

Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.

Video auto play is not working in Safari and Chrome desktop browser

The best fix I could get was adding this code just after the </video>

<script>
    document.getElementById('vid').play();
</script>

...not pretty but somehow works.

UPDATE Recently many browsers can only autoplay the videos with sound off, so you'll need to add muted attribute to the video tag too

<video autoplay muted>
...
</video>

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I think , your app installed by other account.( multiple account mode feature ) You can uninstall app in Setting>Apps>"app name"> Uninstall

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

How to create a number picker dialog?

To show NumberPicker in AlertDialog use this code :

final AlertDialog.Builder d = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.number_picker_dialog, null);
d.setTitle("Title");
d.setMessage("Message");
d.setView(dialogView);
final NumberPicker numberPicker = (NumberPicker) dialogView.findViewById(R.id.dialog_number_picker);
numberPicker.setMaxValue(50);
numberPicker.setMinValue(1);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i1) {
        Log.d(TAG, "onValueChange: ");
    }
});
d.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        Log.d(TAG, "onClick: " + numberPicker.getValue());
    }
});
d.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    }
});
AlertDialog alertDialog = d.create();
alertDialog.show();

number_picker_dialog.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">

<NumberPicker
    android:id="@+id/dialog_number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

PHP float with 2 decimal places: .00

you can try this,it will work for you

number_format(0.00, 2)

How to delete object from array inside foreach loop?

It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.

The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

using c# .net libraries to check for IMAP messages from gmail servers

I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).

One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).

It's also the only library that I know of that supports threading of messages.

using System;
using System.Net;
using System.Threading;

using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            using (var client = new ImapClient ()) {
                using (var cancel = new CancellationTokenSource ()) {
                    client.Connect ("imap.gmail.com", 993, true, cancel.Token);

                    // If you want to disable an authentication mechanism,
                    // you can do so by removing the mechanism like this:
                    client.AuthenticationMechanisms.Remove ("XOAUTH");

                    client.Authenticate ("joey", "password", cancel.Token);

                    // The Inbox folder is always available...
                    var inbox = client.Inbox;
                    inbox.Open (FolderAccess.ReadOnly, cancel.Token);

                    Console.WriteLine ("Total messages: {0}", inbox.Count);
                    Console.WriteLine ("Recent messages: {0}", inbox.Recent);

                    // download each message based on the message index
                    for (int i = 0; i < inbox.Count; i++) {
                        var message = inbox.GetMessage (i, cancel.Token);
                        Console.WriteLine ("Subject: {0}", message.Subject);
                    }

                    // let's try searching for some messages...
                    var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
                        .And (SearchQuery.SubjectContains ("MailKit"))
                        .And (SearchQuery.Seen);

                    foreach (var uid in inbox.Search (query, cancel.Token)) {
                        var message = inbox.GetMessage (uid, cancel.Token);
                        Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
                    }

                    client.Disconnect (true, cancel.Token);
                }
            }
        }
    }
}

How to determine if a number is positive or negative?

if (((Double)calcYourDouble()).toString().contains("-"))
        doThis();
else doThat();

Easy way to convert Iterable to Collection

I use FluentIterable.from(myIterable).toList() a lot.

Why can't variables be declared in a switch statement?

I just wanted to emphasize slim's point. A switch construct creates a whole, first-class-citizen scope. So it is posible to declare (and initialize) a variable in a switch statement before the first case label, without an additional bracket pair:

switch (val) {  
  /* This *will* work, even in C89 */
  int newVal = 42;  
case VAL:
  newVal = 1984; 
  break;
case ANOTHER_VAL:  
  newVal = 2001;
  break;
}

Truncate string in Laravel blade templates

In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.

While in Laravel 5.8 up, you can use the Str::limit helper.

//For Laravel 4 to Laravel 5.5
{{ str_limit($string, $limit = 150, $end = '...') }}
//For Laravel 5.5 upwards
{{ \Illuminate\Support\Str::limit($string, 150, $end='...') }}

For more Laravel helper functions http://laravel.com/docs/helpers#strings

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

Pause Console in C++ program

If you want to write portable C++ code, then I'd suggest using cin.get().

system("PAUSE") works on Windows, since it requires the execution of a console command named "PAUSE". But I'm not sure that other operating systems like Linux or other Unix derivatives support that. So that tends to be non-portable.

Since C++ already offers cin.get(), I see no compelling reason to use C getch().

Http 415 Unsupported Media type error with JSON

I was sending "delete" rest request and it failed with 415. I saw what content-type my server uses to hit the api. In my case, It was "application/json" instead of "application/json; charset=utf8".

So ask from your api developer And in the meantime try sending request with content-type= "application/json" only.

Convert Python ElementTree to string

If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e)) you can use dump like this:

xml.etree.ElementTree.dump(e)

And this works both with Element and ElementTree objects as e, so there should be no need for getroot.

The documentation of dump says:

xml.etree.ElementTree.dump(elem)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.

elem is an element tree or an individual element.

Changed in version 3.8: The dump() function now preserves the attribute order specified by the user.

How to calculate a time difference in C++

In Windows: use GetTickCount

//GetTickCount defintition
#include <windows.h>
int main()
{

    DWORD dw1 = GetTickCount();

    //Do something 

    DWORD dw2 = GetTickCount();

    cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;

}

How to Apply Corner Radius to LinearLayout

You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How to change line width in ggplot?

It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

How do I add a Maven dependency in Eclipse?

You need to be using a Maven plugin for Eclipse in order to do this properly. The m2e plugin is built into the latest version of Eclipse, and does a decent if not perfect job of integrating Maven into the IDE. You will want to create your project as a 'Maven Project'. Alternatively you can import an existing Maven POM into your workspace to automatically create projects. Once you have your Maven project in the IDE, simply open up the POM and add your dependency to it.

Now, if you do not have a Maven plugin for Eclipse, you will need to get the jar(s) for the dependency in question and manually add them as classpath references to your project. This could get unpleasant as you will need not just the top level JAR, but all its dependencies as well.

Basically, I recommend you get a decent Maven plugin for Eclipse and let it handle the dependency management for you.

Height of an HTML select box (dropdown)

i have been working on a dropdown replacement jquery plugin to combat this problem. As of this post, it is almost indistinguishable from a native dropdown in terms of look and functionality.

here is a demo (also a link to downloads): http://programmingdrunk.com/current-projects/dropdownReplacement/

here is the project page of the plugin:

http://plugins.jquery.com/project/dropdownreplacement

(update:) the jquery plugin page seems to no longer work. I will probably not put my plugin on their new site when they get it working, so feel free to use the programmingdrunk.com link for demo/download