- Programming Questions & Answers Hub For Beginners

Some Of The Best Answers From Latest Asked Questions

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.

How do I remove an item from a stl vector with a certain value?

The other answers cover how to do this well, but I thought I'd also point out that it's not really odd that this isn't in the vector API: it's inefficient, linear search through the vector for the value, followed by a bunch of copying to remove it.

If you're doing this operation intensively, it can be worth considering std::set instead for this reason.

Why doesn't JavaScript support multithreading?

I don't know the rationale for this decision, but I know that you can simulate some of the benefits of multi-threaded programming using setTimeout. You can give the illusion of multiple processes doing things at the same time, though in reality, everything happens in one thread.

Just have your function do a little bit of work, and then call something like:

setTimeout(function () {
    ... do the rest of the work...
}, 0);

And any other things that need doing (like UI updates, animated images, etc) will happen when they get a chance.

Embed a PowerPoint presentation into HTML

Well, I think you get to convert the powerpoint to flash first. PowerPoint is not a sharable format on Internet. Some tool like PowerPoint to Flash could be helpful for you.

Is a GUID unique 100% of the time?

I experienced a duplicate GUID.

I use the Neat Receipts desktop scanner and it comes with proprietary database software. The software has a sync to cloud feature, and I kept getting an error upon syncing. A gander at the logs revealed the awesome line:

"errors":[{"code":1,"message":"creator_guid: is already taken","guid":"C83E5734-D77A-4B09-B8C1-9623CAC7B167"}]}

I was a bit in disbelief, but surely enough, when I found a way into my local neatworks database and deleted the record containing that GUID, the error stopped occurring.

So to answer your question with anecdotal evidence, no. A duplicate is possible. But it is likely that the reason it happened wasn't due to chance, but due to standard practice not being adhered to in some way. (I am just not that lucky) However, I cannot say for sure. It isn't my software.

Their customer support was EXTREMELY courteous and helpful, but they must have never encountered this issue before because after 3+ hours on the phone with them, they didn't find the solution. (FWIW, I am very impressed by Neat, and this glitch, however frustrating, didn't change my opinion of their product.)

How to loop through files matching wildcard in batch file

Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.

According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:

for %%f in (*.in) do call process.cmd %%~nf

Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:

echo The file is %0
copy %0.out
ren %0.out monkeys_are_cool.txt

There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.

EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...

Best way to do multi-row insert in Oracle?

Here is a very useful step by step guideline for insert multi rows in Oracle:

The last step:

/* Everyone is a person, so insert all rows into people */
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
  WITH names AS (
    SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
           NULL hired_date, DATE'2009-12-31' admission_date
    FROM   dual UNION ALL
    SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
           NULL hired_date, DATE'2014-01-01' admission_date
    FROM   dual UNION ALL
    SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
           NULL hired_date, DATE'2015-04-22' admission_date
    FROM   dual UNION ALL
    SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
           DATE'2015-01-01' hired_date, NULL admission_date
    FROM   dual
  SELECT * FROM names

What is the best way to convert an array to a hash in Ruby

Not sure if it's the best way, but this works:

a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
  m1[a[x*2]] = a[x*2 + 1]

b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
  m2[x] = y

What is the yield keyword used for in C#?

It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

How do I install a color theme for IntelliJ IDEA 7.0.x

Go to File->Import Settings... and select the jar settings file

Update as of IntelliJ 2020:

Go to File -> Manage IDE Settings -> Import Settings...

Search and replace a line in a file in Python

fileinput is quite straightforward as mentioned on previous answers:

import fileinput

def replace_in_file(file_path, search_text, new_text):
    with fileinput.input(file_path, inplace=True) as f:
        for line in f:
            new_line = line.replace(search_text, new_text)
            print(new_line, end='')


  • fileinput can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path in with statement.
  • print statement does not print anything when inplace=True, because STDOUT is being forwarded to the original file.
  • end='' in print statement is to eliminate intermediate blank new lines.

Can be used as follows:

file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

In your case, what you can do is:

z = dict(list(x.items()) + list(y.items()))

This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict's value:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}

If you use Python 2, you can even remove the list() calls. To create z:

>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}

If you use Python version 3.9.0a4 or greater, then you can directly use:

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x | y
{'a': 1, 'c': 11, 'b': 10}

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

What static analysis tools are available for C#?

  • Gendarme is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
  • Clone Detective is a nice plug-in for Visual Studio that finds duplicate code.
  • Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).

Using Django time/date widgets in custom form

Starting in Django 1.2 RC1, if you're using the Django admin date picker widge trick, the following has to be added to your template, or you'll see the calendar icon url being referenced through "/missing-admin-media-prefix/".

{% load adminmedia %} /* At the top of the template. */

/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";

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

The General Idea

Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN, RIGHT OUTER JOIN and LEFT OUTER JOIN.

These two table form a basis for the representation of the JOINs below:




  FROM citizen
 CROSS JOIN postalcode

The result will be the Cartesian products of all combinations. No JOIN condition required:



INNER JOIN is the same as simply: JOIN


  FROM citizen    c
  JOIN postalcode p ON c.postal = p.postal

The result will be combinations that satisfies the required JOIN condition:





  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal

The result will be everything from citizen even if there are no matches in postalcode. Again a JOIN condition is required:


Data for playing

All examples have been run on an Oracle 18c. They're available at which is also where screenshots of tables came from.

CREATE TABLE citizen (id      NUMBER,
                      name    VARCHAR2(20),
                      postal  NUMBER,  -- <-- could do with a redesign to instead.
                      leader  NUMBER);

CREATE TABLE postalcode (id      NUMBER,
                         postal  NUMBER,
                         city    VARCHAR2(20),
                         area    VARCHAR2(20));

INSERT INTO citizen (id, name, postal, leader)
              SELECT 1, 'Smith', 2200,  null FROM DUAL
        UNION SELECT 2, 'Green', 31006, 1    FROM DUAL
        UNION SELECT 3, 'Jensen', 623,  1    FROM DUAL;

INSERT INTO postalcode (id, postal, city, area)
                 SELECT 1, 2200,     'BigCity',         'Geancy'  FROM DUAL
           UNION SELECT 2, 31006,    'SmallTown',       'Snizkim' FROM DUAL
           UNION SELECT 3, 31006,    'Settlement',      'Moon'    FROM DUAL  -- <-- Uuh-uhh.
           UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space'   FROM DUAL;

Blurry boundaries when playing with JOIN and WHERE


