text:
Egyptian Pyramids
The Great Pyramid of Giza, the largest pyramid in Egypt, is not only the oldest of the Seven Wonders of the Ancient World, but it is also the only one to remain largely intact. The Egyptian Pyramids can take up to 20 years to build and are so big that Al-Aziz Uthman, son of the great Saladin who crushed the Crusaders, had to give up demolishing the Great pyramids of Giza because it was deemed too great a task. The Egyptian pyramids were mostly built as tombs for the country's Pharaohs and their consorts during the Old and Middle Kingdom periods (c. 2686–1690 BCE), and as of 2008, 138 Egyptian pyramids have been discovered.
The task is to create a program which inputs a sequence of distances separated by a space, and produces 10×10 text pyramids separated by those distances. A distance of 1 is equal to two characters.
A text pyramid will look like this:
         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\

If the input consists of only a line break, then one pyramid will be produced, as above. For each pyramid, pyramids to the left are displayed as if they were in front.
Example I
Input:
4 3 1

Output:
         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\

Example II
Input:
0 9

Output:
         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\

Example III
Input:
11

Output:
         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\

The application to fulfill these requirements in the fewest amount of characters is the winner.
Reference: Wikipedia.org

I presume that additional whitespace at the end of the line is permitted?

Depends who you ask. In the strictest reading of the spec, there is no whitespace following the output. But given that this is for fun, I have no problem with it.

So command line arguments for taking input is allowed?

As long as it meets the requirements. I do see now that Whitledge's solution is actually not able to handle linebreaks as input (I cannot undo my upvote), it simply works around it by producing a pyramid if there is no input. But if you can find a solution that can handle linebreak inputs (\r or \n is fine) as command line args, then it is okay with me.

Golfscript, 70 characters
~]0-:|;10,{:§9\-" "*"/""-"§2**+"\\"+:&|{.§>{§-(2*" "*1$}{-2*&>}if}%n}%

Direct port of my Ruby solution, so I'm sure it's possible to shorten this by quite a few characters.

Windows PowerShell, 122 132 133 139
$d=@(-split$input)-gt0
0..9|%{' '*(9-($x=$_))+($a="/$('--'*$_)\")+-join($d|%{'  '*(($_-$x-1)*($x-lt$_))
$a[(-2*$_)..-1]})}

Test script.
Random input also makes for nice images:

It works if I add $input=Read-Host at the top, otherwise it doesn't ask for input. How should this be run?

@nharren: echo 0 3 4 1|powershell -noprofile -file pyramids.ps1 Or from PowerShell '0 1 4 3' | .\pyramids.ps1. This is a frequent problem with golfing in PowerShell, sadly, as you can only accept either piped-in input or interactive input. PowerShell doesn't really have the notion of stdin other languages and environments have and this shows sometimes. I usually go for piped input, unless the task explicitly calls for interactivity, like Guess the number.

Ah yes, now it works. My button mashing wasn't yielding any results, and I couldn't figure out why.

Haskell, 148 characters
r=replicate
p d=map(\k->foldr(\n i->r(9-k)' '++'/':r(2*k)'-'++"\\"++drop(11+k)(r(2*n)' '++i))""$d++[0])[0..9]
main=interact$unlines.p.map read.words

I'm quite unsatisfied with this! It just feels way too long. Ideas?

Inside the lambda, you could change the big pile of ++'s to a single list and use concat aka >>=id. I don't know whether it will help. Another point would be using foldr1 instead of foldr.

Thanks for the ideas. Neither helps in this case: Converting ++ sequences only saves you one character per item, and the overhead of the final concat is too high here. The foldr can't use the foldr1 form as the result time is String whereas the list type is [Int] (The 1 variants fold require them to be the same.)

Ruby 1.9, 116 characters
d=gets.split-[?0]
10.times{|i|puts [?\s*(9-i),l=?/+?-*2*i+?\\,d.map{|r|i<(r=r.to_i)??\s*2*(r+~i)+l :l[-2*r,99]}]*""}

Python, 123 characters
N=[10]+map(int,raw_input().split())
for y in range(10):print''.join((2*n*' '+'/'+2*y*'-'+'\ ')[-2*n-1:-1]for n in N)[9-y:]

Out of curiosity, is this python 2.5? To get this to work in python 3.2, I wrapped the map function in a list function, changed raw_input() to input(), and changed print to print().

@nharren: works in both 2.4.4 and 2.5.2 for me.

Perl, 130 126 132 chars
$_=<>;$s=" "x9;map{$k.="/\\"."  "x($_-1)if$_}split;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}

Slightly shorter version which takes input as command-line arguments rather than from stdin:
$s=" "x9;map{$k.="/\\"."  "x($_-1)if$_}@ARGV;$_="$s$k/\\$s\n";for$i(0..9){print;s%\\-%-\\%g;s%\\/%-\\%g;s%\\ %-\\%g;s% /%/-%g}

Can't believe no-one did a regex solution yet. Perl is a long way from being my best language, so this can probably lose a lot more. I'd be interested to see a sed implementation, if someone's up for the challenge.
(Thanks, @mbx, for 4 chars).

foreach==for -> save 4 chars

have you tested your version with the given testcases?!

@mbx, yes, works for me. Perl 5.10.1, Ubuntu. What bug are you seeing?

@Peter Taylor - on my ubuntu and win32 it works also fine. I first tried it on ideone which is running perl 5.12.1.

@mbx, I see the problem. On ideone input is via stdin, whereas I'm reading command-line args. I'm not sure why I got the idea that that's the expected way to take input - looking now, it seems to be unspecified whether to take it on the command line or via stdin.

»If the input consists of only a line break« hints at standard input, actually.

Ah, of course - as the assignment does not force STDIN both variants of input might be okay

JavaScript, 396 bytes
function p(a){for(u=0;u<10;u++){t[u+a][9-u]="/";for(k=9-u+1+a;k<10+u+a;k++)t[k][u]="-";
t[10+u+a][u]="\\"}}function _(a){t=[];for(i=0;i<50;i++){t[i]=[];for(j=0;j<10;j++)t[i][j]=" "
}var a=a.split(" "),b=a.reduce(function(a,b){return a-0+(b-0)})*2;for(i=a.length-1;i>=0;
i--)p(b),b-=a[i]*2-0;p(0);a="";for(j=0;j<10;j++){b="";for(i=0;i<50;i++)b+=t[i][j];
a+=b.replace(/\s+$/,"")+(j<9?"\n":"")}return a}

I'm not going to win with JavaScript, but there is a JavaScript entry now :)
Usage: _("1 2 3") etc.

Ruby (112)
Slightly shorter than Ventero's Ruby solution, with a different approach. I just started learning Ruby, so this can probably be reduced quite a bit.
s=' '*9+r='/\\';gets.split.map{|i|s+=' '*2*(i.to_i-1)+r}
10.times{puts s;s.gsub!' /','/-';s.gsub!(/\\.?/,'-\\')}

