Two Pots, One Treasure Problem

On the right, you see a silver and a golden pot. One of these pots contains a treasure and the other one is empty. Assume that you can determine from the text prints which pot contains the treasure.
The text prints on the pots are:
The silver pot: “This pot is empty.”
The golden pot: “Exactly one of these texts is true.”

Which pot contains the treasure?

Posted in Cool Problems | 1 Comment

Rich, Poor, Eating Problem

The poor have it,
the rich want it,
but if you eat it you will die.

What is this?

Posted in Cool Problems | 1 Comment

Marble Weighing Problem

In front of you are 10 bags, filled with marbles. The number of marbles in each bag differs, but all bags contain ten marbles or more. Nine of the ten bags only contain marbles of 10 grams each. One bag only contains marbles of 9 grams. In addition, you have a balance which can weigh in grams accurate, and you are allowed to use it only once (i.e. weigh a single time).

How can you find out in one weighing, which bag contains the marbles of 9 grams?

Posted in Cool Problems | 1 Comment

Camel Racing Problem

A long, long time ago, two Egyptian camel drivers were fighting for the hand of the daughter of the sheik of Abbudzjabbu. The sheik, who liked neither of these men to become the future husband of his daughter, came up with a clever plan: a race would determine who of the two men would be allowed to marry his daughter. And so the sheik organized a camel race. Both camel drivers had to travel from Cairo to Abbudzjabbu, and the one whose camel would arrive last in Abbudzjabbu, would be allowed to marry the sheik’s daughter.
The two camel drivers, realizing that this could become a rather lengthy expedition, finally decided to consult the Wise Man of their village. Arrived there, they explained him the situation, upon which the Wise Man raised his cane and spoke four wise words. Relieved, the two camel drivers left his tent: they were ready for the contest!

Which 4 wise words did the Wise Man speak?

Posted in Cool Problems | 1 Comment

Death Sentence Problem

General Gasslefield, accused of high treason, is sentenced to death by the court-martial. He is allowed to make a final statement, after which he will be shot if the statement is false or will be hung if the statement is true. Gasslefield makes his final statement and is released.

What could he have said?

Posted in Cool Problems | 1 Comment

Bridge Crossing Problem

Four men want to cross a bridge. They all begin on the same side. It is night, and they have only one flashlight with them. At most two men can cross the bridge at a time, and any party who crosses, either one or two people, must have the flashlight with them.
The flashlight must be walked back and forth: it cannot be thrown, etc. Each man walks at a different speed. A pair must walk together at the speed of the slower man. Man 1 needs 1 minute to cross the bridge, man 2 needs 2 minutes, man 3 needs 5 minutes, and man 4 needs 10 minutes. For example, if man 1 and man 3 walk across together, they need 5 minutes.

How can all four men cross the bridge in 17 minutes?

Posted in Cool Problems | 1 Comment

Pirate Ship Treasure Splitting

A pirate ship captures a treasure of 1000 golden coins. The treasure has to be split among the 5 pirates: 1, 2, 3, 4, and 5 in order of rank. The pirates have the following important characteristics:

* Infinitely smart.
* Bloodthirsty.
* Greedy.

Starting with pirate 5 they can make a proposal how to split up the treasure. This proposal can either be accepted or the pirate is thrown overboard. A proposal is accepted if and only if a majority of the pirates agrees on it.

What proposal should pirate 5 make?

Posted in Cool Problems | 1 Comment

Colorful Dwarf Party

In a distant, dark forest, lives a population of 400 highly intelligent dwarfs. The dwarfs all look exactly alike, but only differ in the fact that they are wearing either a red or a blue hat. There are 250 dwarfs with a red hat and 150 dwarfs with a blue hat. Striking however, is that the dwarfs don’t know these numbers themselves and that none of them knows what the colour of his hat is (there are for example no mirrors in this forest). But the dwarfs do know that there is at least one dwarf with a red hat.