CROSS JOIN resulting in rows as The General Idea/INNER JOIN:

  FROM citizen          c
  CROSS JOIN postalcode p
 WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows

Using CROSS JOIN to get the result of a LEFT OUTER JOIN requires tricks like adding in a NULL row. It's omitted.


INNER JOIN becomes a cartesian products. It's the same as The General Idea/CROSS JOIN:

  FROM citizen    c
  JOIN postalcode p ON 1 = 1  -- < -- The ON condition makes it a CROSS JOIN

This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.

Using INNER JOIN to get the result of a LEFT OUTER JOIN also requires tricks. It's omitted.


LEFT JOIN results in rows as The General Idea/CROSS JOIN:

  FROM citizen         c
  LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN

LEFT JOIN results in rows as The General Idea/INNER JOIN:

  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal
 WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode

The troubles with the Venn diagram

An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.

Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.

Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.

The set A represents the set on the left (the citizen table) and the set B is the set on the right (the postalcode table) in below discussion.


Every element in both sets are matched with every element in the other set, meaning we need A amount of every B elements and B amount of every A elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION fits at all.

The rows are distinct. The UNION is 7 rows in total. But they're incompatible for a common SQL results set. And this is not how a CROSS JOIN works at all:


Trying to represent it like this:


..but now it just looks like an INTERSECTION, which it's certainly not. Furthermore there's no element in the INTERSECTION that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:


For reference one searchable result for CROSS JOINs can be seen at Tutorialgateway. The INTERSECTION, just like this one, is empty.


The value of an element depends on the JOIN condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x is only true for one row. Once a row in table A (citizen) matches multiple rows in table B (postalcode) under the JOIN condition, the result has the same problems as the CROSS JOIN: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN condition determines the placement of an element in the diagram. Looking only at the values of the JOIN condition with the rest of the row just along for the ride:

InnerJoinIntersection - Filled

This representation falls completely apart when using an INNER JOIN with a ON 1 = 1 condition making it into a CROSS JOIN.

With a self-JOIN, the rows are in fact idential elements in both tables, but representing the tables as both A and B isn't very suitable. For example a common self-JOIN condition that makes an element in A to be matching a different element in B is ON A.parent = B.child, making the match from A to B on seperate elements. From the examples that would be a SQL like this:

  FROM citizen c1
  JOIN citizen c2 ON = c2.leader


Meaning Smith is the leader of both Green and Jensen.


Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN can be though of as to match the empty set. But in set theory the union of any set C and an empty set, is always just C. The empty set adds nothing. The representation of this LEFT OUTER JOIN is usually just showing all of A to illustrate that rows in A are selected regardless of whether there is a match or not from B. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A:

LeftJoinIntersection - Filled

WHERE clause - making sense

Finding all rows from a CROSS JOIN with Smith and postalcode on the Moon:

  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE = 'Smith'
   AND p.area = 'Moon';

Where - result

Now the Venn diagram isn't used to reflect the JOIN. It's used only for the WHERE clause:


..and that makes sense.

When INTERSECT and UNION makes sense


As explained an INNER JOIN is not really an INTERSECT. However INTERSECTs can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL will result in the same row as the one above WHERE, and the Venn diagram will also be the same:

  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE = 'Smith'
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';


An OUTER JOIN is not a UNION. However UNION work under the same conditions as INTERSECT, resulting in a return of all results combining both SELECTs:

  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE = 'Smith'
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';

which is equivalent to:

  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE = 'Smith'
   OR p.area = 'Moon';

..and gives the result:

Union - Result

Also here a Venn diagram makes sense:


When it doesn't apply

An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:

  FROM citizen
 WHERE name = 'Smith'
  FROM postalcode
 WHERE area = 'Moon';

..trying to combine the results with UNION gives a

ORA-01790: expression must have same datatype as corresponding expression

For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT.

What is the purpose of class methods?

What just hit me, coming from Ruby, is that a so-called class method and a so-called instance method is just a function with semantic meaning applied to its first parameter, which is silently passed when the function is called as a method of an object (i.e. obj.meth()).

Normally that object must be an instance but the @classmethod method decorator changes the rules to pass a class. You can call a class method on an instance (it's just a function) - the first argument will be its class.

Because it's just a function, it can only be declared once in any given scope (i.e. class definition). If follows therefore, as a surprise to a Rubyist, that you can't have a class method and an instance method with the same name.

Consider this:

class Foo():
  def foo(x):

You can call foo on an instance

<__main__.Foo instance at 0x7f4dd3e3bc20>

But not on a class:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)

Now add @classmethod:

class Foo():
  def foo(x):

Calling on an instance now passes its class:


as does calling on a class:

It's only convention that dictates that we use self for that first argument on an instance method and cls on a class method. I used neither here to illustrate that it's just an argument. In Ruby, self is a keyword.

Contrast with Ruby:

class Foo
  def foo()
    puts "instance method #{self}"
    puts "class method #{self}"
class method Foo
instance method #<Foo:0x000000020fe018>

The Python class method is just a decorated function and you can use the same techniques to create your own decorators. A decorated method wraps the real method (in the case of @classmethod it passes the additional class argument). The underlying method is still there, hidden but still accessible.

footnote: I wrote this after a name clash between a class and instance method piqued my curiosity. I am far from a Python expert and would like comments if any of this is wrong.

How can I get the DateTime for the start of the week?

Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week.

    DateTime WeekBeginning(DateTime input)
            if (input.DayOfWeek.ToString() == "Monday")
                return input;
                return WeekBeginning(input.AddDays(-1));
        } while (input.DayOfWeek.ToString() == "Monday");

How do I find the authoritative name-server for a domain name?

You used the singular in your question but there are typically several authoritative name servers, the RFC 1034 recommends at least two.

Unless you mean "primary name server" and not "authoritative name server". The secondary name servers are authoritative.

To find out the name servers of a domain on Unix:

  % dig +short NS

To find out the server listed as primary (the notion of "primary" is quite fuzzy these days and typically has no good answer):

% dig +short  SOA | cut -d' ' -f1

To check discrepencies between name servers, my preference goes to the old check_soa tool, described in Liu & Albitz "DNS & BIND" book (O'Reilly editor). The source code is available in

% check_soa has serial number 2008041300 has serial number 2008041300

Here, the two authoritative name servers have the same serial number. Good.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Here is my solution:

/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\:([012345][0-9])\:([012345][0-9])$/u

How to replace plain URLs with links?

I had to do the opposite, and make html links into just the URL, but I modified your regex and it works like a charm, thanks :)