Powershell, 105 98 bytes, the strictest reading of the spec
-7 bytes from migimaru's answer.
($a=' '+-join(,5+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

Test script:
$f = {

($a=' '+-join(,5+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

}

@(
,(@"
         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\
"@)

,(@"
         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\
"@, 4,3,1)

,(@"
         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\
"@, 0,9)

,(@"
         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\
"@, 11)
) | % {
    $expected, $a = $_
    $result = &$f @a
    ($result-join"`n")-eq$expected
    $result
}

Output:
True
         /\
        /--\
       /----\
      /------\
     /--------\
    /----------\
   /------------\
  /--------------\
 /----------------\
/------------------\
True
         /\      /\    /\/\
        /--\    /--\  /--\-\
       /----\  /----\/----\-\
      /------\/------\-----\-\
     /--------\-------\-----\-\
    /----------\-------\-----\-\
   /------------\-------\-----\-\
  /--------------\-------\-----\-\
 /----------------\-------\-----\-\
/------------------\-------\-----\-\
True
         /\                /\
        /--\              /--\
       /----\            /----\
      /------\          /------\
     /--------\        /--------\
    /----------\      /----------\
   /------------\    /------------\
  /--------------\  /--------------\
 /----------------\/----------------\
/------------------\-----------------\
True
         /\                    /\
        /--\                  /--\
       /----\                /----\
      /------\              /------\
     /--------\            /--------\
    /----------\          /----------\
   /------------\        /------------\
  /--------------\      /--------------\
 /----------------\    /----------------\
/------------------\  /------------------\

Powershell, 101 94, fun with one leading whitespace
($a=-join(,6+$args-gt0|%{'  '*--$_+'/\'}))
1..9|%{($a=$a-replace' /','/-'-replace'\\.?','-\')}

I couldn't get the C#3 version any shorter than this. I don't know the character count exactly, but I suspect that I have lost. :-(
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace PyramidRenderer
{
    /// <summary>
    /// Generates ASCII-art pyramids at user-specified horizontal locations to
    /// the standard output stream.
    /// </summary>
    public class Program
    {
        /// <summary>
        /// Generates one or more ASCII-art pyramids at the locations specified and
        /// sends them to the standard output stream.
        /// </summary>
        /// <param name="args">The command-line arguments. These should be non-negative
        /// integers that specify the horizontal distance of each additional pyramid from the
        /// preceeding pyramid. Whether or not any distances are suppplied, a pyramid
        /// is rendered at the starting location.</param>
        public static void Main(string[] args)
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                int[] pyramidDistances = ParsePyramidLocationsFromCommandLine(args).ToArray();
                PyramidCollection pyramids = new PyramidCollection(pyramidDistances);
                pyramids.RenderToText(Console.Out);
            }
            catch (ArgumentException ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Handler for the unhandled exception. This just displays the error message to
        /// the standard error stream.
        /// </summary>
        /// <param name="sender">Required but unnecessary sender object for the event handler.</param>
        /// <param name="e">The object that represents the exception.</param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Debug.Assert(e.ExceptionObject != null);

            string exceptionText;
            Exception ex = e.ExceptionObject as Exception;
            if (ex == null)
                exceptionText = e.ExceptionObject.ToString();
            else
                exceptionText = ex.Message;
            Console.Error.WriteLine(exceptionText);
        }

        /// <summary>
        /// Takes the command-line arguments and converts them to a sequence of
        /// non-negative integers.
        /// </summary>
        /// <param name="args">The command-line arguments as supplied to Main.</param>
        /// <returns>A sequence of integers that represent the user’s distance selections.</returns>
        /// <exception cref="ArgumentException">An invalid argument was supplied.</exception>
        private static IEnumerable<int> ParsePyramidLocationsFromCommandLine(string[] args)
        {
            Debug.Assert(args != null);

            foreach (string arg in args)
            {
                int result;
                if (int.TryParse(arg, out result))
                {
                    if (result < 0)
                        throw new ArgumentException(string.Format("Invalid distance specified: {0}", arg));

                    yield return result;
                }
                else
                {
                    throw new ArgumentException(string.Format("Invalid option: {0}", arg));
                }
            }
        }
    }

    /// <summary>
    /// Represents a single pyramid to be rendered.
    /// </summary>
    internal class Pyramid
    {
        /// <summary>
        /// The height of the pyramids in text rows. The width of each pyramid will be
        /// twice the height.
        /// </summary>
        internal const int Height = 10;

        /// <summary>
        /// The length in characters of the horizontal unit distance in which the user
        /// specifies the pyramid distances.
        /// </summary>
        internal const int PyramidUnits = 2;

        /// <summary>
        /// The character to output as the background of the pyramids.
        /// </summary>
        private const char backgroundChar = ' ';

        /// <summary>
        /// The character to output as the left edge of the pyramids.
        /// </summary>
        private const char leftEdgeChar = '/';

        /// <summary>
        /// The character to output within each pyramid, between the edges.
        /// </summary>
        private const char brickChar = '-';

        /// <summary>
        /// The character to output as the right edge of the pyramids.
        /// </summary>
        private const char rightEdgeChar = '\\';

        /// <summary>
        /// The absolute horizonal location of the pyramid’s bottom left corner as
        /// specified in PyramidUnits.
        /// </summary>
        private int position;

        /// <summary>
        /// Constructs a new pyramid object at the specified location.
        /// </summary>
        /// <param name="position">The absolute horizonal location of the pyramid’s bottom
        /// left corner in PyramidUnits.</param>
        internal Pyramid(int position)
        {
            Debug.Assert(position >= 0);

            this.position = position;
        }

        /// <summary>
        /// Renders a single row the pyramid to the supplied text stream starting at
        /// the indicated location.
        /// </summary>
        /// <param name="textWriter">The output stream to which the pyramid is to
        /// be rendered.</param>
        /// <param name="row">The row of the pyramid to render. Zero is the top row,
        /// and Height - 1 is the bottom row.</param>
        /// <param name="startingPosition">The text character position—indexed at zero—at
        /// which the rendering is to begin. If non-zero, this identifies the column one
        /// past the ending location of the previous pyramid.</param>
        /// <returns>The horizontal location (in characters) at which the next item
        /// may be rendered.</returns>
        internal int RenderRow(TextWriter textWriter, int row, int startingPosition)
        {
            Debug.Assert(textWriter != null);
            Debug.Assert(row >= 0);
            Debug.Assert(startingPosition >= 0);

            int leftBoundary = Height - 1 - row + position * PyramidUnits;
            int rightBoundary = Height + row + position * PyramidUnits;

            startingPosition = RenderField(textWriter, backgroundChar, startingPosition, leftBoundary);
            startingPosition = RenderField(textWriter, leftEdgeChar, startingPosition, leftBoundary + 1);
            startingPosition = RenderField(textWriter, brickChar, startingPosition, rightBoundary);
            startingPosition = RenderField(textWriter, rightEdgeChar, startingPosition, rightBoundary + 1);
            return startingPosition;
        }

        /// <summary>
        /// Outputs a sequence of repeated characters from the indicated starting position to
        /// just before the ending position, unless the starting position is already equal to
        /// or greater than the ending position.
        /// </summary>
        /// <param name="textWriter">The output stream to which the field is to be rendered.</param>
        /// <param name="character">The character to be repeated in the output.</param>
        /// <param name="startingPosition">The location at which rendering may begin in
        /// characters indexed at zero.</param>
        /// <param name="endingPosition">The location one past the location at which rendering
        /// is to end.</param>
        /// <returns>The position at which the next field may begin.</returns>
        private static int RenderField(TextWriter textWriter, char character, int startingPosition, int endingPosition)
        {
            Debug.Assert(textWriter != null);
            Debug.Assert(startingPosition >= 0);
            Debug.Assert(endingPosition >= 0);

            int charCount = endingPosition - startingPosition;
            if (charCount <= 0)
                return startingPosition;
            textWriter.Write(new string(character, charCount));
            return endingPosition;
        }
    }

    /// <summary>
    /// A collection of pyramids to be displayed.
    /// </summary>
    internal class PyramidCollection
    {
        /// <summary>
        /// A left-to-right ordered list of the pyramids that the user has
        /// requested to be rendered.
        /// </summary>
        List<Pyramid> allPyramids = new List<Pyramid>();

        /// <summary>
        /// Constructs a new pyramid collection.
        /// </summary>
        /// <param name="distances">The distances of each non-leftmost pyramid (in PyramidUnits) after
        /// the previous pyramid. The total number of pyramids will be one greater than the length of
        /// the distances array.</param>
        internal PyramidCollection(int[] distances)
        {
            Debug.Assert(distances != null);

            int nextPosition = 0;
            allPyramids.Add(new Pyramid(nextPosition));
            foreach (int nextDistance in distances)
            {
                Debug.Assert(nextDistance >= 0);

                try
                {
                    checked
                    {
                        nextPosition += nextDistance;
                        int endLocation = nextPosition * Pyramid.PyramidUnits + Pyramid.Height * 2;
                    }
                }
                catch (OverflowException)
                {
                    // Ignore any pyramids specified beyond the integer maximum distance.
                    break;
                }
                allPyramids.Add(new Pyramid(nextPosition));
            }
        }

        /// <summary>
        /// Outputs ASCII-art images of the pyramids in this collection to the
        /// provided output stream.
        /// </summary>
        /// <param name="textWriter">The output stream to which the pyramids
        /// are to be rendered.</param>
        internal void RenderToText(TextWriter textWriter)
        {
            Debug.Assert(textWriter != null);

            for (int row = 0; row < Pyramid.Height; row++)
            {
                int startingPosition = 0;
                foreach (Pyramid pyramid in allPyramids)
                {
                    startingPosition = pyramid.RenderRow(textWriter, row, startingPosition);
                }
                textWriter.WriteLine();
            }
        }
    }

}

Did you confuse Code Bowling and Code Golf by any chance?

At least pretend to try. People won't hold a verbose language against you if you golf it.

I guess that is your verbose version to explain your nifty tricks. It seems you forgot to post the golf version of it.

@Joey, @dmckee - I thought about doing a golf version, but haven't got around to it. I am terrible at this game anyway. Obscure code goes completely against my nature. I should probably stay away from the golf puzzles! - @mbx - Sadly, there are no nifty tricks.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Square Number Digit Density
The square number digit density (SNDD) of a number - invented by myself - is the ratio of the count of square numbers found in consecutive digits to the length of the number.  For instance, 169 is a 3-digit number containing 4 square numbers - 1, 9, 16, 169 - and thus has a square number digit density of 4/3, or 1.33.  The 4-digit number 1444 has 6 squares - 1, 4, 4, 4, 144, 1444 - and thus a ratio of 6/4, or 1.5.  Notice in the previous example that squares are allowed to be repeated.  Also, 441 is not allowed, because it cannot be found consecutively inside the number 1444.
Your task is to write a program that searches a given range A - B (inclusive) for the number with the highest square number digit density.  Your program should abide by the following specifications:

Take input A, B in the range 1 to 1,000,000,000 (1 billion).  Example: sndd 50 1000
Return as a result the number with the largest SNDD.  In the case of a tie, return the smallest number.
0 does not count as a square in any form, 0, 00, 000, etc.  Neither do squares starting with 0, such as 049 or 0049.
Note that the entire number does not have to be a square number.

Examples:
sndd 14000 15000
Output: 14441

sndd 300 500
Output: 441

Bonus: What is the number with the largest SNDD between 1 and 1,000,000,000?  Can you prove whether this is the largest possible, or there might be a larger one in a higher range?
Current Scores:

Ruby: 142
Windows PowerShell: 153
Scala: 222
Python: 245

Now that an answer has been selected, here is my (ungolfed) reference implementation in JavaScript: http://jsfiddle.net/ywc25/2/

Ruby 1.9, 142 characters
$><<($*[0]..$*[1]).map{|a|n=0.0;(1..s=a.size).map{|i|n+=a.chars.each_cons(i).count{|x|x[0]>?0&&(r=x.join.to_i**0.5)==r.to_i}};[-n/s,a]}.min[1]

(139 -> 143): Fixed output in case of a tie.

@Ventero: Fails both test cases.  I think you are forgetting to leave out squares starting with 0*

@mellamokb: Doesn't fail them here: $ ruby1.9 sndd.rb 14000 15000 => 14441. x[0]>?0 checks for squares starting with 0.

@mellamokb: It passes the test cases here.

@Ventero: Hmm.. something must be wrong with my ruby test environment.  I'm not familiar with Ruby.  I have 1.87 I think, and I copied / pasted the code above into sndd.rb, then run with ruby sndd.rb 14000 15000 from Windows, I get 14000.

@mellamokb: In Ruby 1.8, ?0 is a Fixnum, whereas in Ruby 1.8 it's a string, so the comparison I mentioned has a different meaning depending on the Ruby version (actually it should throw an exception in 1.8). That's why I explicitly mentioned version 1.9 in the title.

@Ventero: Ya, I did get an exception with your newest coding.  Downloading 1.9.2 now to test :-)

@Ventero: Works beautifully.  Thanks!  I have accepted your answer because it is currently the shortest.

Answering the bonus: the best score for numbers <1e9 is 5/3=1.666..., generated by 144411449 (and maybe others?).
But you can do better with larger numbers.  Generally if n has a score of x, then you can concatenate two copies of n and get the same score x.  If you're lucky and n has the same first and last digit, then you can drop one of those digits in the concatenation and improve your score slightly (one less than double the number of squares and one less than double the number of digits).
n=11449441 has a score of 1.625 and has the same first & last digit.  Using that fact, we get the following sequence of scores:
1.625 for 11449441
1.666 for 114494411449441
1.682 for 1144944114494411449441
1.690 for 11449441144944114494411449441
1.694 for 114494411449441144944114494411449441

which gives an infinite sequence of numbers which are strictly (although decreasingly) better than previous numbers, and all but the first 2 better than the best score for numbers < 1e9.
This sequence may not be the best overall, though.  It converges to a finite score (12/7=1.714) and there may be other numbers with better scores than the limit.
Edit: a better sequence, converges to 1.75
1.600 14441
1.667 144414441
1.692 1444144414441
1.706 14441444144414441
1.714 144414441444144414441

Interesting!  You may have just proven that this sequence is actually infinite.

@ESultanik: Not really, because there is no requirement here that the overall number be a perfect square.

@ESutanik: I don't think that sequence is related, as they are requiring the whole number to be a square - in my sequence the only squares are small subsequences (<= 5 digits), unless by accident there is a larger one.

You could also generate an infinite sequence where the link generates an extra square, i.e., something ending in 44 and beginning with 1 would make a 441 with every combination.  A trivial example would be the sequence 144, 144144, 144144144, etc.

@mellamokb Wow, I totally missed that the number didn't have to be a perfect square.  You're right.

@ESultanik: I've added a note, because I see that isn't clear from the examples I gave.

Windows PowerShell, 153 154 155 164 174
$a,$b=$args
@($a..$b|sort{-(0..($l=($s="$_").length)|%{($c=$_)..$l|%{-join$s[$c..$_]}}|?{$_[0]-48-and($x=[math]::sqrt($_))-eq[int]$x}).Count/$l},{$_})[0]

Thanks to Ventero for a one-byte reduction I was too stupid to find myself.
154-byte version explained:
$a,$b=$args   # get the two numbers. We expect only two arguments, so that
              # assignment will neither assign $null nor an array to $b.

@(   # @() here since we might iterate over a single number as well
    $a..$b |  # iterate over the range
        sort {   # sort
            (   # figure out all substrings of the number
                0..($l=($s="$_").length) | %{  # iterate to the length of the
                                               # string – this will run off
                                               # end, but that doesn't matter

                    ($c=$_)..$l | %{       # iterate from the current position
                                           # to the end

                        -join$s[$c..$_]    # grab a range of characters and
                                           # make them into a string again
                    }
                } | ?{                     # filter the list
                    $_[0]-48 -and          # must not begin with 0
                    ($x=[math]::sqrt($_))-eq[int]$x  # and the square root
                                                     # must be an integer
                }

            ).Count `  # we're only interested in the count of square numbers
            / $l       # divided by the length of the number
        },
        {-$_}  # tie-breaker
)[-1]  # select the last element which is the smallest number with the
       # largest SNDD

Python, 245 256
import sys
def t(n,l):return sum(map(lambda x:int(x**0.5+0.5)**2==x,[int(n[i:j+1])for i in range(l)for j in range(i,l)if n[i]!='0']))/float(l)
print max(map(lambda x:(x,t(str(x),len(str(x)))),range(*map(int,sys.argv[1:]))),key=lambda y:y[1])[0]

256 → 245: Cleaned up the argument parsing code thanks to a tip from Keith Randall.

This could be a lot shorter if the range were read from stdin as opposed to the command line arguments.
Edit:
With respect to the bonus, my experiments suggest the following:
Conjecture 1.  For every n ∈ ℕ, the number in ℕ≤n with the largest SNDD must contain solely the digits 1, 4, and 9.
Conjecture 2. ∃ n ∈ ℕ ∀ i ∈ ℕ≥n : SNDD(n) ≥ SNDD(i).
Proof sketch. The set of squares with digits 1, 4, and 9 are likely finite. ∎

Try range(*map(int,sys.argv[1:]))

Conjecture 2 is false if the 1.75-convergent sequence in my answer produces the best scores (a big if, admittedly), as subsequent elements of the sequence are marginally better, forever.

Conjecture 2 is false by @Arnt's answer, because the value of SNDD can be made arbitrarily large.

Scala, 222
object O extends App{def q(i: Int)={val x=math.sqrt(i).toInt;x*x==i}
println((args(0).toInt to args(1).toInt).maxBy(n=>{val s=n+""
s.tails.flatMap(_.inits).filter(x=>x.size>0&&x(0)!='0'&&q(x.toInt)).size.toFloat/s.size}))}

(Scala 2.9 required.)

Considering the bonus question:
Outside of the range the highest possible SNDD is infinite.
At least, if I read the question correctly, a square like 100 (10*10) does count.
If you consider the number 275625, the score is 5/6, since 25, 625, 5625, 75625 and 275625 are all square.
Adding 2 zero's gives: 27562500, which has a score of 10/8.
The limit of this sequence is 5/2=2.5
Along the same lines, you can find squares which end in any number of smaller squares desired. I can proof this, but you probably get the idea.
Admittedly, this is not a very nice solution, but it proofs there's no upper limit to the
SNDD.

"'Along the same lines, you can find squares which end in any number of smaller squares desired. I can proof this, but you probably get the idea."  I'd like to see this proof developed.  I can see the largest sequence ending in 25 where every number ending in 25 is a square is 275625.  There's no digit 1-9 you can place on the beginning to find another square.  Are you saying this can be made arbitrarily large, and if so, how and why?

Yes, the sequence can be made arbitrarily large. The proof is this: If aa=b is your starting number, then (a+10^c)(a+10^c) also ends in b if c is sufficiently large. In practice there may be smaller numbers which end in b if you take the square. For the example, 18275625 is a square(4275*4275).

Code to find squares: http://jsfiddle.net/zVSuZ/2/

@Arnt: Here is such a (trivial) sequence, 5^2 (1/2), 55^2 (2/4), 5055^2 (3/8), 50005055^2 (4/16), etc. where each addition is 5 * 10^n, where n is twice the previous entry.  Each entry grows smaller in score, but the limit when applying the add two 00's rule grows marginally larger, so the limits are (1/2), (2/2), (3/2), (4/2), etc.

Yes, that's the idea which proofs any value for the SNDD can be reached.

@Arnt: Beautiful, I like it!  It also disproves conjecture 2 from @Esultanik, I think.

Clojure - 185 chars
Probably could be optimised further but here goes:
(fn[A,B]((first(sort(for[r[range]n(r A(inc B))s[(str n)]l[(count s)]][(/(count(filter #(=(int%)(max 1%))(for[b(r(inc l))a(r b)](Math/sqrt(Integer/parseInt(subs s a b))))))(- l))n])))1))

Used as a function with two parameters:
(crazy-function-as-above 14000 15000)
=> 14441

Jelly, 21 bytes, language postdates challenge
DµẆ1ị$ÐfḌÆ²S÷L
rµÇÐṀḢ

Try it online!
Explanation
Helper function (calculates digit density of its input):
DµẆ1ị$ÐfḌÆ²S÷L
Dµ              Default argument: the input's decimal representation
  Ẇ             All substrings of {the decimal representation}
      Ðf        Keep only those where
   1ị$          the first digit is truthy (i.e. not 0)
        Ḍ       Convert from decimal back to an integer
         Æ²     Check each of those integers to see if it's square
           S    Sum (i.e. add 1 for each square, 0 for each nonsquare)
            ÷L  Divide by the length of {the decimal representation}

Main program:
rµÇÐṀḢ
rµ              Range from the first input to the second input
  ÇÐṀ           Find values that maximize the helper function
     Ḣ          Choose the first (i.e. smallest)

The program's arguably more interesting without the Ḣ – that way, it returns all maximal-density numbers rather than just one – but I added it to comply with the specification.

Japt -h, 18 bytes
Well, this is pretty hideous!
õV ñÈì ã fÎxÈì ¬v1

Try it
õV ñÈì ã fÎxÈì ¬v1     :Implicit input of integers U & V
õV                     :Range [V,U]
   ñ                   :Sort by
    È                  :Passing each through the following function
     ì                 :  Convert to digit array
       ã               :  Sub-arrays
         f             :  Filter by
          Î            :    First element (0 is falsey)
           x           :  Reduce by addition after
            È          :  Passing each through the following function
             ì         :    Convert from digit array
               ¬       :    Square root
                v1     :    Divisible by 1?
                       :Implicit output of last element

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Implement Sleep Sort
Sleep Sort is an integer sorting algorithm I found on the Internet. It opens an output stream, and for each input numbers in parallel, delay for the number seconds and output that number. Because of the delays, the highest number will be outputted last. I estimate it has O(n + m), where n is the number of elements and m is the highest number.
Here is the original code in Bash
#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

Here is the pseudocode
sleepsort(xs)
 output = []
 fork
   for parallel x in xs:
     sleep for x seconds
     append x to output
 wait until length(output) == length(xs)
 return output

Your task is to implement Sleep Sort as a function in the programming language of your choice. You can neglect any concurrency factors such as race conditions and never lock any shared resources. The shortest code wins. The function definition counts toward the code length.
The input list is limited to non-negative integers only, and the length of the input list is expected to reasonably long (test at least 10 numbers) so race conditions never happen.
and assuming race conditions never happen.

What counts towards the length? Complete programs including IO or just the relevant routine?

A problem with this. Depending on the order of the list, you might not read the entire list before the first value is printed. For example, a large list that takes 45 seconds to read, the first value is 2 and the last value is 1. The thread to print 1 might be executed after the 2 is printed. Oops - the output is no longer sorted properly. There might be some workarounds - creating the threads and then starting them after the whole list is read (but that will lead to longer code, against the golf). I wonder if someone can provide a golf that addresses this potential issue...I'm going to try.

Incidentally, what makes this algorithm really interesting is that there actually exist real-life applications. For instance, DNA sequencing (Sanger sequencing) depends on something like this to sort DNA fragments according to their length (and more generally, every electrophoresis does something similar). The difference is that sequencing is performed physically, not in a computer.

I hate to be the one to rain on everybody's parade, but doesn't this just offload complexity onto the OS scheduler in a way that's probably O(N^2)?

I wonder weather you can implement this in a way it actually performs well. How would you have to figure out the amount of time it has to wait per step, so the numbers would be still placed in the right order?

I think there are physical sort algorithms that takes O(n) time but O(n) physical objects. Well, we can use melting candles and a tube to do it. http://en.wikipedia.org/wiki/Spaghetti_sort

Original source, since OP didn't credit it: http://dis.4chan.org/read/prog/1295544154 NSFW (yes, seriously.)

@Nils: Well - for N < 1000, a sleep 1s should be sufficient. If n > 1000, the user has to experiment and verify the solutions :) .

Typically, insertion sort is used afterwards to correct any errors.

A kind of lame Perl attempt, 59 55 52 38 32 characters:
map{fork||exit print sleep$_}@a
Barebones: 25 Characters:
...if you don't mind the sort results as die output:
map{fork||die sleep$_}@a
With all the trimmings:
(for maximum challenge compliance, 44 characters)
sub t{map{fork||exit print sleep$_}@_;wait}
If you let perl do the wait for you, 39 characters:
sub t{map{fork||exit print sleep$_}@_}
And again, if you don't mind die(), 32 characters...
sub t{map{fork||die sleep$_}@_}
Note that in Perl 6, or when the 'say' feature is declared, it is possible to replace the print function with say, saving a character in each instance. Obviously since die both terminates the forked process and writes the output, it remains the shortest solution.

you can stil run perl-E to enable 5.010 features like say

(fork&&die sleep$_)for@a works too

C, 127 characters, a rather obvious solution:
main(int c,char**v){
#pragma omp parallel for num_threads(c)
for(int i=1;i<c;++i){int x=atoi(v[i]);sleep(x);printf("%d ",x);}}

(Compiled with gcc -std=c99 -fopenmp sort.c and ignoring all warnings.)

Cool I really have to learn opemp

I would call that 93 characters (without command-line parsing and such), but it's impressive that you can do that in only 34 extra characters in C!

@KonradRudolph - You can save 6 bytes going backwards: for(;c>=0;--c){int x=atoi(v[c]);. Not sure if that's allowed.

@owacoder that would be for(;--c;)... to leave out v[c] and v[0] which are not part of the list, v[c] == NULL and v[0] == "a.out"

APL (15 13)
{⎕←⍵⊣⎕DL⍵}&¨⎕

What it does:
¨⎕       : for each element of the input
&        : do on a separate thread
⎕DL⍵    : wait approx. ⍵ seconds
⎕←⍵     : output ⍵

I see boxes instead of 3 characters.

@ArtemIce: There are supposed to be three boxes (quads). Two are the I/O variable (reading it gets input, and writing to it prints output), and one is in the name of the ⎕DL function which is sleep.

Discussing on the APL Orchard, we wonder if ⌊∘⎕DL&¨ would count, for 7; removing the quad on the right makes it a function, ⎕DL is in the ISO SPEC for APL as delaying for "not less than" the time, so flooring its return value of "time actually delayed for" should be valid.

Ruby 1.9, 32 characters
As a function:
s=->a{a.map{|i|fork{p sleep i}}}

If we can just use a predefined variable, it reduces to 25 characters:
a.map{|i|fork{p sleep i}}

You can save quite some chars by using Thread.new{p sleep i} to print the output.

@Ventero, I'm only just learning Ruby and I'd like to know how you would run this lambda function or more specifically how you give this an input. Is it possible to run with IRB? Thanks!

JavaScript, 65 characters (depending on whether you use console.log or something else for outputting the result)
a.map(function(v){setTimeout(function(){console.log(v)},v*1000)})

This assumes that a is an array of non-negative integers and that map() exists on the array prototype (JavaScript 1.6+).

You can probably shave off two or even three characters by multiplying with 10 (or 9) instead of 1000, without compromising correctness.

@Konrad: Yes, I think that would work. I just took the "one second" from the question.

If the one second is intended to remain, you can probably use 1e3 instead.

@Tomalak, alert is JavaScript's blocking output, prompt is JavaScript's blocking input, and confirm is JavaScript's blocking binary input. If JS were to be written on the command line, those would be the calls you would use.

@zzzzBov, using blocking output would almost certainly be a bad idea for this task.

@Peter Taylor, it would make no difference. The subsequent alert calls will be performed in the order that they were called. Consider alert just duping data to an output buffer.

@zzzzBov, it's the order in which they're called which I'm worried about - unless the JS spec has strong guarantees about the order in which setTimeout-enqueued thunks are called.

@Peter Taylor, the event loop mandates that all actions/events are queued. If an event is called while the script is blocked, it will wait its turn to execute. This is well defined behavior although it can lead to some serious issues with functions like setInterval which will continue to be called while the script is blocked, creating more calls that take longer than the duration of the interval leading to a constant block.

@Peter: JavaScript is strictly single-threaded. All events are processed in the order they were queued, setTimeout() is no exception. FWIW, I had more "append to a DOM element" in my mind than "alert". For things like node.js, I'm certain that "output to the console" also exists. My point was that the 65 characters might vary depending on what function you call.

How does it destroy the original array?

@minitech You are right, it doesn't. My mistake. I'll correct the post.

Even better: setTimeout("console.log(v)",v*1e4)

a.map(v=>{setTimeout(()=>{v},v*1)})

Four tries in Erlang:
Output to the console, have taken the liberty to do this each 9ms * Number since this is plenty enough to make it work (tested on a Atom embedded board = slow):
Needs 60 chars
s(L)->[spawn(fun()->timer:sleep(9*X),io:write(X)end)||X<-L].

Output to the console is total un-Erlangish, so we send a message to process P instead:
Needs 55 chars
s(P,L)->[spawn(fun()->timer:sleep(9*X),P!X end)||X<-L].

Sending after a time can also be done differently (this even works with 1ms * Number):
Needs 41 chars
s(P,L)->[erlang:send_after(X,P,X)||X<-L].

Actually this is a bit unfair since the built in function send_after is a late comer and needs the namespace erlang: prefixed, if we consider this namespace imported (done on module level):
Needs 34 chars
s(P,L)->[send_after(X,P,X)||X<-L].

Java (aka never wins at codegolf) : 234 211 187 chars
public class M{public static void main(String[]s){for(final String a:s)new Thread(){public void run(){try{sleep(Long.parseLong(a));}catch(Exception e){}System.out.println(a);}}.start();}}

ungolfed:
public class M {
    public static void main(String[] s) {
        for(final String a:s) new Thread(){
            public void run() {
                try {
                    sleep(Long.parseLong(a));
                } catch(Exception e){}
                System.out.println(a);
            }
        }.start();
    }
}

@Joey thanks for setting it straight.

The class can be non-public, saving 7 chars.

You could also declare throws Throwable and get rid of the catch clause.

I think you can save 2 bytes by replacing Long.parseLong with Long.valueOf.

I know it's been 6.5 years, but you can golf some parts: public and final can be removed; class M{public static void main can be interface M{static void main (Java 8+); Long.parseLong(a) can be new Long(a) (resulting in 165 bytes)

would enum M work?

@MilkyWay90 I'm pretty sure that shortcut works in Java 5 and 6, but not in Java 7 and later. I haven't tested it though.

Python - 81 93 148 150 153
Tweaking @BiggAl's code, since that's the game we're playing....
import threading as t,sys
for a in sys.argv[1:]:t.Timer(int(a),print,[a]).start()

... or 97 175 with delayed thread starting
import threading as t,sys
for x in [t.Timer(int(a),print,[a]) for a in sys.argv[1:]]:x.start()

Takes input via the command line, ala
./sleep-sort\ v0.py 1 7 5 2 21 15 4 3 8

As with many python golfs, there comes a point where the code is compact enough that aliasing variables to shorten names doesn't even save characters.
This one is funky though because it aliases sys and threading BOTH as t, so sys.argv becomes t.argv. Shorter than from foo import *, and a net character savings! However I suppose Guido wouldn't be pleased...
Note to self - learn c and stop golfing in python. HOLY COW THIS IS SHORTER THAN THE C SOLUTION!

I managed to make some tweaks, but the formatting doesn't show up nicely in comments so I made my own answer. daemon doesn't need setting unless you're starting this as a daemon, and it's shorter to use positional args, esp. if you alias None to N

Oh and the first one doesn't work for me under 2.7.1, as j seems to end up as False - a side-effect of trying to do too much in one line?

shit I didn't realise you could import multiple modules to the same alias - I could actually think of some uses for that where I have multiple subclasses of the same custom base class lying about in seperate sub-modules. If we can shave off another 30 it's shorter than bash... But I don't think that'll happen.

Argh the reason why I didn't know is because you can't - I just tried running it and threading is not aliased, it's just called threading. It's sys that is aliased to t... Did you try running this? It's only an extra 2 chars on each though to import as t,s and then change to use s for sys

Argh you can't even do that, it's import threading as t, sys as s

You called me on it, I only did one incomplete test before I posted this solution. If my char count holds,     import threading as t, sys as s is still better so net victory

why don’t you use the print function instead of sys.stdout.write?

for x in [t.Timer(int(a),print,[a]) for a in sys.argv[1:]]:x.start() can become for x in[t.Timer(int(a),print,[a])for a in sys.argv[1:]]:x.start() by removing useless espaces to save 2 bytes

C# - 137 characters
Here is an answer in C# (updated with degrees of parallelism as commented)
void ss(int[]xs){xs.AsParallel().WithDegreeOfParallelism(xs.Length).Select(x=>{Thread.Sleep(x);return x;}).ForAll(Console.WriteLine);}

You’ll need to specify WithDegreeOfParallelism for this to work, analogously to the num_threads in my OpenMP C code.

120 bytes: void m(int[] l){foreach(var i in l){var t=new Thread(()=>{Thread.Sleep(int.Parse(s));Console.Write(s);});t.Start();}}}

@MrPaulch Note that you need to join the threads again, if you want your program to have the expected behaviour

Why? The longest running thread will keep the process alive.

ColdFusion (8+), 109 bytes
<cfloop array="#a#" index="v"><cfthread><cfthread action="sleep" duration="#v*1000#"/>#v#</cfthread></cfloop>

Ungolfed:
<cfloop array="#a#" index="v">
  <cfthread><cfthread action="sleep" duration="#v*1000#"/>#v#</cfthread>
</cfloop>

This assumes that <cfoutput> is in effect. A few characters could be saved by writing it all on one line.

Scala - 42 40 characters (special case)
If you have a thread pool at least the size of the number of list elements:
a.par.map{i=>Thread.sleep(i);println(i)}

Scala - 72 characters (general)
a.map(i=>new Thread{override def run{Thread.sleep(i);println(i)}}.start)

afaik you don’t use {} when staying on one line.

@flying sheep - You can omit {} with one statement, but you still need it to group things separated by ;, one line or no.  And you can write multi-line statements without {} in some cases (if/else for instance).

oh, i didn’t mean you can omit them, but that you can use () for one-liners instead. it’s a matter of taste there, i think. (i just don’t really get why () are supported at all when {} superseed them. maybe to not alienate java users instantly). Scala is cool, but defining code blocks by indentation is clearly superior. (and so, the religious war ensues ;))

@flying sheep - You're misinformed.  You can use () for single statements.  Try entering (1 to 9).map(i => {val j = i+1; i*j}) in the REPL and then see what happens if you use (1 to 9).map(i => (val j = i+1; i*j)).

true, but i only referred to for expressions and stuff. Sorry, I hate writing stuff without being able to use linebreaks ;)

@flying sheep - Agreed about line breaks, but there are no {} that can be replaced with () in my answer, so why did you bring it up?

Oh, crap, you’re right. It’s lrn2read for me, I guess :)

But there was a set of ()s that could be replaced by {}!

Javascript  - 52 characters
for(i in a)setTimeout("console.log("+a[i]+")",a[i])

Welcome to CodeGolf.SE! I have formatted you answer for you, in particular indenting your code by four space to make it display as code. You'll find other formatting help in the sidebar of the edit page.

Haskell - 143 characters
import Control.Concurrent
import System
d=threadDelay
f x=d(10^6*x)>>print x
g s=mapM(forkIO.f)s>>d(10^6*maximum s+1)
main=getArgs>>=g.map read

This probably could be made a shorter by taking input on stdin if that were an option, but it's late and either way, it's still 104 characters for the function itself.

Befunge-98, 38 31 bytes
I know this is an old challenge, but I just recently discovered both sleepsort and 2D languages, had an idea about how to combine them, and looked for a place to post it, so here we are.
&#vt6j@p12<'
v:^ >$.@
>:!#^_1-

The main IP reads a number (&), then hits the t which clones it: one proceeds on the same line and cycles, reading new numbers and generating new childs until it reaches EOF which terminates the sequence.
All the child processes get stuck in a closed loop (the v and ^ of the third column) until the main IP finishes reading the input and executes the sequence of commands '<21p, which puts the character < at position (1,2), overwriting the ^ and freeing all the child processes, which start to simultaneously cycle, reducing by 1 their number at each iteration. Since execution speed of different IPs is synchronized in befunge, they will terminate (and print their value) in order, sorting the input list.

26 bytes by moving the control flow around a bit.

A little late to the party:
Maple - 91 83 characters
In 91:
M:=():use Threads in p:=proc(n)Sleep(n);:-M:=M,n;end:Wait(map(i->Create(p(i)),L)[])end:[M];

In 83:
M:=():use Threads in Wait(seq(Create(proc(n)Sleep(n);:-M:=M,n end(i)),i=L))end:[M];

(This needs Maple version 15, and expects the list to be sorted in L)

C, 70 69 chars
Doesn't wait for child processes to return, otherwise works.
main(n) {
    while(~scanf("%d",&n)?fork()||!printf("%d\n",n,sleep(n)):0);
}

Haskell, 90
import Control.Concurrent
s::[Int]->IO()
s=mapM_(\x->forkIO$threadDelay(x*9999)>>print x)

I hope this meets all the requirements.

Rust, 125 bytes
Used the depricated sleep_ms function so I don't need to write a long duration.
|p:Vec<u32>|p.into_iter().for_each(|i|{use std::thread::{spawn,sleep_ms};spawn(move||{sleep_ms(i*1000);println!("{}",i)});});

playground link

JavaScript, 38 bytes
a=>a.map(x=>setTimeout(alert,x*1e3,x))

This will wait milliseconds instead of seconds

You can use alert to save 6 bytes

@mousetail Oops, didn't catch that it was required to use seconds.

PHP 57 bytes
<?for(;$i=fgets(STDIN);)pcntl_fork()?:die($i.usleep($i));

pcntl_fork() is only available under linux.

Bash (38):
xargs -P0 -n1 sh -c 'sleep $0;echo $0'

Edit: Floating-point from stdin, separated by spaces or newlines.

, 11 chars / 22 bytes
ïć⇝שĤ⇀ôa,a⸩

Try it here (Firefox only).
שĤ⇀ôa, this looks cool.

PowerShell 7, 40 bytes
Filters are a kind of function:
filter f{$args|% -Pa{sleep $_;$_}-Th 99}

PS C:\> f 3 2 1
1
2
3

It uses Powershell 7's ForEach-Object -Parallel feature, which defaults to 5 threads, so has -ThrottleLimit 99 to make it at work for the required 10 numbers.

you can save this code $args|% -Pa{sleep $_;$_}-Th 99 to a stanalone .ps1 script file. This is a Powershell program.

@mazzy Nice! this question specifically asks for "a function" including the function definition, so I'm not sure if it counts - if it is valid, it's -10 and would put it around 3rd shortest, which would be good.

A file with a Powershell script is both a program and a function. So a code that works in a standalone .ps1 file fits perfectly

Just some tweaking from @rmckenzie 's version:
Python delayed thread start in 155 152 114 108 107:
import sys, threading as t
for x in [t.Timer(int(a),sys.stdout.write,[a]) for a in sys.argv[1:]]:x.start()

Python without delay in 130 128 96 95 93:
import sys,threading as t
for a in sys.argv[1:]:t.Timer(int(a),sys.stdout.write,[a]).start()

Managed a few more optimisations, using Timer instead of Thread, which has a more concise call and removed the need to import time. Delayed thread start method benefits from list comprehension as it removes the need to initialise the list seperately at the start, although it's two characters longer ("["+"]"+" "-":") than the for loop so it's useless without delayed start, and you have to be careful to use a list rather than a generator, or you're not actually creating the timer threads until you chunk through the generator.
Does anyone else have any optimisations?

The trick with as helps, but in 2.7.1 you can only import one module into an alias, and after some playing about you can't even import mod1,mod2 as a,b, you have to import mod1 as a, mod2 as b. It still saves a few characters, but isn't quite the cure-all I thought it was... And in fact it's better to leave sys as sys. Aliasing threading still helps though...

you got me beat, have an upding. I like the x=[];x+=[]. Didn't know you could do that....

... you could do this in 128 if you loose the spaces between the : [statement] in your loop and f(x)... somehow I got it to 127, but I think that's by not counting the final newline (which is legit in CG). Thought I'd give you the update rather than being a tool and stealing your code.

@rmckenzie go for it, I stole yours. I'm always interested in seeing CG'd python - I feel like I'm doing something very perverse considering the goals of the language...

Yeah, I'm honestly shocked by how legible most python golfs stay... at the cost of a "glass floor" of characters. Check this one out: import threading,sys as t

Clojure, 54
(defn s[n](doseq[i n](future(Thread/sleep i)(prn i))))

you can get rid of few characters by inlining omitting defn (its brackets + argument list: from 54 to 43 chrs), or use fn instead of defn => len-=2
so I'd say in clj its 43 :D

C++11, 229 bytes
#import<future>
#import<iostream>
using namespace std;int main(int a,char**v){auto G=new future<void>[a];while(--a){G[a]=move(async([=](){this_thread::sleep_for(chrono::seconds(atoi(v[a])));cout<<v[a]<<" "<<flush;}));}delete[]G;}

Ungolfed and usage:
#import<future>
#import<iostream>
using namespace std;
int main(int a,char**v){
 auto G=new future<void>[a];
 while(--a){
  G[a]=move(async(
   [=](){
    this_thread::sleep_for(chrono::seconds(atoi(v[a])));
    cout<<v[a]<<" "<<flush;
   }
  ));
 }
 delete[]G;
}

Rust - 150 bytes
And this is why you don't code golf in Rust, it's more verbose than Java ;). Depends on external crate crossbeam, it would be even worse without it.
|x|{extern crate crossbeam;crossbeam::scope(|s|for&v in x{s.spawn(move||{std::thread::sleep(std::time::Duration::from_secs(v));println!("{}",v)});})}

Complete test program:
fn main() {
    let z =
    |x|{extern crate crossbeam;crossbeam::scope(|s|for&v in x{s.spawn(move||{std::thread::sleep(std::time::Duration::from_secs(v));println!("{}",v)});})}
    ;
    z(&[4, 2, 3, 5, 7, 8, 9, 1, 6, 10])
}

Julia 1.0, 41 bytes
!l=@sync l.|>i->@async sleep(i)println(i)

Try it online!
@async adds the task to the machine's scheduler queue, and @sync waits for all @asyncs to finish

C (clang), 72 bytes
main(n){~scanf("%d",&n)?fork()?wait(main()):printf("%d ",n+sleep(n)):0;}

I chose clang but it also works on gcc.

takes input from stdin
fork()
if it's the child, then sleep (returns 0 if sleep succeeded, see sleep(3)) and print the number... if it's the parent call main recursively (which implicitly returns 0 since C99).
when there's no more input we return from main() and start waiting for the children, the children also call wait() a number of times depending on the recursion depth but they don't have any children so that fails immediately for them.

Try it online!

Kind of boring, port of C#, just to get started with the language again:
F# - 90 characters
PSeq.withDegreeOfParallelism a.Length a|>PSeq.iter(fun x->Thread.Sleep(x);printfn "%A" x)

JavaScript, 74
function(a){for(i=0;i<a.length;i++)setTimeout('alert('+a[i]+')',a[i]*1e3)}

or 71/65 characters with nonstandardness:
function(a){a.map(function(v){setTimeout('console.log('+v+')',v*1e3)})}

Even back in 2011 I think function(a){a.map(function(v){setTimeout(console.log,v,v)})} may have worked in at least one browser for 60 bytes. Of course these days you would write a=>a.map(v=>setTimeout(console.log,v,v)) instead.

Tcl 8.6, 41 chars
lmap c $argv {after $c "puts $c"};vwait f

You have to kill it with ^C

VB.NET 100 bytes
Because VB.Net requires single line lambdas to contain only one statement, this code has to have the multiple lines:
Array.ForEach(i, Async Sub(x)
Await Threading.Tasks.Task.Delay(x*1000)
Console.WriteLine(x)
End Sub)

Ungolfed:
Option Strict Off

Sub Main(i() as String)
    Array.ForEach(i, Async Sub(x)
                         Await Threading.Tasks.Task.Delay(x * 1000)
                         Console.WriteLine(x)
                     End Sub)
End Sub

However I'm not sure if you count imports statements in the byte counts because if you don't count them then I could write this:
VB.NET 71 bytes
a.ForEach(i, Async Sub(x)
Await t.Delay(x*1000)
c.WriteLine(x)
End Sub)

Ungolfed:
Option Strict Off
Imports t = System.Threading.Tasks.Task
Imports c = System.Console
Imports a = System.Array

Sub Main(i() as String)
    a.ForEach(i, Async Sub(x)
                     Await t.Delay(x * 1000)
                     c.WriteLine(x)
                 End Sub)
End Sub

Groovy, 47 bytes
Assumes numbers are given on the command line...

args.each{i->Thread.start{sleep(i*22)print i}}

Mathematica, 34 or 36 bytes
RunScheduledTask[Print@#,{#,1}]&/@

Just append the list to be sorted to the end of this code and evaluate. If it needs to be a valid function definition then it takes two extra bytes:
RunScheduledTask[Print@#,{#,1}]&/@#&

Java 9, 82 bytes
i->{i.parallelStream().map(j->{Thread.sleep(j);System.out.println(j);return 0;});}
i->{                                                                             }  //lambda: arguments: List<int> i
    i.parallelStream().map(                                                    );   //iterate over each item in a parallel thread
                           j->{                                               }     //lambda: arguments: int j
                               Thread.sleep(j);                                     //sleep j milliseconds
                                               System.out.println(j);               //print that int
                                                                     return 0;      //just some return value to fullfil the requirements of map()

Some issues which practically mean this is an invalid solution. Thread.sleep throws InterruptedException (a checked exception that needs to be caught) which means this does not work. Also, streams don't run every element in a separate thread, and in fact because streams are lazy, this doesn't work at all as nothing is done with result of map. There is also no such thing as List<int> in Java.

Java - 106 bytes
l->l.forEach(x->new Thread(()->{try{Thread.sleep(x);System.out.println(x);}catch(Exception e){}}).start())

Complete test program:
import java.util.List;
import java.util.function.Consumer;

public class CG {
    public static void main(String[] args) {
        Consumer<List<Integer>> sleepSort = l->l.forEach(x->new Thread(()->{try{Thread.sleep(x);System.out.println(x);}catch(Exception e){}}).start());
        sleepSort.accept(List.of(3423, 143, 4545, 2545, 764, 5121, 2333, 944, 6555, 1066));
    }
}

Japt, 11 bytes
Ëe3 t{OpD
P

Try it online!
Unpacked & How it works
UmD{De3 t{OpD
P

UmD{  Map input array with the function...
De3 t{  Run the following function after D * 1000 milliseconds...
OpD       Print D with newline

P     Set "" as the thing to implicitly print

JS's setTimeout is obviously the winner. Unlike setInterval which is low-capped at 10ms, setTimeout doesn't have such an arbitrary limit.
If the delay need not be in seconds, the following works (and gives the result much faster):
8 bytes
Ët{OpD
P

Try it online!

You could overwrite the crud output by N.t() (no idea why ETH  did that) and avoid the need for the "P" by using O.q() instead. Each number would overwrite the previous one, though, which may not be allowed behaviour.

PowerShell 6, 34 bytes
$args|%{$(sleep $_;$_)&}|rcjb -wai

Try it online!
See Background operator &

PowerShell, 48 bytes
$args|%{sajb{sleep $args;$args}-ar $_}|rcjb -wai

Try it online!
where:

sajb is the predefined alias for start-job and
rcjb is the predefined alias for receive-job

The default ThrottleLimit is 32.


text:
Pascal's Pyramid and Higher Dimensions
Pascal's Triangle is a familiar mathematical construct with many interesting properties.  It is constructed by starting with a 1 on top, and generating the numbers in the next row from the sum of the number to the left and right in the row above (with implied 0's around the boundary):
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

The Triangle can be expanded into N dimensions by using the same rules. For example, the 3-D Pascal's Triangle would be a pyramid with each row being a cross-section of the pyramid, i.e., a triangle.  Each triangle's entry is generated by adding the three numbers in the "row" above forming a triangle directly above that entry.  An example of the first four "rows" is shown below:
1

 1
1 1

  1
 2 2
1 2 1

   1
  3 3
 3 6 3
1 3 3 1

The 4-D Pascal's Triangle would have a 3-D Pascal's Triangle for the cross section, and so forth.
Your task is to write a program that takes as input the dimension of the Pascal's Triange, and a row index to display.  The row index starts at 0, so row 0 is 1 for every dimension.  Your program should abide by the following specifications:

Take input N = dimension number, R = row number (0-based). The input can be either command-line arguments or from stdin.  N >= 2, R >= 0
Output the R'th row in the N-dimensional Pascal's Triangle, by displaying each row or triangle on a separate line as in the above example.
The format can vary as long as it is 'triangle-like' and obvious where each row and entry in the row belongs with respect to other rows.

Here is some sample output (I believe these are correct):
>./pascal 2 5
1 5 10 10 5 1
>./pascal 3 4
        1
      4   4
    6  12   6
  4  12  12   4
1   4   6   4   1
>./pascal 4 3
1

 3
3 3

  3
 6 6
3 6 3

   1
  3 3
 3 6 3
1 3 3 1
>./pascal 5 2
1

2

 2
2 2

1

 2
2 2

  1
 2 2
1 2 1

Bonus: What is the significance of each "row" in an N-dimensional Pascal's triangle?  I can think of at least three interesting facts.

Attempt to partly answer to the bonus question: 1/ obvious, but each is an (N-1)-dimensional "triangular" slice; 2/ the N extremeties are always all "1".

@asoundmove: All good ideas.  Here's something to think about.  What is the sum of all the numbers in one "row"?

Further attempt: 3/ all N (N-2)-bases of the (N-1) slice of the N-dimensional pascal triangle are identical.

Yet another one: 4/ all N (2D) vertices of the R-th row of the N-dimensional pascal triangle are the R-th row of the 2D pascal triangle.

@ mellamokb: sum of all numbers: N^R

Ruby, 181
def P(a)a.min<0?0:a.max<1?1:(b=a*1;t=k=0;b.map{b[k]-=1;k+=1;t+=P(b)};t)end
def d(n,a)print n>1?((0..a[-1]).map{|i|d(n-1,a+[i])};"\n"):"#{P(a)} "end
d(ARGV[0].to_i,[ARGV[1].to_i])

The first approach using the following recursive formula
P(...,-1,...) = 0
P(0,0,...,0) = 1
P(a,b,c,....) = P(a-1,b,c,...) + P(a-1,b-1,c,...) + P(a-1,b-1,c-1,...) + ...

and then printing row P(R,...).
The output is triangle-like - for pascal 4 2 it looks like
1

3
3 3

3
6 6
3 6 3

1
3 3
3 6 3
1 3 3 1

@Peter adjusted formula and code to match starting index 0.


text:
Expanding Expressions
Given an expression of one-letter variables ([a-z]), operators (*, +, &) and parenthesis, expand it using the following axioms:
a * b != b * a
a * b * c = (a * b) * c = a * (b * c)
a + b = b + a
a + b + c = (a + b) + c = a + (b + c)
a * (b + c) = a * b + a * c
a & b = b & a
a & (b + c) = a & b + a & c

   | Comm | Assoc | Dist
 * | NO   | YES   |
 + | YES  | YES   | *
 & | YES  | YES   | + *

The user will input an expression, the syntax of the input expression is called "input form". It has the following grammar:
inputform ::= expr
var ::= [a-z] // one lowercase alphabet
expr ::= add
       | add & expr
add ::= mult
      | mult + add
mult ::= prim
       | prim * mult
       | prim mult
prim ::= var
       | ( expr )

Before
That means, the order of operations is * + &, a + b * c & d + e = (a + (b * c)) & (d + e)
Furthermore, the operator * can be omitted:
    a b (c + d) = ab(c + d) = a * b * (c + d)
Whitespace is stripped out before parsing.
Examples:
(a + b) * (c + d)
= (a + b)(c + d)
= (a + b)c + (a + b)d
= ac + bc + ad + bd
(a & b)(c & d)
= ac & ad & bc & bd
(a & b) + (c & d)
= a + c & a + d & b + c & b + d
((a & b) + c)(d + e)
= ((a & b) + c)d + ((a & b) + c)e (I'm choosing the reduction order that is shortest, but you don't need to)
= ((a & b)d + cd) + ((a & b)e + ce)
= ((ad & bd) + cd) + ((ae & be) + ce)
= (ad + cd & bd + cd) + (ae + ce & be + ce)
= ad + cd + ae + ce & ad + cd + be + ce & bd + cd + ae + ce & bd + cd + be + ce

Due to commutativity, order of some terms do not matter.
Your program will read an expression in input form, and expand the expression fully, and output the expanded expression in input form, with one space separating operators, and no spaces for multiplication. (a + bc instead of a+b * c or a + b * c or a + b c)
The fully expanded form can be written without any parens, for example, a + b & a + c is fully expanded, because it has no parens, and a(b + c) is not.
Here is an example interactive session (notice the whitespaces in input)
$ expand
> a(b + (c&d))
ab + ac & ab + ad
> x y * (wz)
xywz
> x-y+1
Syntax error
> c(a +b
Syntax error

The last axiom states a & (b + c) = a & b + a & c but this is not stated in your distribution table below. In contrast there it says a+(b&c)=a+b&a+c which you also do in your last example.

these stuff are too difficult to done by head

I don't think there is a unique reduction, or not all formulae can be reduced.  Note: (a & b)(c+d) = (a & b)x = ax & bx = a(c+d) & b(c+d) = ac+ad & bc+bd but (a & b)(c+d) = y(c+d) = yc+yd = (a & b)c+(a & b)d = (ac & bc)+(ad & bd) = z+(ad & bd) = z+ad & z+bd = (ac & bc)+ad & (ac & bc)+bd = ac+ad & bc+ad & ac+bd & bc+bd.  In contrast, if you only allow right-associativity or left-associativity and not both, then any expression with the other (given with parens) cannot be unfolded.

After finding out how Perl junctions expand, I found a solution to the associativity problem: (a+b)(c&d)(e+f)(g+(h&i)) = (a+b)u(e+f)(g+v), u = (c+d), v = (h&i), but it's too late to change the question

Ruby, 698 648
O=[A='&',B='+',C='*']
M='Syntax error'
def u(x)c=x.shift;(c.nil?)?S[0]=~/[a-z]/?(S.shift):S[0]=='('?(S.shift;o=u(O*1);S[0]==')'?(S.shift;o):abort(M)):abort(M):(o=[c];loop{o<<u(x*1);break if S[0]!=c;S.shift};o)end
def d(e,a,b)a!=e[0]?e:(i=e.index{|x|x[0]==b};(i.nil?)?e:y([b]+e[i][1..-1].map{|k|z=e*1;z[i]=k;z}))end
def y(e)e.map!{|x|(x.is_a?Array)?(y(x)):(x)};o=[e[0]];e[1..-1].map{|x|x[0]==o[0]?(o+=x[1..-1]):(o<<x)};d(d(d(o.size==2?o[1]:o,C,B),C,A),B,A)end
def j(e)(e.is_a?Array)?(e.map!{|x|j(x)};o=e.shift;e*(o=='*'?'':" #{o} ")):e;end
S=gets.gsub(/ /,'').gsub(/([a-z)])(?=[a-z(])/,'\1*\2').split(//)
k=u(O*1)
puts S!=["\n"]?(M):(j y k)

This solution consists of a basic recursive descent parser (method u) which builds an syntax tree which is then flattened (y) and transformed (d) according to the distribution axioms. The output (j) simply joins the operands again.
Unfortunately I broke the functionality when I later tried to reduce the code by restructuring. Nevertheless I think there is still some chance for golfing.

Scala - 1049 characters
This is not fully golfed, but it gets increasingly incomprehensible as I continue, and since the examples do not all appear to be correct, I want to leave the code at least slightly sane so it can be modified.
To be run as a script file.  Empty input ends the program.
type S=String
case class R(rs: List[R], s: S)
def n(s: S)=List(" + "," & ").indexOf(s)
def pr(r:R,v:Int=2):S = if (r.rs.isEmpty) r.s else {
  val x = r.rs.map(pr(_,n(r.s))).mkString(r.s)
  if (n(r.s)>v) "("+x+")" else x
}
object P extends scala.util.parsing.combinator.RegexParsers {
  val v="[a-z]"r
  def e:Parser[R]=repsep(a,"&") ^^ {R(_," & ")}
  def a=repsep(m,"+") ^^ {R(_," + ")}
  def m=repsep(p,"\\*?"r) ^^ {R(_,"")}
  def p=v ^^ {R(Nil,_)} | "("~>e<~")" ^^ {r=>R(r::Nil,"")}
}
def up(r: R):R = r match {
  case R(x::Nil,_) => up(x)
  case _ => R(r.rs.map(up),r.s)
}
def asc(r: R) = R(r.rs.flatMap(i=>if (i.s==r.s) i.rs else List(i)),r.s)
def dis(r: R):R = {
  val q = asc(r.rs.find(i=>n(i.s)>n(r.s)).map(i => {
    val (a,b)=r.rs.span(_ ne i)
    R(i.rs.map(j=>R(a ::: j :: b.tail,r.s)),i.s)
  }).getOrElse(R(r.rs.map(dis),r.s)))
  if (q==r) r else dis(q)
}
def parse(s: S) = P.parseAll(P.e,s).map(x=>pr(dis(up(x)))).getOrElse("Syntax error")
Iterator.continually{print("> ");readLine}.
takeWhile(_.length>0).foreach(s=>println(parse(s)))

Haskell, 472 437 characters
import Text.Parsec
data E=V Char|O Int E E
r o=fmap$foldr1(O o)
c=char
s=sepBy1
e=r 0$s(r 1$s (r 2$s(fmap V lower<|>between(c '(')(c ')')e)(optional$c '*'))(c '+'))(c '&')
g(O a x(O b y z))|b<a=g$O b(g$O a x y)(g$O a x z)
g(O a (O b x y)z)|b<a=g$O b(g$O a x z)(g$O a y z)
g e=e
d(V c)=[c]
d(O o x y)=d x++[" & "," + ",""]!!o++d y
x=either(const "Syntax error")d.fmap g.parse e"".filter(`notElem`" \t")
main=interact$unlines.map x.lines


text:
Code 39 Barcode Scanner
Code 39, developed in 1974, is one of the most commonly used symbologies, or types, of barcodes, although it is the UPC/EAN system that is most often seen in retail sales. Code 39 barcodes can encode uppercase letters, numbers, and some symbols and are trivial to print from computer software using a special font. This led to their widespread commercial and industrial use (e.g. company ID badges, asset tracking, factory automation).
Create the shortest program or function to read a Code 39 barcode in any orientation from a 512x512 pixel grayscale image; the barcode might not be aligned horizontally or vertically.

Your program must accept a standard image file format and produce the data encoded in the barcode as its standard output or return value (not including any start/stop character).
No image contains more than one valid Code 39 barcode, and no barcode encodes a space character (ASCII 32).
If no valid Code 39 barcode is shown in the image, the program must output a single question mark (?).

I have prepared a JavaScript reference implementation and test suite of images in PNG format, both with valid barcodes and without. The reference implementation, which fails only 3 of 46 test cases in most recent Web browsers, is intended to show one possible decoding algorithm, not to strictly conform to the above specification.
A valid submission passes at least 80% of these tests (37/46) and takes no more than one minute to do so for each image on a reasonably fast CPU (e.g. 2.6 GHz quad-core). My reference implementation passes 93% of tests and processes each image within 10 seconds (on my desktop PC running Google Chrome).
(This question was proposed on Meta on May 28, 2011.)

There appears to be a bug in your barcode generator - it puts a wide space between characters instead of a narrow one.

@Keith: The intercharacter gap (I) does not have to be equal to the width of a narrow bar (X), although it often is. Valid submissions should be able to read barcodes where I ≤ 3X. My test case generator intentionally randomizes the intercharacter gap. http://www.adams1.com/39code.html

a Code 39 barcode with anintercharacter gap between 1X and 3X can be read by most common scanners? I will testify it and see whether it works this way. By the way, in my eyes, the intergap can only enlarge the Code 39 printout size, so why should we expand its intercharacter gap?

Python, 899 chars
import sys,random
raw_input()
X,Y=map(int,raw_input().split())
input()
I=[' x'[v<'~']for v in sys.stdin.read()]
M={196:' ',168:'$',148:'*',388:'.',52:'0',97:'2',49:'4',112:'6',292:'8',73:'B',25:'D',88:'F',268:'H',28:'J',67:'L',19:'N',82:'P',262:'R',22:'T',193:'V',145:'X',208:\
'Z',42:'%',138:'+',133:'-',162:'/',289:'1',352:'3',304:'5',37:'7',100:'9',265:'A',328:'C',280:'E',13:'G',76:'I',259:'K',322:'M',274:'O',7:'Q',70:'S',385:'U',448:'W'\
,400:'Y'}
N=500
for w in' '*30000:
 a,b,c,d=eval('random.random(),'*4);A=''.join(I[int((a+(c-a)*i/N)*X)+X*int((b+(d-b)*i/N)*Y)]for i in range(N)).lstrip();T=A.count(' x')+1;K=A.count('x')/T;L=A.count\
(' ')/T;s='';z=c=0
 while A:
  z*=2;y=A.find(' ')
  if y<0:y=len(A)
  z+=y>K;A=A[y:]
  z*=2;y=A.find('x')
  if y<0:y=len(A)
  z+=y>L;A=A[y:];c+=2
  if c>9:
   if z/2in M:s+=M[z/2];z=c=0
   else:break
 if s and'*'==s[0]and'*'==s[-1]and'*'!=s:print s[1:-1];break

This code takes a pnm format image as input, so I normally run it like:
pngtopnm s01.png | ./barcode.py

The code itself just picks lots of random scanlines and tries to match the black and white runs on that scanline to the code39 patterns.  It is randomized so it can fail to find barcodes on occasion.  (I get about a 20% false negative failure rate on the test images.)  When it fails it takes about a minute to run, when it succeeds it often does so much quicker than that.  I've never seen a false positive.

M=dict(zip('UK.-RQA+HGYXON*TEDJ1/87$%540WVML SCBIZPF3296',[385,259,...]))


text:
Reversing base numbers
Where input is binary, convert it to a decimal number (base 10), reverse the decimal number and output it. Vice versa for decimal (base 10) input: reverse it, convert it to binary and output the binary number.
Sample Input:
00000001
00000010
255
00011000

Sample Output
1
2
1000101000
42

other Sample Input
78
35
01011001
231

other Sample Output
01010111
00110101
98
10000100

Welcome to CodeGolf.SE! You question seem to be underspecified (by which I mean I am not parsing "decimal reversed equivalent" at all), and you have not stated what contest is being proposed. If you mean this to be a code golf it should be tagged as such. Please consider having your questions reviewed at the meta SandBox or in the puzzle lab chat where we would be more than happy to help you hammer out these kinds of details before your task goes live.

What happens if the input is a number which has an ambiguous base, e.g. 10000000 which could be interpreted as binary (32768 decimal) or decimal (1 million) ?

yes, may be we have to add some thing to recognize when is binary and when decimal :) some thing like d or b after the number idk :)

What about those leading zeroes actually?

In C and other languages a 0123 means an octal number and a 0x123 a hex number. Maybe leading zero (or two) can specify it.

@pimvdb: They are needed so you always have four-digit numbers. @queue: Obviously this is math, not C, so octal doesn't apply.

The problem remains inadequately specified.

There needs to be a spec for what makes defines a binary number. While it makes the control logic ludicrously short, I agree with @skylamer that the "b" flag should be added to the end of binary cases. 00000010b = 2 for instance.

Ruby, 68 characters
puts$<.map{|i|i[/[^01\s]/]?"%08b"%i.reverse: i.to_i(2).to_s.reverse}

Uses stdin/stdout, interprets lines that consist only of 1s, 0s and whitespace as binary numbers, everything else as decimal.

this is working , but its just conversing the number from bin to dec... not reversing it :)

@skylamer: Fixed, I wasn't sure what exactly you meant with "reversing" before. A more detailed problem description with more details for the input/ouput specification would help preventing such misunderstandings.

So for now, pimvdb@js and ventero@ruby is the closer to the answer z

JavaScript, 140 199 bytes
(function(x){s=x.split("\n"),r=b='';for(i in s)r+='\n'+(s[i].replace(/[01]*/g,b)?
(s[i].split(b).reverse().join(b)-0).toString(2):(parseInt(s[i],2)+"")
.split(b).reverse().join(b));return r.trim()})('1\n10\n255\n11000')

Excluding input. It requires, however, that there are no numbers present in the input which are base 10 and only have 1s / 0s in them.

may be , cuz when the input is dec... goes reversed in same and then out like a binary :) so 255 552 and 1000101000

@primvdb: Apparently this is what the OP means by the confusing phrase "decimal reversed equivalent".  It looks like all decimal input is to be text reversed before converting, and all binary after converting should be text reversed as well.

@mellamokb: Oh I see, thanks. It now passes the testcases.

So for now, pimvdb@js and ventero@ruby is the closer to the answer z

@skylamer: I don't have the leading zeroes yet, as I still don't see the way you'd like them to appear - should a binary number's length always be a multiple of 4?

perl - 90 89
map{print reverse(/^[01]+$/?unpack"N",pack"B*",sprintf"%032d",$_:sprintf"%b",$_).$/}@ARGV

Any number containing only 1's and 0's is considered binary.
Funny how so much more code is required for bin->dec vs. dec->bin...

Python - 117 characters
while 1:
 x=raw_input()
 if(not(False in map(lambda x:x in ("1","0"),s))):print int(x,2)
 else:print bin(int(x))[2:]

This golf relies heavily on the fact that python counts a single space as a full indentation. Note that this golf IS NOT ERROR-PROOF. While functional, it will throw an EOFError when there is no input. Protecting against this requires an extra 30 characters.
Changelog
v0 - 120 chars
v1 - 117 chars - changes "While True" to "While 1"

Quite frankly, i still don't get the testcase for 255, i'll mend my solution when the OP corrects/expands the description.
My Solution is based of rmckenzie
Python - 84 bytes
while 1:
 x=raw_input()
 print all(i<"2"for i in x)and int(x,2)or bin(int(x))[2::]

all(i<"2"for...)

@gnibbler, doh, so obvious...

bash 67
b(){ [[ $1 =~ ^[01]*$ ]]&& s="i"||s="o";echo $s"base=2;$1"|bc|rev;}

J, 60 characters
((1&":@#:@(10&#.@|.)`(|.@":@#.))@.(0=[:+/1<[))".;' ',.1!:1[1


text:
Score counter for Skat
You task is to write a small program, that counts the points of a Skat hand. A Skat deck has cards 7 to 10, Jack, Queen, King and Ace (called Unter, Ober, König and Daus). We use the German suits, which have Acorns, Leaves, Hearts and Bells instead of Clubs, Spades, Hearts and Diamonds. The points are determined by the number on the card:

7, 8 and 9 are 0 points
Unter is 2 points
Ober is 3 points
König is 4 points
10 is 10 points
Daus is 11 points.

Input / Output
The input format consists of two symbols, the first one represents the value, while the second one stands for the suit:

7, 8 and 9 stand for them self
0 (zero) stands for 10
Unter, Ober, König and Daus are named after their first letters (U, O and D)
The same for Acorns, Leaves, Hearts and Bellys (A, L, H and B)

The input is a single line of cards, separated by a single whitespace. You may take the input from anywhere, command line arguments are okay too. The output is the value of the hand, either printed out or returned as an exit code. The output of your program must show an error, if any card appears twice in the hand. (So 7A 0L 7A must return an error instead of 10). It is also okay to quit with an exit code of 255 instead of showing an error, if this is the default way of your program to output the result.
Examples

7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB gives 120
7A 8L 0K DB 8L gives an error
UA OB DL KH gives 20

Rules

Code golf: The shortest code wins
Usual code golf rules apply
The program has to work for all hands, not just the examples
GIGO: If the input is invalid, the output may be arbitrary

Is additional output to stderr (e.g. warnings) ok?

@Ventero: Yes, it is. Any way to err out is okay, but it must be clearly visible to the user, that there is an error.

Jack, Queen, and Ace are called Unter, Ober, King and Daus? Is a king supposed to be in there?

@minitech No, it is not.

I believe you mean "bells", not "bellys".  Very different, that.

APL (54 48)
There has to be a shorter way of selecting the card value, but I don't see it.
(+/12-'D0.....KOU.'⍳⊃¨A)÷A≡∪A←↓A⍴⍨2,⍨2÷⍨⍴A←⍞~' '

You get a DOMAIN ERROR if there's a duplicate card.
Explanation:

A←⍞~' ': store (←) into A a line of user input (⍞) without (~) the spaces.
2,⍨2÷⍨⍴A: a two-element list, containing the length of (⍴) A divided by (÷⍨) 2, followed by (,⍨) the number 2. (So, if the input is UA OB DL KH the list is (4, 2)).
↓A⍴⍨: define a matrix (⍴), with the dimensions of that list, containing the values of A. Then join the elements of its rows together (↓), giving a list of lists, for example ['UA','OB','DL','KH'].
A←: Store this list in A.
A≡∪A: ∪A is the list of unique elements in A. If this is equal to A, there are no duplicates and this returns 1, otherwise 0.
÷: divide what's on the left (which does the actual calculation) by the result of the equality test. So if there are no duplicates, the score is unchanged, and if there are duplicates you get a DOMAIN ERROR because of the division by zero.
⊃¨A: A list giving the first element (⊃) of each element (¨) of A. So this drops the suit letter, leaving the score letter. (UODK)
'D0.....KOU.'⍳: gives the index of each of the score letters in this string, returns 12 for values not in the string. (10 9 1 8)
+/12-: subtract all of these from 12, and then add them together. (2 + 3 + 11 + 4 = 20)

I totally missed that your answer is the shortest.

Ruby 1.9, 52 characters
Input via command line arguments. I'm assuming the error message when having duplicate cards doesn't matter, so it just complains about an eval/type conversion error.
p eval$*.uniq!||$*.map{|i|"..UOK#$<.0D"=~/#{i}?/}*?+

Example usage:
$ ruby1.9 skatscore.rb 7A 8A 9A UA OA KA 0A DA 7L 8L 9L UL OL KL 0L DL 7H 8H 9H UH OH KH 0H DH 7B 8B 9B UB OB KB 0B DB
120

$ ruby1.9 skatscore.rb 7A 7A
skatscore.rb:1:in `eval': can't convert Array into String (TypeError)
    from skatscore.rb:1:in `<main>'

On the one hand I think the undefined variable error for duplicate cards is kinda lame. On the other hand, it doesn't break the rules, so it's kinda clever.

@Charles: Since the spec only calls for an error, I guess what error exactly is pretty much irrelevant. And if there are short methods of producing any error, that should be fine, I guess.

Scala, 87 82 characters
args.distinct(args.size-1);println(args.map(a=>1+" UOK     0D".indexOf(a(0))).sum)

Throws an exception on repeated cards.

Haskell, 122 108 107 characters
import List
main=interact$f.words
f x|nub x==x=show$sum$map(maybe 0 id.(`elemIndex`"  UOK     0D").head)x

error"" is shorter than undefined. Save one char using interact.

@FUZxxl: Using interact it won't print a newline, so I'm not sure if that's acceptable. However, I was able to save a lot more by using an incomplete pattern instead of undefined.

Where did I say, that a newline is needed? I can't remember.

GolfScript 54 53 52
Edit 1:
I just discovered an error in the code. It did not detect duplicate cards if the duplicates were the first two in the input (because I was using the * fold operator and not the / each operator for the first loop).
Now I fixed the code and also managed to strip off 1 char in the process. Here's the new version:
' '/{1$1$?){]?}{\+}if}/2%{"UOK0D"\?).0>+.4>5*+}%{+}*

The input has to be on the stack as a string, in the specified format (example: '7A UA DA').
In case the input is valid, the program prints the total value of the cards.
In case there's at least one duplicate card, the program throws the following exception:
(eval):1:in `block in initialize': undefined method `class_id' for nil:NilClass (NoMethodError)

Edit 2:
After seeing this post on the meta site, I decided to post a description of the code. This also helped me find and fix an error. So, here goes:
# Initially, we epect the input string to be on the stack
# Example: "7A UA DA"

' '/            # split the input string by spaces
                # now we have on the stack an array of strings
                # (in our example: ["7A" "UA" "DA"])

# {1$1$?)!{\+}{]?}if}/  -> this piece of code checks for duplicate cards
#
# The trailing symbol (/) is the 'each' operator, meaning that the
# preceding code block (enclosed in curly brackets) will be executed
# for every cards in the previous array.
#
# Before each execution of the code block, the current card value
# is pushed on the stack.
#
# Basically what this code does is concatenate cards into a string
# and checks whether the current card is contained in the accumulated
# value.
#
# So, for each card, this is what we execute:

1$              # copies the concatenated string on top of the stack
                # (initially this is an empty string)

1$              # copies the current card on top of the stack

?               # returns (places on the stack) the 0-based index where
                # the current card is found in the concatenated string
                # or -1 if not found

)               # increments the topmost stack value
                # Now we have 0 if the card is not a duplicate
                # or a value greater than 0 otherwise

{]?}{\+}if      # if the current stack value is non-0 (duplicate)
                # then execute the first code {]?} (generates an error)
                # Otherwise, if the card is valid, execute the {\+} block.
                # What this code does is essentially concatenate the current
                # card value:
                #    \ -> swaps the two topmost stack values; now we have
                #         the concatenated string and the current card value
                #    + -> this is the concatenation operator

# After the previous code block finishes execution (in case the input is)
# valid, we end up having the concatenated card values on the stack
# In our example, this value is "DAUAUB7A".

# The next code fragment is the one that computes the card values
# This is the code: 2%{"UOK0D"\?).0>+.4>5*+}%{+}*

# And this is how it can be broken down:

2%              # takes only the even indexed chars from the existing string
                # in our case, "DAUA7A" -> "DU7"
                # Only these characters are important for determining the
                # card values.

# The following piece of code is:
# {"UOK0D"\?).0>+.4>5*+}%

# This code performs a map; it takes the individual chars,
# computes the corresponding numeric value for each of them and outputs an
# array containing those values

# This is achieved using the map operator (%) which evaluates the preceding
# code block, delimited by curly braces, so, essentially this is the code that
# computes the value for a card:
# "UOK0D"\?).0>+.4>5*+
# It can be broken down like this:

"UOK0D"         # pushes the "UOK0D" string on the stack
\               # swaps the two topmost stack values
                # Now, these values are: "UOK0D" and "l"
                # (where "l" represents the current letter
                # that gives the card its value: U,O,K,0,D,7,8...)

?               # Find the index of the card's letter in the
                # "UOK0D" string.
                # Remember, this is 0-based index, or -1 if not found.

)               # increment the index value
                # Now we have the following value:
                #     1 if the card is U
                #     2 if the card is O
                #     3 if the card is K
                #     4 if the card is 0
                #     5 if the card is D
                #     0 if it is anything else

.0>+            # if the current value is greater than 0,
                # add 1 to it.

.4>5*+          # if the current value is greater than 4,
                # add 5 to it.

# Passing through these steps, we now have the following value:
#     2  if the card is U
#     3  if the card is O
#     4  if the card is K
#     10 if the card is 0
#     11 if the card is D
#     0  if it is anything else
# This is the exact value we were looking for.

# Now we have an array containing the value of each card.
# in our example, [0, 2, 11]
# The next piece of code is easy:

{+}*            # uses the * (fold) operator to add up all the
                # values in the array.

# This leaves the total value of the cards on the stack,
# which is exactly what we were looking for (0+2+11=13).

# Golfscript is awesome! :-)

Python, 114 characters
i=input().split();print(sum(int(dict(zip('7890UOKD','000A234B'))[x[0]],16)for x in i)if len(i)<=len(set(i))else'')

Unfortunately, the index method of lists in Python raises an error if an element isn't found rather than returning a negative value, and importing defaultdict would require more characters than it would save.

eTeX, 201 characters (not counting the two irrelevant linebreaks)
\def~#1#2{\catcode`#113\lccode`~`#1\lowercase{\def~}##1 {\ifcsname
#1##1 ~\D\fi\if\csname#1##1 ~\fi+"#2}}~70~80~90~0A~U2~O3~K4~DB\def
\a[#1]{\let~\endcsname\write6{^^J \the\numexpr#1 }\end}\expandafter\a

Used as etex filename.tex [UA OB DL KH]. Putting the argument in brackets is necessary: otherwise, eTeX has no way of determining that we reached the end of the argument list.
EDIT: as allowed in the statement of the question, incorrect input can cause (an) error. For instance, etex filename.tex [OK] crashes horribly (because K is not a valid color).

Doesn't works on my machine.

@FUZxxl. What is the output of etex -v? What is the error message (roughly)? The code should be put in a file (with name filename.tex, or anything else ending in .tex), and use that name in the command line etex filename.tex [<argument>]. (sorry to repost the same comment, I forgot "@FUZxxl")

Please look here: http://hpaste.org/48949

@FUZxxl. Thank you for your feedback. K is not a valid color, and replacing it by X in your examples removes the errors (it crashes with K because that letter has another meaning, King). I could make the error less horrible by adding \string before each ##1, but that would cost 12 more characters.

Sorry. I misstyped the example. It works now. Sorry.

PowerShell, 79 80
($a=$args|sort)|%{$s+=(10,11+4..0)['0DKOU'.IndexOf($_[0])]}
$s/("$a"-eq($a|gu))

Throws »Attempted to divide by zero.« if cards appear twice.