During a certain period of their year, there is a big party in this village, to which initially all dwarfs will go. However, this party is only intended for dwarfs wearing a blue hat. Dwarfs with a red hat are supposed never to return to the party again, as soon as they know that they are wearing a red hat.

How many days does it take before there are no more dwarfs with a red hat left at the party?

Posted in Cool Problems | 1 Comment

Prisoner Hats, 3 Heads, 5 Hats

In a small village in the middle of nowhere, three innocent prisoners are sitting in a jail. One day, the cruel jailer takes them out and places them in a line on three chairs, in such a way that man C can see both man A and man B, man B can see only man A, and man A can see none of the other men. The jailer shows them 5 hats, 2 of which are black and 3 of which are white. After this, he blindfolds the men, places one hat on each of their heads, and removes the blindfolds again. The jailer tells his three prisoners that if one of them is able to determine the color of his hat within one minute, all of them are released. Otherwise, they will all be executed. None of the prisoners can see his own hat, and all are intelligent. After 59 seconds, man A shouts out the (correct) color of his hat!

What is the color of man A’s hat, and how does he know?

Posted in Cool Problems | 1 Comment

MySQL Best Data Types For Common Types Of Data

Primary Key : INT UNSIGNED

- About 4.3 billion available IDs. Going unsigned gives you the extra 2 billion.

Phone Number : VARCHAR

- Phone numbers are identifiers that happen to use digits.
- See this post.

Price : FLOAT

- FLOATs will be calculated natively by the CPU rather than by the server.

Posted in MySQL | Leave a comment

Starvation vs. Synchronize vs. Deadlock

Starvation

In computer science, starvation is a multitasking-related problem, where a process is perpetually denied necessary resources. Without those resources, the program can never finish its task.

Starvation is similar in effect to deadlock. Two or more programs become deadlocked together, when each of them wait for a resource occupied by another program in the same set. On the other hand, one or more programs are in starvation, when each of them is waiting for resources that are occupied by programs, that may or may not be in the same set that are starving. Moreover, in a deadlock, no program in the set changes its state. There may be a similar situation called livelock, where the processes changes their states continually, but cannot progress. Livelock is a special case of starvation. In that sense, deadlock can also be said a special case of starvation. Usually the problems in which programs are perpetually deprived of resources are referred as deadlock problems when none of them are changing their states and each of them is waiting for resources only occupied by programs in the same set. All other such problems are referred to as starvation.

Synchronization

In computer science, synchronization refers to one of two distinct but related concepts: synchronization of processes, and synchronization of data. Process synchronization refers to the idea that multiple processes are to join up or handshake at a certain point, so as to reach an agreement or commit to a certain sequence of action. Data synchronization refers to the idea of keeping multiple copies of a dataset in coherence with one another, or to maintain data integrity. Process synchronization primitives are commonly used to implement data synchronization.

Deadlock

A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like the “chicken or the egg.”

“When two trains approach each other at a crossing, both shall come to a full stop and neither shall start up again until the other has gone.”

— Illogical statute passed by the Kansas Legislature[1]

In computer science, Coffman deadlock refers to a specific condition when two or more processes are each waiting for each other to release a resource, or more than two processes are waiting for resources in a circular chain (see Necessary conditions). Deadlock is a common problem in multiprocessing where many processes share a specific type of mutually exclusive resource known as a software lock or soft lock. Computers intended for the time-sharing and/or real-time markets are often equipped with a hardware lock (or hard lock) which guarantees exclusive access to processes, forcing serialized access. Deadlocks are particularly troubling because there is no general solution to avoid (soft) deadlocks.

This situation may be likened to two people who are drawing diagrams, with only one pencil and one ruler between them. If one person takes the pencil and the other takes the ruler, a deadlock occurs when the person with the pencil needs the ruler and the person with the ruler needs the pencil to finish his work with the ruler. Both requests can’t be satisfied, so a deadlock occurs.