var exp = /<a\s.*href=['"](\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])['"].*>.*<\/a>/ig;

source = source.replace(exp,"$1");

What is reflection and why is it useful?

As name itself suggest it reflects what it holds for example class method,etc apart from providing feature to invoke method creating instance dynamically at runtime.

It is used by many frameworks and application under the wood to invoke services without actually knowing the code.

How do I determine the size of my array in C?

Note: This one can give you undefined behaviour as pointed by M.M in the comment.

int a[10];
int size = (*(&a+1)-a) ;

For more details see here and also here.

iPhone App Minus App Store?

With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.

Now everyone can get their app on their Apple device.

Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.

Quoted from:


XCode 7 is now released:

Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.

See Launching Your App on Devices for detailed information about installing and running on devices.

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

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Yes, with -Xmx you can configure more memory for your JVM. To be sure that you don't leak or waste memory. Take a heap dump and use the Eclipse Memory Analyzer to analyze your memory consumption.

What is the syntax for an inner join in LINQ to SQL?

And because I prefer the expression chain syntax, here is how you do it with that:

var dealerContracts = DealerContact.Join(Dealer, 
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);

SQL Query for Logins

On SQL Azure as of 2012;


SELECT * from master.sys.sql_logins


SELECT * from master.sys.sysusers

How do you remove a specific revision in the git history?

Here is a way to remove non-interactively a specific <commit-id>, knowing only the <commit-id> you would like to remove:

git rebase --onto <commit-id>^ <commit-id> HEAD

Make browser window blink in task Bar

                var oldTitle = document.title;
                var msg = "New Popup!";
                var timeoutId = false;

                var blink = function() {
                    document.title = document.title == msg ? oldTitle : msg;//Modify Title in case a popup

                    if(document.hasFocus())//Stop blinking and restore the Application Title
                        document.title = oldTitle;

                if (!timeoutId) {
                    timeoutId = setInterval(blink, 500);//Initiate the Blink Call
                };//Blink logic 

CSS - Make divs align horizontally

You may put an inner div in the container that is enough wide to hold all the floated divs.

#container {_x000D_
  background-color: red;_x000D_
  overflow: hidden;_x000D_
  width: 200px;_x000D_
#inner {_x000D_
  overflow: hidden;_x000D_
  width: 2000px;_x000D_
.child {_x000D_
  float: left;_x000D_
  background-color: blue;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
<div id="container">_x000D_
  <div id="inner">_x000D_
    <div class="child"></div>_x000D_
    <div class="child"></div>_x000D_
    <div class="child"></div>_x000D_

Java: notify() vs. notifyAll() all over again

notify() wakes up the first thread that called wait() on the same object.

notifyAll() wakes up all the threads that called wait() on the same object.

The highest priority thread will run first.

How do you use script variables in psql?

I solved it with a temp table.

CREATE TEMP TABLE temp_session_variables (
    "sessionSalt" TEXT
INSERT INTO temp_session_variables ("sessionSalt") VALUES (current_timestamp || RANDOM()::TEXT);

This way, I had a "variable" I could use over multiple queries, that is unique for the session. I needed it to generate unique "usernames" while still not having collisions if importing users with the same user name.

How can I represent an 'Enum' in Python?

Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:

months = {
    'January': 1,
    'February': 2,


months = dict(

Then, you can use the symbolic name for the constants like this:

mymonth = months['January']

There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the value.

Edit: I like Alexandru's answer too!

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

What does ** (double star) and * (star) do for parameters

They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*) and keyword (**).

Defining Functions

*args allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args.

**kwargs allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs.

You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics, args and kwargs are standard names.

Expansion, Passing any number of arguments

You can also use *args and **kwargs to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.

The function recieving the parameters does not have to know that they are being expanded.

For example, Python 2's xrange does not explicitly expect *args, but since it takes 3 integers as arguments:

>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x)    # expand here
xrange(0, 2, 2)

As another example, we can use dict expansion in str.format:

>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'

New in Python 3: Defining functions with keyword only arguments

You can have keyword only arguments after the *args - for example, here, kwarg2 must be given as a keyword argument - not positionally:

def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): 
    return arg, kwarg, args, kwarg2, kwargs


>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})

Also, * can be used by itself to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.

def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): 
    return arg, kwarg, kwarg2, kwargs

Here, kwarg2 again must be an explicitly named, keyword argument:

>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})

And we can no longer accept unlimited positional arguments because we don't have *args*:

>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments 
    but 5 positional arguments (and 1 keyword-only argument) were given

Again, more simply, here we require kwarg to be given by name, not positionally:

def bar(*, kwarg=None): 
    return kwarg

In this example, we see that if we try to pass kwarg positionally, we get an error:

>>> bar('kwarg')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given

We must explicitly pass the kwarg parameter as a keyword argument.

>>> bar(kwarg='kwarg')

Python 2 compatible demos

*args (typically said "star-args") and **kwargs (stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the * and ** notation. These specific variable names aren't required (e.g. you could use *foos and **bars), but a departure from convention is likely to enrage your fellow Python coders.

We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).

Example 1

The following function describes how they can be used, and demonstrates behavior. Note the named b argument will be consumed by the second positional argument before :

def foo(a, b=10, *args, **kwargs):
    this function takes required argument a, not required keyword argument b
    and any number of unknown positional arguments and keyword arguments after
    print('a is a required argument, and its value is {0}'.format(a))
    print('b not required, its default value is 10, actual value: {0}'.format(b))
    # we can inspect the unknown arguments we were passed:
    #  - args:
    print('args is of type {0} and length {1}'.format(type(args), len(args)))
    for arg in args:
        print('unknown arg: {0}'.format(arg))
    #  - kwargs:
    print('kwargs is of type {0} and length {1}'.format(type(kwargs),
    for kw, arg in kwargs.items():
        print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
    # But we don't have to know anything about them 
    # to pass them to other functions.
    print('Args or kwargs can be passed without knowing what they are.')
    # max can take two or more positional args: max(a, b, c...)
    print('e.g. max(a, b, *args) \n{0}'.format(
      max(a, b, *args))) 
    kweg = 'dict({0})'.format( # named args same as unknown kwargs
      ', '.join('{k}={v}'.format(k=k, v=v) 
                             for k, v in sorted(kwargs.items())))
    print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
      dict(**kwargs), kweg=kweg))

We can check the online help for the function's signature, with help(foo), which tells us