The telecommunications description of deadlock is weaker than Coffman deadlock because processes can wait for messages instead of resources. Deadlock can be the result of corrupted messages or signals rather than merely waiting for resources. For example, a dataflow element that has been directed to receive input on the wrong link will never proceed even though that link is not involved in a Coffman cycle.

Source: Wikipedia

Posted in Lingo | Leave a comment

Threads vs. Processes

Threads vs. Processes

Processes

Both threads and processes are methods of parallelizing an application. However, processes are independent execution units that contain their own state information, use their own address spaces, and only interact with each other via interprocess communication mechanisms (generally managed by the operating system). Applications are typically divided into processes during the design phase, and a master process explicitly spawns sub-processes when it makes sense to logically separate significant application functionality. Processes, in other words, are an architectural construct.

Threads

By contrast, a thread is a coding construct that doesn’t affect the architecture of an application. A single process might contains multiple threads; all threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables.

Threads typically are spawned for a short-term benefit that is usually visualized as a serial task, but which doesn’t have to be performed in a linear manner (such as performing a complex mathematical computation using parallelism, or initializing a large matrix), and then are absorbed when no longer required. The scope of a thread is within a specific code module—which is why we can bolt-on threading without affecting the broader application.

Source: Alan Zeichick

Posted in Lingo | Leave a comment

Mutex vs. Semaphore, what is the difference?

Mutex vs. Semaphore, what is the difference?

The Toilet Example

Mutex

Is a key to a toilet. One person can have the key – occupy the toilet – at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: “Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section.”
Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count – the count of keys – is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: “A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).”

Ref: Symbian Developer Library

Source: Niclas Winquist

Posted in Lingo | Leave a comment

Linux Screen Basics

CTRL-A : screen command mode

CTRL-A ” ” : show list

CTRL-A SHIFT-A : rename this screen session

CTRL-A n : next screen

CTRL-A p : previous screen

CTRL-A M : monitor for activity

CTRL-A _ : monitor for silence

CTRL-A H : keep a running log

$ screen -ls : list screen sessions (useful if more than one session)

$ screen -r : reattach

$ screen -x : connect to already attached screen session (subsequent windows)

Posted in Linux, Screen | Leave a comment

How To Show Different Colors Per Level Using Log4perl

Use the following appender to show different colors. You can also customize the color per level.

log4perl.appender.SCREEN            = Log::Log4perl::Appender::ScreenColoredLevels
log4perl.appender.SCREEN.color.INFO = white
log4perl.appender.SCREEN.color.FATAL= bold underline blink red on_white

attributes
BOLD, DARK, UNDERLINE, UNDERSCORE, BLINK
colors
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE
background colors
ON_BLACK, ON_RED, ON_GREEN, ON_YELLOW, ON_BLUE, ON_MAGENTA, ON_CYAN, ON_WHITE

Log/Log4perl/Appender/ScreenColoredLevels.pm

Posted in Log4perl, Perl | Leave a comment

How To Print in Color Using Perl

http://perldoc.perl.org/Term/ANSIColor.html

use Term::ANSIColor;
print color 'bold blue';
print "This text is bold blue.\n";
print color 'reset';
print "This text is normal.\n";
print colored ("Yellow on magenta.", 'yellow on_magenta'), "\n";
print "This text is normal.\n";
print colored ['yellow on_magenta'], 'Yellow on magenta.';
print "\n";

use Term::ANSIColor qw(uncolor);
print uncolor ('01;31'), "\n";

use Term::ANSIColor qw(colorstrip);
print colorstrip '\e[1mThis is bold\e[0m', "\n";

use Term::ANSIColor qw(colorvalid);
my $valid = colorvalid ('blue bold', 'on_magenta');
print "Color string is ", $valid ? "valid\n" : "invalid\n";

use Term::ANSIColor qw(:constants);
print BOLD, BLUE, "This text is in bold blue.\n", RESET;
Posted in Perl | Leave a comment

How To Log to Multiple Files Using Log4perl

How to log to multiple files using a single Log4perl logger.

Example: you have an INFO level logger, but you want to log warnings and errors to separate files. You also want to log to the screen.

### Throw everything into the rootLogger, then add filters and appenders
log4perl.rootLogger=INFO, LOGFILE, WARNLOG, ERRLOG, SCREEN

### Filters

# Warning log to log ONLY warnings
log4perl.filter.MatchWARN = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchWARN.LevelToMatch = WARN
log4perl.filter.MatchWARN.AcceptOnMatch = true

# Error log to log ERROR and above (ERROR and FATAL, but nothing else)
log4perl.filter.MatchERROR = Log::Log4perl::Filter::LevelRange
log4perl.filter.MatchERROR.LevelMin = ERROR
log4perl.filter.MatchERROR.AcceptOnMatch = true

### Appenders
log4perl.appender.SCREEN           = Log::Log4perl::Appender::Screen
log4perl.appender.SCREEN.mode      = append
log4perl.appender.SCREEN.layout    = Log::Log4perl::Layout::PatternLayout
log4perl.appender.SCREEN.layout.ConversionPattern  = $pattern

log4perl.appender.LOGFILE          = Log::Log4perl::Appender::File
log4perl.appender.LOGFILE.filename = $abslogfile
log4perl.appender.LOGFILE.mode     = append
log4perl.appender.LOGFILE.layout   = PatternLayout
log4perl.appender.LOGFILE.layout.ConversionPattern = $pattern

log4perl.appender.WARNLOG          = Log::Log4perl::Appender::File
log4perl.appender.WARNLOG.filename = $abslogfile.warn
log4perl.appender.WARNLOG.mode     = append
log4perl.appender.WARNLOG.layout   = PatternLayout
log4perl.appender.WARNLOG.layout.ConversionPattern = $pattern
log4perl.appender.WARNLOG.Filter   = MatchWARN

log4perl.appender.ERRLOG           = Log::Log4perl::Appender::File
log4perl.appender.ERRLOG.filename  = $abslogfile.error
log4perl.appender.ERRLOG.mode      = append
log4perl.appender.ERRLOG.layout    = PatternLayout
log4perl.appender.ERRLOG.layout.ConversionPattern = $pattern
log4perl.appender.ERRLOG.Filter    = MatchERROR
Posted in Log4perl, Perl | Leave a comment

How To Quickly Go Split Screen in VIM

Horizontal split

:split

Vertical split

:vsplit
Posted in VIM | Leave a comment

How To Determine a Good Unique Key

Make the unique key long enough to allow for reasonable duplication of names in the real world

For example, for a table of people, a unique key of country/state/city/address might be a good choice.  This allows for two people in the same city to have the same name as long as they live at different addresses.

Make the unique key short enough in case you don’t have all the information for the key always available.

Using the same example, you might not have an address for everyone, so unique key becomes useless.  You might as well shorten the unique key to country/state/city and require that people in the same city have slightly different names (maybe using a middle initial or a suffix like Jr. or Sr.)

Use a unique key that makes the most sense most of the time.

Using a unique key like country/state/metro/city might be bad since many cities might not fall into a popular metro.  Then, your data will become bad when you have two of the exact same city, but one row has the metro filled in and the other does not.  You might as well leave metro off the unique key since it will not be there ALL of the time.

In the US, a city will always belong to a state, and a state will always belong to the US, so country/state/city is a good unique key in this case.

Don’t make the unique key too short.

A unique key of country/state will be too short because there will be many people with the same name in the same state.

This is not a perfect solution.

But, it might fall into the “good enough for now” category.

Posted in MySQL | Leave a comment

How To Access Values in Perl Hash as an Array, Given a List of Keys

  my @fields = (
    "country_name",
    "region_name",
    "city_name",
  );
  while (my $row = $sth->fetchrow_hashref) {
    my %row = %$row;
    printf $format, @row{ @fields };
  }
Posted in Perl | Leave a comment