foo(a, b=10, *args, **kwargs)

Let's call this function with foo(1, 2, 3, 4, e=5, f=6, g=7)

which prints:

a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args) 
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: 
{'e': 5, 'g': 7, 'f': 6}

Example 2

We can also call it using another function, into which we just provide a:

def bar(a):
    b, c, d, e, f = 2, 3, 4, 5, 6
    # dumping every local variable into foo as a keyword argument 
    # by expanding the locals dict:

bar(100) prints:

a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args) 
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: 
{'c': 3, 'e': 5, 'd': 4, 'f': 6}

Example 3: practical usage in decorators

OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.

def foo(a, b, c, d=0, e=100):
    # imagine this is much more code than a simple function call
    # imagine this is much more code than a simple function call

def bar(a, b, c=None, d=0, e=100, f=None):

def baz(a, b, c, d, e, f):
    ... and so on

We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how *args and **kwargs can be very useful:

def decorator(function):
    '''function to wrap other functions with a pre- and postprocess'''
    @functools.wraps(function) # applies module, name, and docstring to wrapper
    def wrapper(*args, **kwargs):
        # again, imagine this is complicated, but we only write it once!
        function(*args, **kwargs)
    return wrapper

And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:

def foo(a, b, c, d=0, e=100):

def bar(a, b, c=None, d=0, e=100, f=None):

def baz(a, b, c=None, d=0, e=100, f=None, g=None):
    differentiating_process_baz(a,b,c,d,e,f, g)

def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):

And by factoring out our code, which *args and **kwargs allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.

How do you set up use HttpOnly cookies in PHP

Note that PHP session cookies don't use httponly by default.

To do that:

$sess_name = session_name();
if (session_start()) {
    setcookie($sess_name, session_id(), null, '/', null, null, true);

A couple of items of note here:

  • You have to call session_name() before session_start()
  • This also sets the default path to '/', which is necessary for Opera but which PHP session cookies don't do by default either.

Should a function have only one return statement?

Nobody has mentioned or quoted Code Complete so I'll do it.

17.1 return

Minimize the number of returns in each routine. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.

Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn't require any cleanup, not returning immediately means that you have to write more code.

Struct like objects in Java

You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class. There is no way to genuinely reproduce structs in Java.

What is a 'Closure'?

Please have a look below code to understand closure in more deep:

        for(var i=0; i< 5; i++){            
            }, 1000);                        

Here what will be output? 0,1,2,3,4 not that will be 5,5,5,5,5 because of closure

So how it will solve? Answer is below:

       for(var i=0; i< 5; i++){
           (function(j){     //using IIFE           

Let me simple explain, when a function created nothing happen until it called so for loop in 1st code called 5 times but not called immediately so when it called i.e after 1 second and also this is asynchronous so before this for loop finished and store value 5 in var i and finally execute setTimeout function five time and print 5,5,5,5,5

Here how it solve using IIFE i.e Immediate Invoking Function Expression

       (function(j){  //i is passed here           
        })(i);  //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4

For more, please understand execution context to understand closure.

  • There is one more solution to solve this using let (ES6 feature) but under the hood above function is worked

     for(let i=0; i< 5; i++){           
    Output: 0,1,2,3,4

=> More explanation:

In memory, when for loop execute picture make like below:

Loop 1)


Loop 2)


Loop 3)


Loop 4)


Loop 5)


Here i is not executed and then after complete loop, var i stored value 5 in memory but it's scope is always visible in it's children function so when function execute inside setTimeout out five time it prints 5,5,5,5,5

so to resolve this use IIFE as explain above.

Why functional languages?

There's a great article from Slava Akhmechet called Functional Programming For The Rest of Us (this was the article that got me into FP btw). Amongst the benefits FP brings, he unorthodoxly emphasizes the following (which I believe contributes to the appeal for software engineers):

  • Unit Testing
  • Debugging
  • Concurrency
  • Hot Code Deployment
  • Machine Assisted Proofs and Optimizations

And then goes on to discuss the goodness of more traditionally discussed aspects of FP like higher order functions, currying, lazy evaluation, optimization, abstracting control structures (although not discussing monads), infinite data structures, strictness, continuations, pattern matching, closures and so on.

Highly recommended !

How to pass a single object[] to a params object[]

The params parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params parameter:

1) Calling with an array of the parameter type, in which case the params keyword has no effect and the array is passed directly to the method:

object[] array = new[] { "1", "2" };

// Foo receives the 'array' argument directly.
Foo( array );

2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:

// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );

// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );

In order to pass in an object array to a method with a "params object[]" parameter, you can either:

1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:

Foo( new object[] { array } );  // Equivalent to calling convention 1.

2) Or, cast the argument to object, as mentioned by Adam, in which case the compiler will create the wrapper array for you:

Foo( (object)array );  // Equivalent to calling convention 2.

However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]" parameter. This would allow you to pass multiple arrays as arguments:

void Foo( params object[][] arrays ) {
  foreach( object[] array in arrays ) {
    // process array

Foo( new[] { "1", "2" }, new[] { "3", "4" } );

// Equivalent to:
object[][] arrays = new[] {
  new[] { "1", "2" },
  new[] { "3", "4" }
Foo( arrays );

Edit: Raymond Chen describes this behavior and how it relates to the C# specification in a new post.

What is 'Currying'?

It can be a way to use functions to make other functions.

In javascript:

let add = function(x){
  return function(y){ 
   return x + y

Would allow us to call it like so:

let addTen = add(10);

When this runs the 10 is passed in as x;

let add = function(10){
  return function(y){
    return 10 + y 

which means we are returned this function:

function(y) { return 10 + y };

So when you call


you are really calling:

 function(y) { return 10 + y };

So if you do this:


it's the same as:

function(4) { return 10 + 4} // 14

So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:

let addTwo = add(2)       // addTwo(); will add two to whatever you pass in
let addSeventy = add(70)  // ... and so on...

Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things 1. cache expensive operations 2. achieve abstractions in the functional paradigm.

Imagine our curried function looked like this:

let doTheHardStuff = function(x) {
  let z = doSomethingComputationallyExpensive(x)
  return function (y){
    z + y

We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

let finishTheJob = doTheHardStuff(10)

We can get abstractions in a similar way.

How to sort a list of strings?

It is simple:

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

scores = scores.split(',') for x in sorted(scores): print(x)

How to get controls in WPF to fill available space?

Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():

  • Measure() determines the size of the panel and each of its children
  • Arrange() determines the rectangle where each control renders

The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.

The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.

A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.

You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().

See this article for a simple example.

How do I execute a file in Cygwin?

When you start in Cygwin you are in the "/home/Administrator" zone, so put your a.exe file there.

Then at the prompt run:

cd a.exe

It will be read in by Cygwin and you will be asked to install it.

C-like structures in Python

How about a dictionary?

Something like this:

myStruct = {'field1': 'some val', 'field2': 'some val'}

Then you can use this to manipulate values:

print myStruct['field1']
myStruct['field2'] = 'some other values'

And the values don't have to be strings. They can be pretty much any other object.

Rolling back bad changes with svn in Eclipse

If you want to do 1 file at a time you can go to the History view for the file assuming you have an Eclipse SVN plugin installed. "Team->Show History"

In the History view, find the last good version of that file, right click and choose "Get Contents". This will replace your current version with that version's contents. Then you can commit the changes when you've fixed it all up.

Base64 Encoding Image

Check the following example:

// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'

How can a Java program get its own process ID?

I found a solution that may be a bit of an edge case and I didn't try it on other OS than Windows 10, but I think it's worth noticing.

If you find yourself working with J2V8 and nodejs, you can run a simple javascript function returning you the pid of the java process.

Here is an example:

public static void main(String[] args) {
    NodeJS nodeJS = NodeJS.createNodeJS();
    int pid = nodeJS.getRuntime().executeIntegerScript(";\n");

What is the Difference Between Mercurial and Git?

Sometime last year I evaluated both git and hg for my own use, and decided to go with hg. I felt it looked like a cleaner solution, and worked better on more platforms at the time. It was mostly a toss-up, though.

More recently, I started using git because of git-svn and the ability to act as a Subversion client. This won me over and I've now switched completely to git. I think it's got a slightly higher learning curve (especially if you need to poke around the insides), but it really is a great system. I'm going to go read those two comparison articles that John posted now.

XML serialization in Java?

Worth mentioning that since version 1.4, Java had the classes java.beans.XMLEncoder and java.beans.XMLDecoder. These classes perform XML encoding which is at least very comparable to XML Serialization and in some circumstances might do the trick for you.

If your class sticks to the JavaBeans specification for its getters and setters, this method is straightforward to use and you don't need a schema. With the following caveats:

  • As with normal Java serialization
    • coding and decoding run over a InputStream and OutputStream
    • the process uses the familar writeObject and readObject methods
  • In contrast to normal Java serialization
    • the encoding but also decoding causes constructors and initializers to be invoked
    • encoding and decoding work regardless if your class implements Serializable or not
    • transient modifiers are not taken into account
    • works only for public classes, that have public constructors

For example, take the following declaration:

public class NPair {
  public NPair() { }
  int number1 = 0;
  int number2 = 0;
  public void setNumber1(int value) { number1 = value;}
  public int getNumber1() { return number1; }
  public void setNumber2(int value) { number2 = value; }
  public int getNumber2() {return number2;}

Executing this code:

NPair fe = new NPair();
FileOutputStream fos1 = new FileOutputStream("d:\\ser.xml");
java.beans.XMLEncoder xe1 = new java.beans.XMLEncoder(fos1);

Would result in the following file:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_02" class="java.beans.XMLDecoder">
 <object class="NPair">
  <void property="number1">
  <void property="number2">

Internet Access in Ubuntu on VirtualBox

I had the same problem.

Solved by sharing internet connection (on the hosting OS).

Network Connection Properties -> advanced -> Allow other users to connect...

What are the main performance differences between varchar and nvarchar SQL Server data types?

Generally speaking; Start out with the most expensive datatype that has the least constraints. Put it in production. If performance starts to be an issue, find out what's actually being stored in those nvarchar columns. Is there any characters in there that wouldn't fit into varchar? If not, switch to varchar. Don't try to pre-optimize before you know where the pain is. My guess is that the choice between nvarchar/varchar is not what's going to slow down your application in the foreseable future. There will be other parts of the application where performance tuning will give you much more bang for the bucks.

What is the difference between the | and || or operators?

Just like the & and && operator, the double Operator is a "short-circuit" operator.

For example:

if(condition1 || condition2 || condition3)

If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition2 | condition3)

This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.

There is one big caveat, NullReferences or similar problems. For example:

if(class != null && class.someVar < 20)

If class is null, the if-statement will stop after class != null is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.

No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions, and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.

There is a Second use of the | and & operator though: Bitwise Operations.

How do I fix a NoSuchMethodError?

I have just solved this error by restarting my Eclipse and run the applcation. The reason for my case may because I replace my source files without closing my project or Eclipse. Which caused different version of classes I was using.

How to declare an array of strings in C++?

You can use Will Dean's suggestion [#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.

The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[]) is really some_function(string *parameter).

How do you create optional arguments in php?

Give the optional argument a default value.

function date ($format, $timestamp='') {

How do I list the symbols in a .so file

For shared libraries the -D switch was necessary to see symbols in my Linux

nm -D

and for static library as reported by others

nm -g libNAME.a

Subversion ignoring "--password" and "--username" options

Best I can give you is a "works for me" on SVN 1.5. You may try adding --no-auth-cache to your svn update to see if that lets you override more easily.

If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.

What is a good Hash Function?

For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.

If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.


Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

How do I test a private function or a class that has private methods, fields or inner classes?

You can turn off Java access restrictions for reflection so that private means nothing.

The setAccessible(true) call does that.

The only restriction is that a ClassLoader may disallow you from doing that.

See Subverting Java Access Protection for Unit Testing (Ross Burton) for a way to do this in Java.

What is a mutex?

What is a Mutex?

The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.

What is a Race Condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Real life example:

When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.

Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.


Usage in C#:

This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.

using System;
using System.Threading;

class Example
    // Create a new Mutex. The creating thread does not own the mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
            Thread newThread = new Thread(new ThreadStart(ThreadProc));
            newThread.Name = String.Format("Thread{0}", i + 1);

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.

    private static void ThreadProc()
        for(int i = 0; i < numIterations; i++)

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
        // Wait until it is safe to enter.
        Console.WriteLine("{0} is requesting the mutex", 

        Console.WriteLine("{0} has entered the protected area", 

        // Place code to access non-reentrant resources here.

        // Simulate some work.

        Console.WriteLine("{0} is leaving the protected area", 

        // Release the Mutex.
        Console.WriteLine("{0} has released the mutex", 
// The example displays output like the following:
//       Thread1 is requesting the mutex
//       Thread2 is requesting the mutex
//       Thread1 has entered the protected area
//       Thread3 is requesting the mutex
//       Thread1 is leaving the protected area
//       Thread1 has released the mutex
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
//       Thread3 has released the mutex
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       Thread2 has released the mutex

MSDN Reference Mutex

What is a semaphore?

There are two essential concepts to building concurrent programs - synchronization and mutual exclusion. We will see how these two types of locks (semaphores are more generally a kind of locking mechanism) help us achieve synchronization and mutual exclusion.

A semaphore is a programming construct that helps us achieve concurrency, by implementing both synchronization and mutual exclusion. Semaphores are of two types, Binary and Counting.

A semaphore has two parts : a counter, and a list of tasks waiting to access a particular resource. A semaphore performs two operations : wait (P) [this is like acquiring a lock], and release (V)[ similar to releasing a lock] - these are the only two operations that one can perform on a semaphore. In a binary semaphore, the counter logically goes between 0 and 1. You can think of it as being similar to a lock with two values : open/closed. A counting semaphore has multiple values for count.

What is important to understand is that the semaphore counter keeps track of the number of tasks that do not have to block, i.e., they can make progress. Tasks block, and add themselves to the semaphore's list only when the counter is zero. Therefore, a task gets added to the list in the P() routine if it cannot progress, and "freed" using the V() routine.

Now, it is fairly obvious to see how binary semaphores can be used to solve synchronization and mutual exclusion - they are essentially locks.

ex. Synchronization:

thread A{
semaphore &s; //locks/semaphores are passed by reference! think about why this is so.
A(semaphore &s): s(s){} //constructor
;// some block of code B2

//thread B{
semaphore &s;
B(semaphore &s): s(s){} //constructor
// some block of code B1

semaphore s(0); // we start the semaphore at 0 (closed)
A a(s);
B b(s);

In the above example, B2 can only execute after B1 has finished execution. Let's say thread A comes executes first - gets to sem.P(), and waits, since the counter is 0 (closed). Thread B comes along, finishes B1, and then frees thread A - which then completes B2. So we achieve synchronization.

Now let's look at mutual exclusion with a binary semaphore:

thread mutual_ex{
semaphore &s;
mutual_ex(semaphore &s): s(s){} //constructor
//critical section
//critical section


semaphore s(1);
mutual_ex m1(s);
mutual_ex m2(s);

The mutual exclusion is quite simple as well - m1 and m2 cannot enter the critical section at the same time. So each thread is using the same semaphore to provide mutual exclusion for its two critical sections. Now, is it possible to have greater concurrency? Depends on the critical sections. (Think about how else one could use semaphores to achieve mutual exclusion.. hint hint : do i necessarily only need to use one semaphore?)

Counting semaphore: A semaphore with more than one value. Let's look at what this is implying - a lock with more than one value?? So open, closed, and ...hmm. Of what use is a multi-stage-lock in mutual exclusion or synchronization?

Let's take the easier of the two:

Synchronization using a counting semaphore: Let's say you have 3 tasks - #1 and 2 you want executed after 3. How would you design your synchronization?

thread t1{
//block of code B1

thread t2{
//block of code B2

thread t3{
//block of code B3

So if your semaphore starts off closed, you ensure that t1 and t2 block, get added to the semaphore's list. Then along comes all important t3, finishes its business and frees t1 and t2. What order are they freed in? Depends on the implementation of the semaphore's list. Could be FIFO, could be based some particular priority,etc. (Note : think about how you would arrange your P's and V;s if you wanted t1 and t2 to be executed in some particular order, and if you weren't aware of the implementation of the semaphore)

(Find out : What happens if the number of V's is greater than the number of P's?)

Mutual Exclusion Using counting semaphores: I'd like you to construct your own pseudocode for this (makes you understand things better!) - but the fundamental concept is this : a counting semaphore of counter = N allows N tasks to enter the critical section freely. What this means is you have N tasks (or threads, if you like) enter the critical section, but the N+1th task gets blocked (goes on our favorite blocked-task list), and only is let through when somebody V's the semaphore at least once. So the semaphore counter, instead of swinging between 0 and 1, now goes between 0 and N, allowing N tasks to freely enter and exit, blocking nobody!

Now gosh, why would you need such a stupid thing? Isn't the whole point of mutual exclusion to not let more than one guy access a resource?? (Hint Hint...You don't always only have one drive in your computer, do you...?)

To think about : Is mutual exclusion achieved by having a counting semaphore alone? What if you have 10 instances of a resource, and 10 threads come in (through the counting semaphore) and try to use the first instance?

What is a deadlock?

Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.

Ways to avoid having deadlocks are:

  • avoid having locks (if possible),
  • avoid having more than one lock
  • always take the locks in the same order.

What is a race condition?

What is a Race Condition?

You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That's a race condition - specifically a "check-then-act" scenario of race conditions.

How do you detect them?

Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.

How do you handle and prevent them?

The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.

The best resource for concurrency is JCIP. You can also get some more details on above explanation here.

Finding what methods a Python object has

The simplest method is to use dir(objectname). It will display all the methods available for that object. Cool trick.

Why am I getting a NoClassDefFoundError in Java?

This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

and here how to write files:

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

i added this just to provide some more information.

How to read a value from the Windows registry

const CString REG_SW_GROUP_I_WANT = _T("SOFTWARE\\My Corporation\\My Package\\Group I want");
const CString REG_KEY_I_WANT= _T("Key Name");

CRegKey regKey;
DWORD   dwValue = 0;

  m_pobLogger->LogError(_T("CRegKey::Open failed in Method"));
  goto Function_Exit;
if( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT))
  m_pobLogger->LogError(_T("CRegKey::QueryValue Failed in Method"));
  goto Function_Exit;

// dwValue has the stuff now - use for further processing

Find out how much memory is being used by an object in Python

Try this:


getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

What is tail recursion?

In Java, here's a possible tail recursive implementation of the Fibonacci function:

public int tailRecursive(final int n) {
    if (n <= 2)
        return 1;
    return tailRecursiveAux(n, 1, 1);

private int tailRecursiveAux(int n, int iter, int acc) {
    if (iter == n)
        return acc;
    return tailRecursiveAux(n, ++iter, acc + iter);

Contrast this with the standard recursive implementation:

public int recursive(final int n) {
    if (n <= 2)
        return 1;
    return recursive(n - 1) + recursive(n - 2);

Any way to write a Windows .bat file to kill processes?

Please find the below logic where it works on the condition.

If we simply call taskkill /im applicationname.exe, it will kill only if this process is running. If this process is not running, it will throw an error.

So as to check before takskill is called, a check can be done to make sure execute taskkill will be executed only if the process is running, so that it won't throw error.

tasklist /fi "imagename eq applicationname.exe" |find ":" > nul

if errorlevel 1 taskkill /f /im "applicationname.exe"

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.


A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.


As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:

<httpCookies httpOnlyCookies="true"/>

How do you configure HttpOnly cookies in tomcat / java webapps?

httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.

See the changelog entry for bug 44382.

The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.

The httpOnly functionality can be enabled for all webapps in conf/context.xml:

<Context useHttpOnly="true">

My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).

How do I check if a SQL Server text column is empty?

Use the IS NULL operator:

Select * from tb_Employee where ename is null

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();

Setting the height of a DIV dynamically

What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:

div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;

This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.

Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?

SVN repository backup strategies

Basically it's safe to copy the repository folder if the svn server is stopped. (source:!topic/visualsvn/i_55khUBrys%5B1-25%5D )

So if you're allowed to stop the server, do it and just copy the repository, either with some script or a backup tool. Cobian Backup fits here nicely as it can stop and start services automatically, and it can do incremental backups so you're only backing up parts of repository that have changed recently (useful if the repository is large and you're backing up to remote location).


  1. Install Cobian Backup
  2. Add a backup task:

    • Set source to repository folder (e.g. C:\Repositories\),

    • Add pre-backup event "STOP_SERVICE" VisualSVN,

    • Add post-backup event, "START_SERVICE" VisualSVN,

    • Set other options as needed. We've set up incremental backups including removal of old ones, backup schedule, destination, compression incl. archive splitting etc.

  3. Profit!

How do you generate dynamic (parameterized) unit tests in Python?

The metaclass-based answers still work in Python 3, but instead of the __metaclass__ attribute, one has to use the metaclass parameter, as in:

class ExampleTestCase(TestCase,metaclass=DocTestMeta):

How do I get today's date in C# in mm/dd/yyyy format?

Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:-

using System.Globalization;
using System.Threading;


var currentCulture = Thread.CurrentThread.CurrentCulture;
try {
  Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us");
  string shortDateString = DateTime.Now.ToShortDateString();
  // Do something with shortDateString...
} finally {
  Thread.CurrentThread.CurrentCulture = currentCulture;

Though clearly the "m/dd/yyyy" approach is considerably neater!!

Is there a constraint that restricts my generic method to numeric types?

I had a similar situation where I needed to handle numeric types and strings; seems a bit of a bizarre mix but there you go.

Again, like many people I looked at constraints and came up with a bunch of interfaces that it had to support. However, a) it wasn't 100% watertight and b), anyone new looking at this long list of constraints would be immediately very confused.

So, my approach was to put all my logic into a generic method with no constraints, but to make that generic method private. I then exposed it with public methods, one explicitly handling the type I wanted to handle - to my mind, the code is clean and explicit, e.g.

public static string DoSomething(this int input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this decimal input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this double input, ...) => DoSomethingHelper(input, ...);
public static string DoSomething(this string input, ...) => DoSomethingHelper(input, ...);

private static string DoSomethingHelper<T>(this T input, ....)
    // complex logic

Creating a LINQ select from multiple tables


select op) 


select new { op, pg })

How can I force clients to refresh JavaScript files?

How about adding the filesize as a load parameter?

<script type='text/javascript' src='path/to/file/mylibrary.js?filever=<?=filesize('path/to/file/mylibrary.js')?>'></script>

So every time you update the file the "filever" parameter changes.

How about when you update the file and your update results in the same file size? what are the odds?

How do you run a Python script as a service in Windows?

This answer is plagiarizer from several sources on StackOverflow - most of them above, but I've forgotten the others - sorry. It's simple and scripts run "as is". For releases you test you script, then copy it to the server and Stop/Start the associated service. And it should work for all scripting languages (Python, Perl, node.js), plus batch scripts such as GitBash, PowerShell, even old DOS bat scripts. pyGlue is the glue that sits between Windows Services and your script.

A script to create a Windows Service, which, when started, will run an executable with the specified parameters.
Optionally, you can also specify a startup directory

To use this script you MUST define (in class Service)
1. A name for your service (short - preferably no spaces)
2. A display name for your service (the name visibile in Windows Services)
3. A description for your service (long details visible when you inspect the service in Windows Services)
4. The full path of the executable (usually C:/Python38/python.exe or C:WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe
5. The script which Python or PowerShell will run(or specify None if your executable is standalone - in which case you don't need pyGlue)
6. The startup directory (or specify None)
7. Any parameters for your script (or for your executable if you have no script)

NOTE: This does not make a portable script.
The associated '_svc_name.exe' in the dist folder will only work if the executable,
(and any optional startup directory) actually exist in those locations on the target system

Usage: 'pyGlue.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
Options for 'install' and 'update' commands only:
        --username domain\\username : The Username the service is to run under
        --password password : The password for the username
        --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
        --interactive : Allow the service to interact with the desktop.
        --perfmonini file: .ini file to use for registering performance monitor data
        --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll
Options for 'start' and 'stop' commands only:
        --wait seconds: Wait for the service to actually start or stop.
                If you specify --wait with the 'stop' option, the service and all dependent services will be stopped,
                each waiting the specified period.

# Import all the modules that make life easy
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
import win32evtlogutil
import os
from logging import Formatter, Handler
import logging
import subprocess

# Define the win32api class
class Service (win32serviceutil.ServiceFramework):
        # The following variable are edited by the script
        _svc_name_ = "TestService"
        _svc_display_name_ = "Test Service"
        _svc_description_ = "Test Running Python Scripts as a Service"
        service_exe = 'c:/Python27/python.exe'
        service_script = None
        service_params = []
        service_startDir = None

        # Initialize the service
        def __init__(self, args):
                win32serviceutil.ServiceFramework.__init__(self, args)
                self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

        # Configure logging to the WINDOWS Event logs
        def configure_logging(self):
                self.formatter = Formatter('%(message)s')
                self.handler = logHandler()
                self.logger = logging.getLogger()

        # Stop the service
        def SvcStop(self):

        # Run the service
        def SvcDoRun(self):

        # This is the service
        def main(self):

                # Log that we are starting
                servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
                                                          (self._svc_name_, ''))

                # Fire off the real process that does the real work
      '%s - about to call Popen() to run %s %s %s', self._svc_name_, self.service_exe, self.service_script, self.service_params)
                self.process = subprocess.Popen([self.service_exe, self.service_script] + self.service_params, shell=False, cwd=self.service_startDir)
      '%s - started process %d', self._svc_name_,

                # Wait until WINDOWS kills us - retrigger the wait for stop every 60 seconds
                rc = None
                while rc != win32event.WAIT_OBJECT_0:
                        rc = win32event.WaitForSingleObject(self.hWaitStop, (1 * 60 * 1000))

                # Shut down the real process and exit
      '%s - is terminating process %d', self._svc_name_,
      '%s - is exiting', self._svc_name_)

class logHandler(Handler):
Emit a log record to the WINDOWS Event log

        def emit(self, record):

# The main code
if __name__ == '__main__':
Create a Windows Service, which, when started, will run an executable with the specified parameters.

        # Check that configuration contains valid values just in case this service has accidentally
        # been moved to a server where things are in different places
        if not os.path.isfile(Service.service_exe):
                print('Executable file({!s}) does not exist'.format(Service.service_exe), file=sys.stderr)
        if not os.access(Service.service_exe, os.X_OK):
                print('Executable file({!s}) is not executable'.format(Service.service_exe), file=sys.stderr)
        # Check that any optional startup directory exists
        if (Service.service_startDir is not None) and (not os.path.isdir(Service.service_startDir)):
                print('Start up directory({!s}) does not exist'.format(Service.service_startDir), file=sys.stderr)

        if len(sys.argv) == 1:
                # install/update/remove/start/stop/restart or debug the service
                # One of those command line options must be specified

Now there's a bit of editing and you don't want all your services called 'pyGlue'. So there's a script ( to plug in the bits and create a customized 'pyGlue' and create an '.exe'. It is this '.exe' which gets installed as a Windows Service. Once installed you can set it to run automatically.

# This script build a Windows Service that will install/start/stop/remove a service that runs a script
# That is, executes Python to run a Python script, or PowerShell to run a PowerShell script, etc

if [ $# -lt 6 ]; then
        echo "Usage: Name Display Description Executable Script StartupDir [Params]..."
        exit 0

shift; shift; shift; shift; shift; shift
while [ $# -gt 0 ]; do
        if [ "${params}" != "" ]; then
                params="${params}, "

cat | sed -e "s/pyGlue/${name}/g" | \
        sed -e "/_svc_name_ =/s?=.*?= '${name}'?" | \
        sed -e "/_svc_display_name_ =/s?=.*?= '${display}'?" | \
        sed -e "/_svc_description_ =/s?=.*?= '${desc}'?" | \
        sed -e "/service_exe =/s?=.*?= '$exe'?" | \
        sed -e "/service_script =/s?=.*?= '$script'?" | \
        sed -e "/service_params =/s?=.*?= [${params}]?" | \
        sed -e "/service_startDir =/s?=.*?= '${startDir}'?" > ${name}.py

cxfreeze ${name}.py --include-modules=win32timezone

Installation - copy the '.exe' the server and the script to the specified folder. Run the '.exe', as Administrator, with the 'install' option. Open Windows Services, as Adminstrator, and start you service. For upgrade, just copy the new version of the script and Stop/Start the service.

Now every server is different - different installations of Python, different folder structures. I maintain a folder for every server, with a copy of and And I create a '' script for rebuilding all the service on that server.

# A script to build all the script based Services on this PC
sh AutoCode 'AutoCode Medical Documents' 'Autocode Medical Documents to SNOMED_CT and AIHW codes' C:/Python38/python.exe C:/Users/russell/Documents/autocoding -S -T

Disable browser 'Save Password' functionality

I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form.

<form id="loginForm" action="login.cgi" method="post" autocomplete="off">

The easiest and simplest way to disable Form and Password storage prompts and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off".


Some minor research shows that this works in IE to but I'll leave no guarantees ;)

@Joseph: If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved.

Example with jQuery:

$('#loginForm').attr('autocomplete', 'off');

Sending email in .NET through Gmail

Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:

"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"

Or possibly this

Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."

What is the simplest SQL Query to find the second largest value?


  FROM [Users]
    order by UserId desc OFFSET 1 ROW 


  FROM Users
    order by UserId desc LIMIT 1 OFFSET 1

No need of sub queries ... just skip one row and select second rows after order by descending

UDP vs TCP, how much faster is it?

There has been some work done to allow the programmer to have the benefits of both worlds.


It is an independent transport layer protolol, but it can be used as a library providing additional layer over UDP. The basic unit of communication is a message (mapped to one or more UDP packets). There is congestion control built in. The protocol has knobs and twiddles to switch on

  • in order delivery of messages
  • automatic retransmission of lost messages, with user defined parameters

if any of this is needed for your particular application.

One issue with this is that the connection establishment is a complicated (and therefore slow process)

Other similar stuff

One more similar proprietary experimental thing

This also tries to improve on the triple way handshake of TCP and change the congestion control to better deal with fast lines.

What is a magic number, and why is it bad?

What about initializing a variable at the top of the class with a default value? For example:

public class SomeClass {
    private int maxRows = 15000;
    // Inside another method
    for (int i = 0; i < maxRows; i++) {
        // Do something

    public void setMaxRows(int maxRows) {
        this.maxRows = maxRows;

    public int getMaxRows() {
        return this.maxRows;

In this case, 15000 is a magic number (according to CheckStyles). To me, setting a default value is okay. I don't want to have to do:

private static final int DEFAULT_MAX_ROWS = 15000;
private int maxRows = DEFAULT_MAX_ROWS;

Does that make it more difficult to read? I never considered this until I installed CheckStyles.

How do you remove all the options of a select box and then add one option and select it with jQuery?

I saw this code in Select2 - Clearing Selections


This code works well with jQuery even without Select2

Generator expressions vs. list comprehensions

Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.

Remove duplicates from a List<T> in C#

If you're using .Net 3+, you can use Linq.

List<T> withDupes = LoadSomeData();
List<T> noDupes = withDupes.Distinct().ToList();

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

How do I monitor the computer's CPU, memory, and disk usage in Java?

Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"

You can use the class MProcess,

 *Md. Mukit Hasan

public class MProcessor {

public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }


Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.

--Mukit Hasan

Best way in to force https for an entire site?

The IIS7 module will let you redirect.

            <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
                <match url="(.*)"/>
                    <add input="{HTTPS}" pattern="^OFF$"/>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>