text:
The Colors in Our Stars
Write a program that takes in a string or text file whose first line has the form
width height

and each subsequent line has the form
x y intensity red green blue

where:

width and height may be any positive integers.
x and y may be any integers.
intensity may be any non-negative integer.
red, green, and blue may be any integers from 0 to 255 inclusive.

Your program must output a truecolor image in any common lossless image file format whose dimensions are width by height. Each x y intensity red green blue line represents a colorful star or orb that must be drawn on the image. There may be any number of stars to draw, including 0. You may assume the string or file has a trailing newline.
The algorithm for drawing the image is as follows, though you may implement it in any way you like as long as the result is identical:

For every pixel (X,Y) in the image (where X is 0 at the leftmost
  edge and width-1 at the rightmost edge, and Y is 0 at the top edge
  and height-1 at the bottom edge), the color channel C ϵ {red,
  green, blue} (a value pinned between 0 to 255) is given by the equation:

Where the dist function is either Euclidean distance:

Or Manhattan distance:

Choose whichever distance function you prefer, based on golfability or aesthetics.
Each of the lines in the input besides the first is an element of the Stars set. So, for example, Sx represents the x value on one of the input lines, and SC represents either red, green, or blue, depending on which color channel is currently being calculated.

Examples
Example A
If the input is
400 150
-10 30 100 255 128 0

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.
Example B
If the input is
200 200
100 100 10 255 255 255
20 20 40 255 0 0
180 20 40 255 255 0
180 180 40 0 255 0
20 180 40 0 0 255

the respective outputs for Euclidean and Manhattan distance should be
 and .
Example C
If the input is
400 400
123 231 10 206 119 85
358 316 27 170 47 99
95 317 3 202 42 78
251 269 17 142 150 153
43 120 3 145 75 61
109 376 6 230 231 52
331 78 21 31 81 126
150 330 21 8 142 23
69 155 11 142 251 199
218 335 7 183 248 241
204 237 13 112 253 34
342 89 18 140 11 123

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.
Example D
If the input is
400 400
123 231 5 206 119 85
358 316 5 170 47 99
95 317 5 202 42 78
251 269 5 142 150 153
43 120 5 145 75 61
109 376 5 230 231 52
331 78 5 31 81 126
150 330 5 8 142 23
69 155 5 142 251 199
218 335 5 183 248 241
204 237 5 112 253 34
342 89 5 140 11 123

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.
Example E
If the input is
100 1

then the output should be a 100 pixel wide by 1 pixel tall image that is completely black.
Notes

Take the input string or the name of a text file that contains it from stdin or the command line, or you may write a function that takes in a string.
"Outputting" the image means either:

Saving it to a file with the name of your choice.
Printing the raw image file data to stdout.
Displaying the image, such as with PIL's image.show().

I won't be checking that your images are pixel perfect (Stack Exchange lossily compresses images anyway) but I will be very suspicious if I can visually tell any difference.
You may use graphics/image libraries.

Winning
The shortest submission in bytes wins. In case of ties, the earliest submission wins.
Fun Bonus: Give the input for a truly spectacular output image.

+1 Wow. This is gorgeous. (And an appropriate time for posting, as we hear word from a healthy New Horizons spacecraft!)

Does the input have to be in that space separated format, or can it be comma separated? Anyways, +1.

@Maltysen Space separated. (I know that's stingy but it's easier than allowing a dozen input variants.)

I can't decide if the orbs or stars are more beautiful.

For pixel-perfection you could compare the bitmap's hash

Really beautiful. Just one thing that is missing on the formula: C(x,y) = min(formula, 255), since that for small distances, the color goes out of the roof.

@KuramaYoko Good point. Everyone seems to have accounted for that but I've made it clear that the color is pinned between 0 and 255.

Pyth - 46 bytes
This was fun! I finally got to use Pyth's image I/O features. Does euclidean distance because of golfiness, though manhattan is just a short change.
Krz7.wcmmsm/*@b+3k@b2h.a,<b2_.DdhKrR7.zU3*FKhK

This just loops through all the pixels with the formula's though it condenses the pixel loop into one loop and uses divmod since Pyth only supports 3 nested maps and the calculations take two (one for RGB and one for the stars).
Saves image as o.png. Pretty slow, does the first 2 tests in <2 min, but the other 2 take on the order of half an hour.
There is a bug in .w that no one noticed because no one uses it ;) but I put in a pull request so use my fork to test if isn't merged soon. Merged!
Examples Outputs
Example A

Example B

Example C

Example D

Wow, didn't know Pyth could do that. One day we might end up writing business software in Pyth. It's less code to write, so it should be faster and easier to refactor. :D

@w0lf "programmer time is more important than execution time" and we all know that Pyth helps reducing programmer time :) The image I/O was added recently after Pyth was left out from a graphical output challenge. It uses Pillow internally.

@w0lf How short code is has nothing to do with how easy it is to refactor.

@Nit Absolutely. It also has nothing to do with how fast it is to write. My previous comment was a joke.

You guys forgot one important thing - its easier to debug too, since the code is less ;)

By reducing programmer time you mean "They're playing code golf with pyth and so have less time to write 'real' code"?

The only way to know if it reduced programmer time to take an average programmer and have them write code using both Pyth and Python. I think we all know what the results would be. :P

JavaScript 394 344
function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}

Edit: shortened the code a lot by applying wolfhammer's awesome suggestions.
Test
Note: Wait a few seconds for the snippet below to render (takes ~4 seconds on my machine).

function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}

var start = Date.now();

X("400 150\n" +
  "-10 30 100 255 128 0");

X("200 200\n" +
  "100 100 10 255 255 255\n" +
  "20 20 40 255 0 0\n" +
  "180 20 40 255 255 0\n" +
  "180 180 40 0 255 0\n" +
  "20 180 40 0 0 255");

X("400 400\n" +
  "123 231 10 206 119 85\n" +
  "358 316 27 170 47 99\n" +
  "95 317 3 202 42 78\n" +
  "251 269 17 142 150 153\n" +
  "43 120 3 145 75 61\n" +
  "109 376 6 230 231 52\n" +
  "331 78 21 31 81 126\n" +
  "150 330 21 8 142 23\n" +
  "69 155 11 142 251 199\n" +
  "218 335 7 183 248 241\n" +
  "204 237 13 112 253 34\n" +
  "342 89 18 140 11 123");

X("400 400\n" +
  "123 231 5 206 119 85\n" +
  "358 316 5 170 47 99\n" +
  "95 317 5 202 42 78\n" +
  "251 269 5 142 150 153\n" +
  "43 120 5 145 75 61\n" +
  "109 376 5 230 231 52\n" +
  "331 78 5 31 81 126\n" +
  "150 330 5 8 142 23\n" +
  "69 155 5 142 251 199\n" +
  "218 335 5 183 248 241\n" +
  "204 237 5 112 253 34\n" +
  "342 89 5 140 11 123");

var end = Date.now();

console.log('Done in ' + (end - start)/1000 + 's.');
canvas {
  display: block;
  padding: 10px;
}

You can also run it in JSFiddle.
Bonus: Blue Eclipse

function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}

var j = 0;
var renderFrame = function () {
  if(window.h && window.v){h.body.removeChild(v);} // clear prev frame
  X("225 150\n" +
    (70 + j) + " " + (120 - j) + " 170 135 56 0\n" +
    j * 5 + " " + j * 3 + " 64 0 50 205");
  if(++j < 50) { setTimeout(renderFrame, 1); } else { console.log('done!'); }
};
setTimeout(renderFrame, 10);

You can also run it in JSFiddle.
Description
This is a straightforward JavaScript + HTML5 canvas implementation: a function that takes a string argument (without trailing spaces/newlines) and displays the output in the DOM. It uses Euclidean distance.
Here is the readable code:
X = function (str) {
  var lines = str.split("\n");
  var canvas = document.createElement('canvas');
  var z = lines[0].split(u=' ');
  var width = z[0], height = z[1];

  canvas.width = width;
  canvas.height = height;
  document.body.appendChild(canvas);

  var ctx = canvas.getContext("2d");
  var imageData = ctx.createImageData(width, height);

  for(var y = 0; y < height; y++){
    for(var x=0; x < width; x++){
      var coord = (y * width + x) * 4;

      for(i=1; i < lines.length;i++){
        var t = lines[i].split(u);

        var
          dx = x - t[0],
          dy = y - t[1];

        var distance = Math.sqrt(dx * dx + dy * dy);

        for(var channel = 0; channel < 3; channel++) {
          var channelIndex = coord + channel;
          imageData.data[channelIndex] += t[2] * t[3 + channel] / (distance + 1);
        }
      }

      var alphaIndex = coord + 3;
      imageData.data[alphaIndex] = 255;
    }
  }

  ctx.putImageData(imageData, 0, 0);
};

I love how halos glued together in Blue Eclipse, can you add manhatan style?

@PTwr Sure, here it is: http://jsfiddle.net/pjLnazw1/

Awesome! (7 more to go... ugh)

@w0lf You can shave some bytes off your function by combining the x and y iterators.  jsfiddle

@wolfhammer Wow, that's now just "some bytes", it's a lot of improvement. I'll take a look at that later, as I believe there's something to be fixed about the indexing (for sample images 2, 3 and 4 the pixels on the left appear to wrap around). Thanks!

@w0lf Yeah I see that.  The prior iteration looks accurate. Try the third one.

@wolfhammer Thanks! I've edited my post. I managed to save a few more chars. JS has great golfing potential; never realized this until now. :)

Java - 627 bytes
Java is indeed one of the best golfing languages :)
import java.awt.image.*;class M{void f(String n)throws Exception{String[]p=n.split("\n");int[]b=s(p[0]);BufferedImage o=new BufferedImage(b[0],b[1],2);for(int i=0;i<b[0];i++)for(int j=0;j<b[1];j++){int[]c=new int[3];for(int l=1;l<p.length;l++){int[]r=s(p[l]);for(int k=0;k<3;k++){c[k]+=r[2]*r[3+k]/(Math.sqrt(Math.pow(i-r[0],2)+Math.pow(j-r[1],2))+1);if(c[k]>255)c[k]=255;}}o.setRGB(i,j,new java.awt.Color(c[0],c[1],c[2]).getRGB());}javax.imageio.ImageIO.write(o,"png",new java.io.File("o.png"));}int[]s(String s){String[]a=s.split(" ");int[]r=new int[a.length];for(int i=0;i<a.length;i++)r[i]=Integer.valueOf(a[i]);return r;}}

Using the input below, you can create a somewhat realistic model of our solar system (the size of some planets is wrong, but the distance between them should be accurate).
I tried to give rings to saturn, but it didn't work... Source

1950 50
-15 25 25 255 255 0
39 25 1 255 0 0
55 25 3 255 140 0
68 25 4 0 191 255
92 25 2 255 0 0
269 25 10 245 222 179
475 25 7 245 245 220
942 25 6 0 250 150
1464 25 6 0 0 255
1920 25 1 255 245 238

Full HD picture, which doesn't look thaaat great... Would be happy if someone could improve it!

+1 for Solar System. -1 for leaving Pluto (now that we even know its real color and size)

Also, it would be really nice if a full 1080p wallpaper is linked :)

@Optimizer I added pluto ;) Lets see what I can do about the wallpaper

Relevant link on size and color  resp. http://pluto.jhuapl.edu/News-Center/News-Article.php?page=20150713 and https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/tn-p_lorri_fullframe_color.jpg?itok=2Bznj_zJ

@Sp3000 Ups, forgot the intensity when I added pluto

Note that Saturn isn't the only planet with rings. If you get rings to work, you should add them to Uranus also.

In terms of wallpaper, it would be interesting if you plotted the planets in their current orbital position (looking down on the solar system). Or even a recreation of the famous self-portrait of the solar system from Voyager 1

@Optimizer but... what about Ceres? And Eris? And Sedna? And Makemake? And...

Bash, 147 145 bytes
ImageMagick is used to manipulate images. Euclidean distance is used.
read w h
o=o.png
convert -size $w\x$h canvas:black $o
while read x y i r g b
do
convert $o -fx "u+$i*rgb($r,$g,$b)/(hypot(i-$x,j-$y)+1)" $o
done

You can save a byte with $w\x$h.

... and another with o=o.png.

Python 3, 189 bytes
I'm nobody's idea of an expert golfer, but here goes.

Input comes from stdin and goes to stdout in PPM format.
Run it like so: python3 codegolf_stars_golfed.py < starfield.txt > starfield.pnm

First, Manhattan distance:
import sys
(w,h),*S=[list(map(int,l.split()))for l in sys.stdin]
print('P3',w,h,255,*(min(int(sum((I*C[z%3]/(abs(X-z//3%h)+abs(Y-z//3//h)+1))for
X,Y,I,*C in S)),255)for z in range(h*w*3)))

And secondly, Euclidean distance:
import sys
(w,h),*S=[list(map(int,l.split()))for l in sys.stdin]
print('P3',w,h,255,*(min(int(sum((I*C[z%3]/(abs(X-z//3%h+(Y-z//3//h)*1j)+1))for
X,Y,I,*C in S)),255)for z in range(h*w*3)))

I could save four bytes by using integer division instead of int(), and in fact that seems to be what the original images do--you can just barely make out some striations in the dark fringes of the star glow that aren't present in strictly correct code. As it stands, though, this code follows the description, not the images.
The ungolfed version, and my original golfing before the many optimisations that others pointed out or that I stumbled upon myself, are in this gist.
EDIT: I saved 7 bytes by moving for x and for y into a single print (or o) function, but this produces a PNM file with a very long line, which may or may not cause some problems.
EDIT 2: Maltysen saved me another 20 bytes. Thanks!
EDIT again: Now that there's only one print, the o alias is a liability, not a saving. 4 more bytes off.
EDIT some more: Sp3000 saved me 2 more bytes. Meanwhile, aliasing map to m wasn't saving anything, so in the interests of readability(!) I've expanded it again. It's now a nice round 28 bytes.
EDIT the last(?): Now with Euclidean distance support--and by abusing complex numbers, I did it in exactly the same number of bytes!
EDIT, the Hollywood reboot: Sp3000's next suggestion knocked off 5 bytes.
EDIT, the stupidly named sequel: 6 bytes trimmed off, thanks to a suggestion Maltysen made that I didn't grasp until Sp3000 repeated it... then another 8 bytes from % abuse. And talking it out in chat knocked off a phenomenal 21 26 bytes. I'm humbled.

@Maltysen: Quite right. 20 bytes saved!

some more:   instead of that complicated sys.stdin stuff with EOFs you can use iter() with sentinel values: https://docs.python.org/2/library/functions.html#iter as iter(raw_input,''), also put w,h,S on the same line with extended unpacking.

@Maltysen: I'm not sure that would work. I was doing almost exactly that already, but it hits EOFError (and so I needed a try block), because there's no blank line in the input file and I'm not sure the challenge allows me to add one. Or am I missing something?

I think if  you the sentinel value thing, you could just terminate by a blank line versus feeding the file in, though ,yeah, the file thing wouldn't work.

@Sp3000: Surprisingly, yes! I was expecting it to complain that stdin wasn't an iterator.

btw I'm not sure if this helps, but here's how I would have read input if I could get PIL working on Py 3: w,h,*L=map(int,stdin.read().split());*S,=zip(*[iter(L)]*6)

Although, at this point it's better to ditch from sys import*;stdin and make the submission a function taking in a multiline string

@Sp3000: I honestly don't think that would make it shorter! Or rather, I don't think I could make it shorter that way. Between the function definition (what, nine characters minimum?) and splitting on newlines (though there must be something shorter than .splitlines()), I'd be lost to find the savings. Besides, I like it more this way, being self-contained rather than needing something to call it.

The idea was that you'd skip splitting on newlines specifically, and use .split() to split on all whitespace. In any case, you can probably do (w,h),*S=[list(map(int,l.split()))for l in sys.stdin]

Also, instead of for y in r(h)for x in r(w) you can probably loop over for z in r(h*w), and let y be z%h and x be z//h. Then the r=range alias becomes useless, and r(3) can become 0,1,2

@Sp3000, @Maltysen:  I think Maltysen was suggesting (w,h),*S earlier, but I couldn't grasp how it'd work until now. Thanks. (And that %/// trick just shows me how new I am at this whole golfing thing.)

Let us continue this discussion in chat.

Can you please post the original code you wrote (the core which was optimized then)?

@TopQuestions: Linked to a gist in the answer. I wasn't sure whether you meant my original submission, or the completely ungolfed version I started from, so they're both there. (I was going to post some milestone intermediate versions too, but they're in the revision history, so I didn't bother.)

Completly overread that link. Thanks!

Sorry for the downvote haha, I accidentally tapped whilst scrolling down :)

C++, 272 bytes
#include<png.hpp>
#define G(a)i>>C;for(x=0;x<w*h;++x){auto&p=img[x%h][x/h];c=p.a+I*C/(abs(x/h-X)+abs(x%h-Y)+1);p.a=c>255?255:c;}
auto&i=std::cin;main(){int w,h,x,X,Y,I,c,C;i>>w>>h;png::image<png::rgb_pixel>img(w,h);while(i>>X>>Y>>I){G(red)G(green)G(blue)}img.write("a");}

Needs a lenient C++11 compiler (GCC 4.9.2 is only slightly displeased), and the png++ library, which itself requires libpng. Manhattan distance used. Takes input on stdin, outputs to a file named "a" in the current directory in PNG format.
Example D:

I like the PCG image :) (Though PPCG is my preferred abbreviation ;) )

Python 2, 240 232 228 bytes
from PIL.Image import*
def f(S):
 L=map(int,S.split());t=a,b=L[:2];I=new("RGB",t)
 for k in range(a*b):I.load()[k/a,k%a]=tuple(sum(x[2]*x[c]/(abs(x[0]-k/a)-~abs(x[1]-k%a))for x in zip(*[iter(L[2:])]*6))for c in(3,4,5))
 I.show()

Uses Manhattan distance. This would probably be even shorter in Python 3, but I messed up my Python packages recently and I'm having trouble reinstalling Pillow. PPM would probably be even shorter, but I like PIL.
For fun, I tried to apply the algorithm as is in the L*a*b* color space instead, thinking it would give better colour blending (especially in example B). Unfortunately, Calvin's algorithm lets channels go over their max values, which makes the images look a little less awesome than I hoped...

Python 2, 287 251 bytes
A golfed version of the original code I used to generate the images. Could probably be golfed a bit more (by a better golfer than me). It's a function that takes in the full input string. Image processing done with PIL's Image Module. Uses Manhattan distance.
from PIL import Image
def S(I,r=range):
 I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
 for z in r(w*h):
  P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1.+abs(I[i]-z%w)+abs(I[i+1]-z/w))for i in r(2,len(I),6)))for j in r(3))
 M.show()

Using Euclidean distance is 5 bytes longer (256 bytes):
from PIL import Image
def O(I,r=range):
 I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
 for z in r(w*h):
  P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1+((I[i]-z%w)**2+(I[i+1]-z/w)**2)**.5)for i in r(2,len(I),6)))for j in r(3))
 M.show()

Here's a complete test suite that runs examples A through E from the question, for both distance metrics:
from PIL import Image
def S(I,r=range):
 I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
 for z in r(w*h):
  P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1.+abs(I[i]-z%w)+abs(I[i+1]-z/w))for i in r(2,len(I),6)))for j in r(3))
 M.show()

def O(I,r=range):
 I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
 for z in r(w*h):
  P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1+((I[i]-z%w)**2+(I[i+1]-z/w)**2)**.5)for i in r(2,len(I),6)))for j in r(3))
 M.show()

A = """400 150
-10 30 100 255 128 0"""
B = """200 200
100 100 10 255 255 255
20 20 40 255 0 0
180 20 40 255 255 0
180 180 40 0 255 0
20 180 40 0 0 255"""
C = """400 400
123 231 10 206 119 85
358 316 27 170 47 99
95 317 3 202 42 78
251 269 17 142 150 153
43 120 3 145 75 61
109 376 6 230 231 52
331 78 21 31 81 126
150 330 21 8 142 23
69 155 11 142 251 199
218 335 7 183 248 241
204 237 13 112 253 34
342 89 18 140 11 123"""
D = """400 400
123 231 5 206 119 85
358 316 5 170 47 99
95 317 5 202 42 78
251 269 5 142 150 153
43 120 5 145 75 61
109 376 5 230 231 52
331 78 5 31 81 126
150 330 5 8 142 23
69 155 5 142 251 199
218 335 5 183 248 241
204 237 5 112 253 34
342 89 5 140 11 123"""
E = """100 1"""
for i in (A, B, C, D, E):
    S(i) #S for Star
    O(i) #O for Orb

They all look indistinguishable. The larger ones may take a few seconds to run.

I believe you can save a bunch of bytes by changing for x in r(I[0]):...for y in r(I[1]): by changing it to for x in r(I[0]*I[1]):. You can then take every indent level within down by 1, and replace x with x/I[1] and y with y%I[1].

You could save 5 bytes by replacing from PIL import Image to from PIL import*

Mathematica, 146 bytes
Image@Table[Total[#3{##4}/255&@@@{##2}/(1+#~ManhattanDistance~{x,y}&/@({#1,#2}&@@@{##2}))],{y,0,Last@#-1},{x,0,#&@@#-1}]&@@#~ImportString~"Table"&

A pure function taking a string. To run it in a reasonable amount of time, replace the 1 in 1+#~ManhattanDistance... with a 1.; this forces numeric computation instead of symbolic.
Ungolfed:
Image[
    Table[
        Total[
        (#3 * {##4} / 255 & @@@ {##2})
            / (1 + ManhattanDistance[#, {x, y}]& /@ ({#1, #2}& @@@ {##2}) )
        ], {y, 0, Last[#]-1}, {x, 0, First[#]-1}
    ] (* Header is #, data is {##2} *)
]& @@ ImportString[#, "Table"]&

C, 247 bytes
Not going to win, but I like to golf in C. No external image library used, outputs to stdout in PPM format. Takes input on stdin. Uses Manhattan distance for golfiness.
j,w,h,k,*b,t[6];main(){scanf("%d %d",&w,&h);b=calloc(w*h,24);for(;~scanf("%d",t+j++%6);)for(k=0;j%6?0:k<3*w*h;k++)b[k]=fmin(b[k]+t[2]*t[3+k%3]/(abs(k/3%w-*t)+abs(k/3/w-t[1])+1),255);printf("P6\n%d %d\n255\n",w,h);for(k=0;k<3*w*h;putchar(b[k++]));}

Here's the Euclidean distance variant (257 bytes):
j,w,h,k,*b,t[6];main(){scanf("%d %d",&w,&h);b=calloc(w*h,24);for(;~scanf("%d",t+j++%6);)for(k=0;j%6?0:k<3*w*h;k++)b[k]=fmin(b[k]+t[2]*t[3+k%3]/(sqrt(pow(k/3%w-*t,2)+pow(k/3/w-t[1],2))+1),255);printf("P6\n%d %d\n255\n",w,h);for(k=0;k<3*w*h;putchar(b[k++]));}

CJam, 86 bytes
q~]"P3 "\_2>:T;2<_S*" 255 "@:,~\m*{(+0a3*T6/{_2<3$.-:z~+)d\2>(f*\f/.+}/:i255fe<\;S*S}/

While this may look kind of lengthy for a golfing language, I believe that of the solutions posted so far, it's the shortest that does not use image output functionality. This produces a PPM file in ASCII form. The image below was converted from PPM to PNG using GIMP.
I do not recommend to run the code in the online CJam interpreter. At least not for the full size images. My browser locked up, most likely because of the memory usage. It completes the 400x400 images in the second range with the offline version.

Explanation:
q~      Read and parse input.
]       Wrap it in an array.
"P3 "   Output start of PPM header.
\       Swap input to top.
_2>     Slice off first two values, leaving the star descriptors.
:T;     Store star descriptors in variable T.
2<      Get first two values in input, which is the image size.
_S*     Leave a copy of the size in the output for the PPM header.
" 255 " Rest of PPM header, range of color values.
@       Pop sizes to top.
:,      Expand sizes to ranges.
~       Unwrap size ranges into separate stack elements.
\       Swap ranges, since we need x-range second for Cartesian product.
m*      Generate all coordinate pairs with Cartesian product.
{       Loop over pixel coordinate pairs.
  (+      Swap values in coordinate pair to get x-coordinate first again.
  0a3*    Generate [0 0 0] array. Will be used to sum up colors from stars.
  T       Get list of stars.
  6/      Split into sub-lists with 6 values for each star.
  {       Loop over the stars.
    _2<     Get the first two values (position) of the star.
    3$      Pull current pixel coordinates to top of stack.
    .-      Subtract pixel coordinates from star position.
    :z      Absolute value of difference.
    ~+      Unpack differences and add them to get Manhattan distance.
    )d      Add 1 and convert to double to get denominator of formula.
    \       Swap star values to top.
    2>      Slice off first two values, leaving intensity and color.
    (       Pop off intensity.
    f*      Multiply it with color values.
    \       Swap denominator to top.
    f/      Perform division of color components by denominator.
    .+      Add it to sum of colors.
  }/      End loop over stars.
  :i      Convert double values for colors to integer.
  255fe<  Cap color components at 255.
  \;      Swap pixel coordinate to top and pop it.
  S*S     Join color components with space, and add another space.
}/      End loop over coordinate pairs.

C# 718 bytes
I realize that c# is terrible for golfing, but here's my attempt at 718 bytes
namespace System{using Collections.Generic;using Drawing;using Linq;using O=Convert;class P{int j,i;List<S> s=new List<S>();Image G(string t){var l=t.Replace("\r","").Split('\n');var w=O.ToInt32(l[0].Split(' ')[0]);var h=O.ToInt32(l[0].Split(' ')[1]);for(i=1;i < l.Length;i++){var p=l[i].Split(' ');s.Add(new S{X=O.ToInt32(p[0]),Y=O.ToInt32(p[1]),I=O.ToSingle(p[2]),R=O.ToByte(p[3]),G=O.ToByte(p[4]),B=O.ToByte(p[5])});}var b=new Bitmap(w,h);for(j=0;j<h;j++)for(i=0;i<w;i++)b.SetPixel(i,j,C());return b;}Color C(){return Color.FromArgb(X(x=>x.R),X(x=>x.G),X(x=>x.B));}int X(Func<S,float>f){return(int)Math.Min(s.Sum(x=>x.I*f(x)/(Math.Sqrt((x.X-i)*(x.X-i)+(x.Y-j)*(x.Y-j))+1)),255);}class S{public float X,Y,R,G,B,I;}}}

If anyone has any suggestions to shorten it, feel free to let me know.

You've missed the Color.FromArgb(int, int, int) overload. Would save 4 bytes...

Also, you should probably be using .Length instead of .Count(). one byte less, and more efficient. And by the way, you could save a lot more bytes by using the new expression-bodied members of C#6, if you are willing to.

Good points on both the length and the overload, adjusting now.  And looking into the expression-bodied members.  Haven't seen those before.  Thanks

Python, 259 bytes
Finally done! First code golf I've tried, decided to use Python and went with the Manhattan distance. Shoutout to Maltysen for helping me with the iterators, reduced the total size to almost half!
from PIL.Image import new
N,*s=[list(map(int,i.split()))for i in iter(input,'')]
q,m=new("RGB",(N[0],N[1])),[]
[m.append(tuple(sum(k[2]*k[i]//(abs(k[1]-x)+abs(k[0]-y)+1)for k in s)for i in(3,4,5)))for x in range(N[1])for y in range(N[0])]
q.show(q.putdata(m))

I know there must be a way to make one calculation for all of them, but I honestly don't know Python that well.

Let us continue this discussion in chat.

Your's still doesn't work properly, have to switch the k[0] and k[1] in the calculations.

Took me like 10 minutes to realize why it was working on my machine, turns out I did invert them but forgot to change it here.

CJam, 70 bytes
"P3"l_~\:W*255\,[q~]6Te]6/f{\[Wmd\]f{.-Z/~\)\~mh)/f*}:.+{i255e<}/}~]S*

Euclidean distance, ASCII PPM output. Try it online
It should be possible to squeeze a few more bytes, but I don't want to spend too much time.


text:
Garlandification
Garland Words
A garland word is a word which can be strung together like a garland, because it ends with the same letters it starts with. These groups of letters can even overlap!
For example, underground is a garland word of order 3, because it starts and end with the same 3 characters, und. This means it could be strung together like undergroundergrounderground....
alfalfa is a garland word, too! It's of order 4. It starts and ends with alfa. It can be strung together like so: alfalfalfalfa.
A process which I call garlandifying is where once you determine the order n of a garland word, you take the original word and add the segment required to have it loop as a garland n times. So, since onion is an order 2 garland word, you would take onion, chop off the first 2 letters to get ion and add that to the end 2 times to get onionionion.
Objective
Make a program or function which takes input from standard input or a function argument and prints out or returns the word, garlandified.
All words will be lowercase, and the highest possible order for a word is length(word) - 1.
Example I/O
"onion"       --> "onionionion"
"jackhammer"  --> "jackhammer"
"abracadabra" --> "abracadabracadabracadabracadabracadabra"
""            --> ""
"zvioz"       --> "zviozvioz"
"alfalfa"     --> "alfalfalfalfalfalfa"
"aaaa"        --> "aaaaaaa"

This is code-golf, so least number of bytes wins.

Any N-letter word starts with the same N letters that it ends with. What is the maximum order that should be considered?

@feersum The maximum order is the word's length - 1. Added that to the main post.

Do I have to print out just the garland? or can I perhaps print it and an exception?

@DeadChex There should be no exceptions.

There goes my plan to save a byte...

Does it have to work for arbitrarily long words? Or is there a limit in word length?

@LuisMendo It should work for arbitrarily long words.

@Vioz- pleae clarify how "aaaa" becomes 4a+3a rather than 4a+4a or 4a+6a?

That doesn't seem to match the instructions. if abcd is order 3, shouldn't it end up as abcdbcdbcd instead of aaaabcd?

aha, thanks. I mistook the direction.

For those who are interested, you can search a wordlist for garlands of order, say, 4 or higher with egrep '^(.{4,}).*\1$'.  The best one I found in my list is benzeneazobenzene, of order 7.  Note, though, that this would miss words for which the "head"  and "tail" overlap, like ababa (sadly a proper noun), which should be a garland of order 3 - I'm not sure how to handle that in a regex.

@NateEldredge you can solve this with a lookahead ^(?=(.{4})).+\1$

Pyth, 19 18 bytes
+z*>Kf!xz>zT1zl>zK

Try it online: Demonstration or Test harness
Explanations:
+z*>Kf!xz>zT1zl>zK   implicit: z = input string
     f      1        find the first number T >= 1, which satisfies:
         >zT            all but the first T chars of z
       xz               index of ^ in z
      !                 == 0
    K                store in K
                     the order is length(z) - K
   >K        z       the last K chars
  *                  repeated
              l>zK   len(all but the last K chars) times
+z                   insert z at the beginning

Python, 60 bytes
f=lambda s,i=1:s.find(s[i:])and f(s,i+1)or(len(s)-i)*s[:i]+s

Was hoping for better, but oh well. s.find works neatly here in place of not s.startswith.

Retina, 58 bytes
.+
$0#$0
(.*)(.+)#.*\1$
$0#$1#$2-
+`\w#(\w*)-
#$1-$1
#.*-
<empty line>

Each line should go to its own file but you can run the code as one file with the -s flag.
The four substitution pairs do the followings:

Duplicate word so we can search for overlaps too.
Append the word split up at order number of characters.
Append the last part order times.
Keep the original word and the lastly appended part and drop everything else.

The string states for the example onion:
onion
onion#onion
onion#onion#on#ion-
onion#onion##ion-ionion
onionionion

Haskell, 64 bytes
g s=[b>>a|(a,b)<-map(`splitAt`s)[1..],and$zipWith(==)s b]!!0++s

Tests:
λ: g "onion"       == "onionionion"
True
λ: g "jackhammer"  == "jackhammer"
True
λ: g "abracadabra" == "abracadabracadabracadabracadabracadabra"
True
λ: g ""            == ""
True
λ: g "zvioz"       == "zviozvioz"
True
λ: g "alfalfa"     == "alfalfalfalfalfalfa"
True
λ: g "aaaa"        == "aaaaaaa"
True

Java, 160 157 bytes
static void g(String s){int i=s.length(),o;for(String p=s;i-->0;)if(s.endsWith(s.substring(0,i))){for(o=i;o-->0;)p+=s.substring(i);System.out.print(p);i=0;}}

Input/Output:
 g("abracadabra"); --> "abracadabracadabracadabracadabracadabra"

Spaced and tabbed for readability:
static void g(String s){
int i=s.length(),o;
for(String p=s;i-->0;)
    if(s.endsWith(s.substring(0,i))){
        for(o=i;o-->0;)
            p+=s.substring(i);
        System.out.print(p);
        i=0;
    }
}

Suggestions welcome.

As a note to my self, the String ops can be moved into the for loop to save a byte or two on semicolons

why not do i=0; ?

@overactor where? The reason I use the length is because I want the full String and then I want to move towards none of it, with substring I don't think I can avoid using it in this method and will take the byte penalty for it

I meant to break out of the outer for loop.

Sed: 87 84 characters
(83 characters code + 1 character command line option.)
h
s/(.*)./& \1/
T
s/(.+) \1.*/ \1 \1/
t
g
q
:
s/^([^ ]+)(.*)[^ ]$/\1 \1\2/
t
s/ //g

Sample run:
bash-4.3$ sed -r 'h;s/(.*)./& \1/;T;s/(.+) \1.*/ \1 \1/;t;g;q;:;s/^([^ ]+)(.*)[^ ]$/\1 \1\2/;t;s/ //g' <<< 'underground'
undergroundergroundergrounderground

Automatic upvote of sed answer ;-). Follow this tip to drop 2 chars from your label definition and branch

Tried, but I am afraid that advice is only for cases when you not have label-less jumps to the end of code. [A bit later…] Ok, thinking again, why I tried to process multiple input lines at once?

CJam, 24 23 bytes
q_:Q,{~)Q>Q\#!},W>~_Q>*

q_:Q                       e# Read the input, take a copy and store it in Q too
    ,{        },           e# Take the length of the input and filter [0 .. len - 1] array
      ~)                   e# Same as number * -1
        Q>                 e# Take last number characters. Call this string S
          Q\#!             e# See if Q starts with S. After the filter, we will only have
                           e# those numbers from [0 .. len - 1] array which are valid orders
                W>~        e# Take the last order number, if exists.
                   _Q>*    e# Garlandify the input order times.

Just to start it with something..
Try it online here

Matlab: 97 89 82 bytes
Function that uses a regular expression with lookbehind and a capture group:
function t=f(s)
n=sum(regexp(s,'(.*$)(?<=^\1.+)'))-1;t=[s(repmat(1:n,1,end-n)) s];

That sum is needed to handle the empty-string input (convert [] into 0).
Examples:
> f('onion'), f('jackhammer'), f('abracadabra'), f(''), f('zvioz'), f('alfalfa'), f('aaaa')
ans =
onionionion
ans =
jackhammer
ans =
abracadabracadabracadabracadabracadabra
ans =
   Empty string: 1-by-0
ans =
zviozvioz
ans =
alfalfalfalfalfalfa
ans =
aaaaaaa

REGXY, 53 49 bytes
Uses REGXY, a regex substitution based language
//$'#/
/.(.+)#\1\K/#/
a/(#).(.*#)|#.*/$'$1$2/
//a

Overview:
A number of regular expressions are applied. An example run would look like:
onion (input)
onion#onion (line 1 regex)
onion#on#ion (line 2 regex - find the repeated section and separate with #)
onionion#n#ion (line 3 regex - the length of the middle token is the garland order, remove a character and append the third token onto the original string on the left)
onionionion##ion (line 4 regex is a pointer to line 3 - repeat the previous again)
onionionion##ion (line 4 regex is a pointer to line 3 - strip everything after and including the #)

Detailed explanation
The following is a line by line breakdown of the regexes:
//$'#/

This is a regex substitution which matches the first empty string (i.e. the start of the string) and replaces it with everything to the right of the match ($') followed by a hash. For example, it will turn onion into onion#onion.
/.(.+)#\1\K/#/

This line finds the section which overlaps by looking for a group of characters immediate preceding the # ((.+)) which are the same on the other side of the # (\1). The \K just means 'forget that I matched anything', meaning it will not actually be replaced in the substitution. This effectively, this means we just add a # to the position after the overlap has been found, turning onion#onion into onion#on#ion.
a/(#).(.*#)|#.*/$'$1$2/

The initial 'a' is just a label for the regex. After this, we find the first # followed by a single character (.) and capture everything after this until the next # (.*#). We replace this with everything to the right of the match, i.e. the last token ($'), followed by a # ($1), followed by the second token less a character (we treat this as a counter, decreasing it each iteration). In the case of onion#on#ion, the two tokens we backreference on are shown in brackets, and the section the entire regex matches is between the pipes: onion|(#)o(n#)|ion. We then replace the bits we match (between the pipes) with $' (everything to the right of the match, i.e. 'ion'), then $1 (the #), then $2 (n#), meaning we end up with onion|(ion)(#)(n#)|ion (brackets show the three tokens in the replacement string).
If the regex fails to match in the first alternation (everything before the pipe), we must have decreased our counter to zero, meaning there are no characters inside the second token. Instead, we look at the second part of the pattern, #.*. This simply replaces everything after the first # with $'$1$2. Since there are no backreferences created by this alternation, and there is nothing to the right of the match (.* matches until the end of the string), we terminate the match and return the result.
//a

This is just a pointer to the previous line, ensuring we continue to execute the regex substitution until it fails to match any more.

jq 1.5: 91 characters
(87 characters code + 4 characters command line option.)
.+. as$t|[range(1;length)|select($t[:.]==$t[-.:])]|(max//0)as$i|[range($i)|$t[$i:]]|add

Sample run:
bash-4.3$ jq -R -r -f judy.jq <<< 'underground'
undergroundergroundergrounderground

rs, 51 48 bytes
(.+)/\1 \1
(.+)(.+) .+\1$/\1(\2)^^((^^\1_))
 .*/

TAKE THAT, RETINA AND SED!!!!! ;)
Cut off 3 bytes thanks to @randomra.
Live demo and test cases.
Note that the jackhammer test case is not there. There's a bug in the handling of spaces in the web interface that causes it to print incorrect output. The offline version of rs handles it correctly.
51-byte version:
(.+)/\1 \1
^(.+)(.+) (.+)\1$/\1(\2)^^((^^\1_))
 .*/

Live demo and test cases for original.

JavaScript (ES6), 95 bytes
f=s=>{for(e=i=s.length;i&&e;)s+=s.slice(--i).repeat(!(e=!s.endsWith(s.slice(0,i)))*i);return s}

Demo
Firefox only for now:

f = s => {
  for (e = i = s.length; i && e;) s += s.slice(--i).repeat(!(e = !s.endsWith(s.slice(0, i))) * i);
  return s
}

console.log = x => X.innerHTML += x + '\n';

console.log(f('onion'));
console.log(f('jackhammer'));
console.log(f('abracadabra'));
console.log(f(''));
console.log(f('zvioz'));
console.log(f('alfalfa'));
console.log(f('aaaa'));

JavaScript (ES6), 82 bytes
g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i)

[Deleted my original answer, because I've now learned ES6 and was interested in finding a recursive solution to this challenge]
Example

g=(s,i=t=s.length)=>s.endsWith(c=s.slice(0,--i))?c+s.slice(i-t).repeat(i+1):g(s,i)

console.log(g('onion'));
console.log(g('jackhammer'));
console.log(g('abracadabra'));
console.log(g(''));
console.log(g('zvioz'));
console.log(g('alfalfa'));
console.log(g('aaaa'));

Vyxal, 14 13 bytes
ÞKvḟǓṘ†Tt~ȯẋJ

Try it Online! (test suite)
Explanation:
ÞKvḟǓṘ†Tt~ȯẋJ # whole program

ÞK            # get all suffixes of implicit input
  vḟ          # then find each first occurrence in the input
    Ǔ         # rotate the list to the left
     Ṙ        # then reverse
      †       # logical NOT each item
       T      # get indices of elements which are truthy
        t     # get tail
          ȯ   # slice the input from it until the end
         ~    #  just push it, do not pop the used items yet
           ẋ  # repeat the sliced input tail amount of times
            J # then join with the input

CoffeeScript + ES6, 77 bytes
Same approach as my JavaScript answer.
f=(s,e=i=s.length)->s+=s[i..].repeat !(e=!s.endsWith s[...i])*i while--i&&e;s

C
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    char *str   = NULL;
    char *p     = NULL;
    int len     = 0 ;
    int i       = 0;
    int j       = 0;
    int k       = 0;
    int loop    = 0;

    if (argc == 1 )
        return 0;

    str = argv[1];
    len = strlen(str);

    if (len %2) {
        loop = len/2 + 1;
    }
    else {
        loop = len/2;
    }

    p = &str[len/2];
    for (i = 0; i < loop ; i++) {
        if (str[k] == *(p++)) {
            k++;
        }
        else
            k = 0;
    }

    printf("k = %d\n", k);
    printf("%s", str);
    p = &str[k];
    for (j =0; j < k ; j++) {
        printf("%s", p);
    }
    return 0;
}

Golfed: 195 bytes - GCC
main(int c,char**a){
char *s=a[1],*p;int i=0,j=0,k=0,z,l=strlen(a[1]);
z=l%2?-~(l/2):l/2;p=&s[l/2];
for(;i<z;i++)k=s[k]==*(p++)?-~k:0;
printf("k=%d\n",k);puts(s);p= &s[k];
for(;j<k;j++)puts(p);}

Welcome to Programming Puzzles and Code Golf! This question is code golf, so I suggest that you "golf" your code by removing unnecessary whitespace, etc., and then include the byte count of your code in the title of your post along with the language.

Got it. Thank you for the direction. I will keep it in mind next time.

It's not too late to "golf" it. If you click on the "edit" button underneath your answer, you could still remove the unnecessary whitespace and add a byte count.

Isn't int implicit in (sufficiently old versions of) C?

Groovy 75 57 55 bytes
f={w->x=w;w.find{x-=it;!w.indexOf(x)};w+(w-x)*x.size()}

Amazing how coming back to something the day after can help
Ungolfed:
f = {w ->

//Set x equal to w
    x=w

//Loop through the characters of w until we return true
    w.find {

//set x equal to x minus the first instance of the current character, i.e.     the word minus the first character
        x-=it

//Returns the index of the first occurance of the string of chars x, when this is 0 (false) we want to return true, so negate it
        !w.indexOf(x)
    }

//When we've escaped the loop, if we've found a match return the word plus the word minus the match multiplied by the lengh of the match.
    w+(w-x)*x.size()
}

Ruby, 75 bytes
->s{t=(1...s.size).map{s[_1..]}.find{s[/^#{_1}/]}
t ?s+s[(o=t.size)..]*o:s}

Attempt This Online!

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:
Given the names of two planets, give the distance
Using the following table (source) write some code that takes the names of two planets and returns the distance between them:
+-------------------+---------------+
|      Planets      | Distance (km) |
+-------------------+---------------+
| Mercury -> Venus  |      50290000 |
| Venus -> Earth    |      41400000 |
| Earth -> Mars     |      78340000 |
| Mars -> Jupiter   |     550390000 |
| Jupiter -> Saturn |     646270000 |
| Saturn -> Uranus  |    1448950000 |
| Uranus -> Neptune |    1627450000 |
| Neptune -> Pluto  |    1405380000 |
+-------------------+---------------+

Examples, input then output:
Mercury, Mars
170030000

Neptune, Jupiter
-3722670000

Earth, Earth
0

Note the negative sign there, as Jupiter comes before Neptune. They are also all integers.
Pluto doesn't have to be included (mostly because of a weird orbit which makes it hard to work out the distance - that distance given is my own calculation, but as Pluto is all famous now...).
By distances between planets I'm meaning orbits - I don't expect a date and working out where they are.
This is code golf, shortest code wins.

+1 for not "coz Pluto ain't a planet"

@Optimizer I'm doing a project which needs the distances and nobody can agree! I resorted to using it's orbital period and orbital speed...

Can our function/program return a float? i.e. Mercury, Mars -> 170030000.0?

@Vioz- I'm gonna say no, they're all integer distances.

It's implied, but are we assuming the holy moment in time where the planets are all in a straight line and the distance between any two non-adjacent planets is the sum of distances in between?

@Sp3000 yes. will clarify

Is there a penalty for including Pluto (besides the bytes)? I feel kinda bad for it, it just had it's big day and all...

@DeadChex no penalty :) I'll add it onto the table

@Sp3000 It doesn't have to be a holy moment as the distances are pairwise.

I'm testing something right now, since Python will attach an L to a value that's too large, is it OK if I return something like -3722670000L?

@Vioz- yeah that's fine.

do you care about the orbits' eccentricity? or assume circular orbits? edit nvm i read the link to the data source

@Plato use the distances provided. They're circular orbits here.

Is the input guaranteed to be a valid planet?

@kirbyfan64sos yes

CJam, 54 51 44 bytes
2{"X84VT:Z/3KD'Y->>6\ Ta "3/r26b93%=70be4}*-

Try it online in the CJam interpreter.
Idea
We use a simple hashing function to identify all eight planets. By considering each name as the array of its code points, converting them from base 26 to integer and taking the result modulo 93 then modulo 8, Mercury, Venus, Earth, etc. map to 2, 4, 0, 1, 3, 5, 6 and 7.
Now, we choose a point that lies 320,000 km behind Neptune and calculate the distances of all eight planets to that point. After dropping four trailing zeroes and reordering the planets so that they fit the 8 indexes from above, we obtain the array
[435172 427338 444341 372299 439312 307672 162777 32]

which, if we encode each integer in base 70, yields the following:
[
   [1 18 56 52] [1 17 14 58] [1 20 47 51] [1 5 68 39]
   [1 19 45 62] [  62 55 22] [  33 15 27] [       32]
]

Remembering that two adjacent digits (A B) can be replaced with ((A-1) (B+70)), we can modify the array from above so that all integers can be encoded as printable ASCII characters:
["X84" "VT:" "Z/3" "KD'" "Y->" ">6\\" " Ta" " "]

Code
2{                         e# Do twice:
  "X84VT:Z/3KD'Y->>6\ Ta " e#   Push that string.
  3/                       e#   Chop it into chunks of length 3.
  r                        e#   Read a token from STDIN.
  26b                      e#   Convert from base 26 to integer.
  93%                      e#   Take the result modulo 93.
  =                        e#   Retrieve the chunk at that index.
  70b                      e#   Convert from base 70 to integer.
  e4                       e#   Multiply by 10,000.
}*                         e#
-                          e# Subtract the two results.

Python 2, 149 147 142 138 128 123 119 Bytes
Just uses a simple lookup to figure out which distances to use :) This defines an anonymous function, so to use it you'll need to give it a name.
Thanks to Sp3000 for ideas that saved a bunch of bytes!
lambda*x:int.__sub__(*[[0,5029,9169,17003,72042,136669,281564,444309]['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x])*~9999

Indented properly and ungolfed slightly for readability:
def f(*x):
 d=0,5029,9169,17003,72042,136669,281564,444309
 a,b=[d['MeVeEaMaJuSaUr'.find(k[:2])/2]for k in x]
 print(b-a)*10000

Call like so:
f("Mercury","Mars")    -> 170030000
f("Neptune","Jupiter") -> -3722670000L

Your output is missing a 0, but you seem to be multiplying by the right amount.

@Tim I messed up in the example call, it does have a fourth 0 at the end :P

You are forgetting pluto?

@Will Pluto doesn't have to be included...

(You'll save at least two bytes if you copy that find returning -1 trick from my entry, and then you'll pull ahead of me :)

@Will If you look at the golfed code, you'll notice that Neptune is actually missing from the .find string. For some reason it's in the ungolfed code though.

I'm not doing so well with my attention to small details :)

Prolog, 190 174 151 bytes
Thanks to Fatalize for guidance.
g(A,X):-sub_atom(A,2,2,_,B),member(B:X,[rc:0,nu:5029,rt:9169,rs:17003,pi:72042,tu:136669,an:281564,pt:444309]).
s(A,B,R):-g(A,X),g(B,Y),R is(Y-X)*10^4.

$ gprolog --consult-file src.pro
| ?- s('Mercury','Mars',R).
R = 170030000 ?
yes
| ?- s('Neptune','Jupiter',R).
R = -3722670000 ?
yes
| ?- s('Earth','Earth',R).
R = 0 ?
yes

Why don't you return this result directly like this s(A, B, R) instead of writingR? Nothing is specified for outputs so a predicate return should be fine.

You can also shave off 22 bytes by modifying predicate g to g(A,X):-sub_atom(A,2,2,_,B),member(B:X,[rc:0,nu:5029,rt:9169,rs:17003,pi:72042,tu:136669,an:281564,pt:444309]). and removing all facts for planets. It's less cool than =.. but it's shorter to get a key-value mapping

Java, 274 272 264 bytes (includes Pluto!)
  void p(String p,String l){String q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(p.substring(0,2))/2,e=q.indexOf(l.substring(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};long h=0;if(w>e){e=w;w=t;m=-1;}for(;e-->w;)h+=d[e]*1e4;System.out.print(h*m);}

Input/Output:
p("Mercury","Mars") --> 170030000
p("Mars","Mercury") --> -170030000
p("Earth","Earth")  --> 0

Spaced and tabbed:
void p(String p,String l){
    String q="MeVeEaMaJuSaUrNePl";
    int w=q.indexOf(p.substring(0,2))/2,
      e=q.indexOf(l.substring(0,2))/2,
      m=1,
      t=e,
      d[]={5029,4140,7834,55039,64627,144895,162745,140538};
    long h=0;
    if(w>e){
        e=w;
        w=t;
        m=-1;
    }
    for(;e-->w;)
        h+=d[e]*1e4;
    System.out.print(h*m);
}

You could cut off a lot by dividing all numbers by 1000

Just about to do that!

Fixed the Overflow and Neptune being missing

You can also put both the int and int[] declarations on one line if the array comes last: Like int i=0,j=1,k[]={};

You can shave off two bytes by replacing 10000 with 1e4.

since we know e > w you can trim a character using the goes to operator: while(e-->w) which is 12 characters, instead of for(;e--!=w;) which is 13.

@corsiKa Having m=1e4 is a type error. 1e4 is a double whereas m is an int Thanks for the other suggestions though!

@corsiKa Sorry, but I don't see where I can drop the /2s. From what I understand, I need both w and e to be halved before the start of the For loop, otherwise I'll have too many iterations.

Ah, correct you are.

since you're only using String p and String l once each, you can actually save 1 byte by using varargs String...p and using s[0].substring(0,2) and s[1].substring(0,2).

JavaScript (ES6), 115 110 bytes
(x,y,g=k=>"Me0Ve5029Ea9169Ma17003Ju72042Sa136669Ur281564Ne444309".match(k[0]+k[1]+"(\\d*)")[1]*1e4)=>g(y)-g(x)

This is an anonymous function, so you will need to store it in a variable (f=...; f("Earth", "Mercury")) or use it as a parenthesised expression ((...)("Earth", "Mercury").
That messy string is the first two letters of each planet, followed by that planet's distance from Mercury (divided by 10000, to save space). The inner function g does the following:

takes a name (k),
reduces it to the first two letters (k[0]+k[1]),
uses a regex match to find the corresponding distance from Mercury, divided by 10000 (e.g., the "Earth" regex looks like Ea(\d*)),
multiplies the value by 10000 (1e4) and returns the result.

By subtracting one Mercury-distance from the other, we get the distance between the planets.

@vihan1086 Aha, I have made the classic blunder of confusing code-point-value with actual byte representation :(

UTF-8 is just the wrong encoding for this trick. All characters returned by btoa have code points below 256, so ISO 8859-1 will encode each character using a single byte.

APL, 97 95 85 bytes
{1E4×-/(0 5029 9169 17003 72042 136669 281564 444309[{⍵≡'Mars':4⋄'MVEmJSUN'⍳⊃⍵}¨⍵⍺])}

This creates an unnamed dyadic function that takes the origin planet as the left argument and the destination planet as the right.
You can try it online!

Python, 118 bytes
n=lambda x:(5029,9169,17003,72042,136669,281564,444309,0)["VeEaMaJuSaUrNe".find(x[:2])/2]*10000
f=lambda a,b:n(b)-n(a)

n is a function that returns distance from Mercury.
The string "VeEaMaJuSaUrNe" is the first two characters of all planet names except Mercury.  find cannot find Mercury so will return -1. -1/2 is still -1 so this is the last element in the tuple, which is 0.
Simple test code:
test = (
    ("Mercury","Venus",50290000),
    ("Venus","Earth",41400000),
    ("Earth","Mars",78340000),
    ("Mars","Jupiter",550390000),
    ("Jupiter","Saturn",646270000),
    ("Saturn","Uranus",1448950000),
    ("Uranus","Neptune",1627450000),
    #("Neptune","Pluto",1405380000),
    ("Mercury","Mars",170030000),
    ("Neptune","Jupiter",-3722670000),
    ("Earth","Earth",0))

for a, b, expect in test:
    print a, "->", b, "=", expect
    assert f(a, b) == expect, f(a, b)

Nice trick there.

J--, 226 bytes

main{str q="MeVeEaMaJuSaUrNePl";int w=q.indexOf(a[0].subs(0,2))/2,e=q.indexOf(a[1].subs(0,2))/2,m=1,t=e,d[]={5029,4140,7834,55039,64627,144895,162745,140538};lg h = 0;@i(w>e){e=w;w=t;m=-1;}@f(;e--^^w;)h+=d[e]*10000;echo(h*m);}
I don't think this counts as I was making the language while the question was out, but it was mostly a test of how small I could compress Java code. This is totally and completely based off DeadChex's answer.
Here's how to use it:
$ j-- planets.j-- Mercury Mars
170030000

Pyth - 59 53 bytes
Encodes the distance in unicode codepoints.
-Fm*^T4s<CM"Ꭵာẚ훿ﱳ"x"MshrJtaN"@d14_Q

The name lookup is kinda cool because it loops around. Thanks to @Dennis for suggesting index 14 as a collision free lookup!
Try it here online.

I used index 14 in my first revision. It is collision-free.

CoffeeScript, 183 180 bytes
f=(a,b)->t=[d=0,5029,4140,7834,55039,64627,144895,162745];n='MeVeEaMaJuSaUrNe';t=(x=n[q='indexOf'](a[..1])/2)<(y=n[q](b[..1])/2)&&t[x+1..y]||t[y+1..x];d+=c*1e4for c in t;x>y&&-d||d

Unminified:
f = (a,b) ->
 t = [d = 0, 5029, 4140, 7834, 55039, 64627, 144895, 162745]
 n = 'MeVeEaMaJuSaUrNe'
 t = if (x = n[q='indexOf'](a[..1]) / 2) < (y = n[q](b[..1]) / 2) then t[x+1..y] else t[y+1..x];
 d += c * 1e4 for c in t
 if x > y then -d else d

Haskell, 160 158 157 bytes
data P=Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune deriving Enum
d x=[0,5029,9169,17003,72042,136669,281564,444309]!!fromEnum x
x#y=(d y-d x)*10^4

Usage example:
*Main> Neptune # Jupiter
-3722670000

*Main> Mercury # Mars
170030000

How it works: I define a new data type P where the constructor names are the names of the planets. I also put it in the Enum class, i.e. I get a mapping to integers via fromEnum (in order of definition, starting with Mercury -> 0). This integer can be used as a index for the distance list.
Edit: @Kritzefitz found two bytes to save and @Alchymist another one. Thanks!

You can remove the parentheses around fromEnum x and save two bytes.

Can you use 10^4 instead of 10000 or will that affect the output?

@Alchymist: yes, it's possible. Thanks!

Bash, 140 bytes
bc<<<"(-`sed -e 's/,/+/;s/[abd-z]//g;s/Mc/0/g;s/V/5029/g;s/E/9169/g;s/M/17003/g;s/J/72042/g;s/S/136669/g;s/U/281564/g;s/N/444309/g'`)*10^4"

$ bash script.sh
Mercury, Mars
170030000
$ bash script.sh
Neptune, Jupiter
-3722670000
$ bash script.sh
Earth, Earth
0

Ruby, 168 bytes
a=ARGV.map{|e|e=='Mars'?3:%w(M V E m J S U N P).index(e[0])}
p 10000*(a[1]<=>a[0])*[5029,4140,7834,55039,64627,144895,162745,140538][a.min..a.max-1].inject(0){|r,e|r+e}

It's designed as a script to be run from command line, thus uses ARGV.
Run as
$ ruby planets.rb Mercury Mars
170030000
$ ruby planets.rb Neptune Jupiter
-3722670000
$ ruby planets.rb Earth Earth
0
$ ruby planets.rb Mercury Venus
50290000
$ ruby planets.rb Venus Earth
41400000
$ ruby planets.rb Mercury Mercury
0
$ ruby planets.rb Pluto Pluto
0
$ ruby planets.rb Mercury Pluto
5848470000
$ ruby planets.rb Pluto Mercury
-5848470000

Julia, 206 203 190 bytes
(f,t)->t==f?0:(M(p)=p=="Mars"?4:findin("MVEmJSUN",p[1])[1];T=M(t);F=M(f);(T>F?1:-1)*sum([get(Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])),i,0)for i=T>F?(F:T-1):(T:F+1)])*1000)

This creates an unnamed function that accepts two strings and returns an integer. To call it, give it a name.
Ungolfed + explanation:
function planet_distance(p_from, p_to)
    if p_from == p_to
        # Return 0 right away if we aren't going anywhere
        0
    else
        # Define a function to get the planet's order in the solar system
        M(p) = p == "Mars" ? 4 : findin("MVEmJSUN", p[1])[1]

        # Get indices for origin and destination
        ind_from = M(p_from)
        ind_to = M(p_to)

        # Define a dictionary to look up distances by index
        D = Dict(zip(1:8,[5029,4140,7834,55039,64627,144895,162745,0])

        # Determine whether the distance will be positive or negative
        # and the range over which we'll sum distances
        if ind_to > ind_from
            coef = 1
            range = ind_from:ind_to-1
        else
            coef = -1
            range = ind_to:ind_from+1
        end

        # Sum the distances between points
        coef * sum([get(D, i, 0) for i in range]) * 1000
    end
end

Java, 257 228 bytes
enum Z{Mercury(0),Venus(5029),Earth(9169),Mars(17003),Jupiter(72042),Saturn(136669),Uranus(281564),Neptune(444309),Pluto(584847);long r;Z(long x){r=x*10000;}static long d(String...s){return Z.valueOf(s[1]).r-Z.valueOf(s[0]).r;}}

static long d(String...s){...} solves the challenge. Input requires names of planets to match the enum's constants' names exactly. I love how java provides a string to enum conversion method for me <3
Usage:
Z.d("Mercury","Pluto") returns 5848470000
Z.d("Pluto","Mercury") returns -5848470000
Z.d("Uranus","Neptune") returns 1627450000
Z.d("Mars","Pluto") returns 5678440000

C (gcc) pre-processor macro, 146 bytes
char*p="(3$,?2'+";D[]={0,5029,9169,17003,72042,136669,281564,444309,584847};
#define E(x)D[strchr(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL

Try it online!
Another version, courtesy of ceilingcat, using Unicode, which seems to make TiO count weirdly:
C (gcc), 119 bytes
char*p="(3$,?2'+";
#define E(x)L"\0Ꭵ⏑䉫"[index(p,*x^x[1])-p]
#define f(s,t)(E(t)-E(s))*10000LL

Try it online!

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


text:
Numbering Hierarchical Outlines
Write a program that takes in a string where every line consists of the character 0 indented by some number of spaces. The top line is not indented and every other line will be indented by at most one more space than the line just before it.
No lines will have trailing spaces but you may optionally assume there is a single trailing newline.
For example, the input might look something like this:
0
 0
  0
  0
 0
0
 0
 0
 0
  0
0
 0
  0
  0

Your task is to number it like a hierarchical outline, using increasing positive integers as the line headers. This would be the output for the example:
1
 1
  1
  2
 2
2
 1
 2
 3
  1
3
 1
  1
  2

Note how every hierarchical indentation level has its own set of increasing numbers, even if they only go up to one.
In the output, there should be no trailing spaces, but there may optionally be a single trailing newline.
Write a full program that takes the input string via stdin or command line, or write a function that takes the string in as an argument. Print the result or return it as a string.
The shortest code in bytes wins.
Examples
If the empty string is input, the empty string should be output.
The next most trivial example is the input
0

which should become
1

Large example - Input:
0
 0
  0
 0
  0
 0
  0
  0
   0
   0
    0
     0
     0
     0
     0
    0
   0
    0
    0
  0
0
 0
  0
 0
  0
  0
  0
  0
  0
  0
  0
  0
  0
  0
  0
   0
    0
     0
  0
   0
0
0
0
 0
  0
   0
    0
     0
      0
      0
     0
    0
   0
  0
 0
  0
  0
   0
   0
0
0

Output:
1
 1
  1
 2
  1
 3
  1
  2
   1
   2
    1
     1
     2
     3
     4
    2
   3
    1
    2
  3
2
 1
  1
 2
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
   1
    1
     1
  12
   1
3
4
5
 1
  1
   1
    1
     1
      1
      2
     2
    2
   2
  2
 2
  1
  2
   1
   2
6
7

Pyth, 18 bytes
V.z+PNhX0=Y>lN+0Y1

This is an exact translation of @Sp3000's answer. I tried many different approaches and variations, but I couldn't shorten it, so I am marking this CW.
Demonstration.

Python 2, 77
S={'0':0}
for w in input().split('\n'):S[w]+=1;S[' '+w]=0;print w[:-1]+`S[w]`

Like Sp3000's answer, but with a dictionary. The dict S stores the current number for each nesting level '0', ' 0', '  0' and so on. For each line in the input, increment the corresponding nesting level, and reset the nesting level one higher to 0.

Python 2, 86 85 81 bytes
S=[]
for r in input().split("\n"):S=([0]+S)[-len(r):];S[0]+=1;print r[:-1]+`S[0]`

(-5 bytes thanks to @xnor)
Takes input as a string via STDIN, e.g.
'0\n 0\n  0\n  0\n 0\n0\n 0\n 0\n 0\n  0\n0\n 0\n  0\n  0'

Alternatively, here's a function for 5 extra bytes:
def f(I,S=[]):
 for r in I.split("\n"):S=([0]+S)[-len(r):];S[0]+=1;print r[:-1]+`S[0]`

I found that you can save some chars by taking in each line as a string of spaces so you can print those spaces directly S=[]\nfor w in input()[:-1].split('0\n'):S=([0]+S)[~len(w):];S[0]+=1;print w+`S[0]`

Actually, it's a bit shorter to take in the line directly: S=[]\nfor w in input().split('\n'):S=([0]+S)[-len(w):];S[0]+=1;print w[:-1]+`S[0]` .

@xnor Thanks again - that's a lot simpler :)

CJam, 25 bytes
LqN/{0+I,<))_IW@toNo+}fI;

Like my Python answer, this uses an array to store which number each indentation level is up to. One difference, however, is that this uses t (array set) to replace the 0 on each line with the number we want.
Try it online.

JavaScript ES6, 83 81 bytes
f=(z,a=[])=>z.replace(/ *0/g,e=>e.replace(0,a.fill(0,l=e.length)[--l]=a[l]+1||1))

This uses an array that holds the current number for each indentation level. Everything past that level is reset to 0 using fill(). EDIT: 2 bytes saved thanks to vihan1086's tip.
The Stack Snippet below can be used for testing because it is ungolfed slightly and uses better-supported ES5 syntax. The second function is a polyfill for fill() as there is not a short way to do it without ES6.

f=function(z){
  a=[]
  return z.replace(/ *0/g,function(e){
    return e.replace(0,a.fill(0,l=e.length)[--l]=a[l]+1||1)
  })
}

if(!Array.prototype.fill){
  Array.prototype.fill = function(val, start){
    var res = this;
    for(var i = start; i<this.length; i++){
      res[i] = val;
    }
    return res;
  };
}

run=function(){document.getElementById('output').innerText=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
<textarea id="input" rows="15" cols="10">
0
 0
  0
  0
 0
0
 0
 0
 0
  0
0
 0
  0
  0</textarea>

<button id="run">Run</button>

Python - 191
def p(s,i,v,n=1):
    while i<len(s)and s[i]and'0'not in s[i][:v]:
        if s[i][v]=='0':s[i]=' '*v+str(n);n+=1;i+=1
        else:i=p(s,i,v+1)
    return(s,i)[v!=0]
z=lambda r:'\n'.join(p(r.split('\n'),0,0))

The function is z.

Pip -rn, 31 27 bytes
{Wl#<alPU0l@>:-#aaR0++@l}Mg

Input from stdin. Try it online!
Explanation
                             g is list of lines of stdin (-r flag); l is []
                             Note that l is a global variable
{                       }Mg  Map this function to each a in g:
 Wl#:                Slice and assign back to l...
              -#a              ... its last len(a) elements
                              (This handles decreasing the indent)
                 aR0          In a, replace 0 with
                      @l       the first element of l
                    ++         incremented in-place
                              The function returns the above expression
                             The resulting list from map is printed, newline-separated
                              (-n flag)


text:
Alphabet Between Encryption
You must write a program that encrypts an input into a string of characters.
For every character i in the input up to the second to last character, take the i and i+1 characters and encode them by writing the letters of the alphabet, in order, that range in the same direction between those chosen characters.
For example: if the original string were bo then it would be encoded as cdefghijklmn, but if the string were boa then bo is encoded as cdefghijklmn and oa is encoded as nmlkjihgfedcb with the final encrypted string being cdefghijklmnnmlkjihgfedcb.
If the original string contain zero letters between two chosen characters, such as the string ab then you should encrypt it as aRb with R standing for what direction in the alphabet to go in determining the original characters. The encrypted string aRb represents ab but the encrypted string aLb represents ba (R = right, L = left).
If two chosen characters in the original string are the same, such as the string tt, then you should encrypt it as tZt with Z standing for zero letters in between.
Examples:
Input: att Output: bcdefghijklmnopqrstZt
Input: brep Output: cdefghijklmnopqqponmlkjihgffghijklmno
Input: Optimizer Output: oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq
Rules:

You can write a program or a function.
Your input may contain uppercase letters, so you need to put them all to lowercase before encrypting.
You can ignore non-alphabet characters.
One character length strings are undefined.
Shortest code in bytes wins!

I'm not sure I quite get all the rules - what's the expected output for aabbcfcBBAa?

Is "ab" encrypted as "aZb"? Is "aa" encrypted as "aZa"?

@Sp3000 aZa aRb bZb bRc de ed cRb bZb bLa aZa without any spaces.

@MtnViewMark ab = aRb, aa = aZa

What should the output be for the input a?

@Doorknob That is undefined, meaning it doesn't matter.

Does "You can ignore non-alphabet characters." mean that we can expect the input to be letters only or can the input have non-letters and we have to filter them out?

shouldn't cB in @Sp3000's test be encoded cLb not cRb?

@MtnViewMark Yes, I messed up.

@phase In your question, you wrote that the encrypted string aLb represents ba. This mean that the letters are always ordered alphabetically and cLb or bLa is invaild.

Pyth, 38 bytes
M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2

Demonstration.
M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2
                                          Implicit: z = input(), Z = 0
                                          g is a function of a 2 letter string
                                          and an insert letter.
M                                         def g(G, H): return
    rFG                                   Take the string range between the
                                          letters in G.
   t                                      Remove the first letter to get just
                                          the letters in between.
  s                                       Concatenate.
 |                                        Logical or (if nothing in between)
       jHG                                H.join(G)
                                  rzZ     Convert input to lowercase.
                                .:   2    Take 2 letter substrings.
           m                              Map d over the substrings
            ?>Fd                          If the first character of `d`
                                          is greater than the second,
                 _g_\L                    g(d[::-1], 'L')[::-1]
                      gd                  else, g(d,
                        ?qFd              if the letters of d are the same,
                            \Z            'Z'
                              \R          else 'R')
          s                               Concatenate and print.

C - 161 Bytes - GCC
#define y(x) putchar(x)
main(_,z){for(_=getchar();-~(z=getchar());_=z)for(_==z?y(_),y(90),y(z):-~_==z?y(_++),y(82),y(z):_==-~z?y(_),y(76),y(z):_;_<z;y(_),_++);}

Will update when I get it shorter

JavaScript ES6, 253 bytes
(d,y=`abcdefghijklmnopqrstuvwxyz`)=>[...`${d}`.toLowerCase()].map((l,i,a,m=a[i-1],c=s=>y.search(s),d=(s,e)=>y.slice(c(s),c(e)).slice(1),j=c(m),k=c(l))=>m?l==m?l+'Z'+l:j+1==k?m+'R'+l:k+1==j?l+'L'+m:j>k?[...d(l,m)].reverse().join``:k>j?d(m,l):0:'').join``

Just by glancing you can see all the places where this can be golfed. I can probably chop off 100 bytes.
Ungolfed:
(d,y=`abcdefghijklmnopqrstuvwxyz`)=>
[...`${d}`.toLowerCase()].map((l,i,a, m=a[i-1],
 c=s=>y.search(s),
 d=(s,e)=>y.slice(c(s),c(e)).slice(1))
   =>m?
     l==m?         l+'Z'+l:
     c(m)+1==c(l)? m+'R'+l:
     c(l)+1==c(m)? l+'L'+m:
     c(m)>c(l)?    [...d(l,m)].reverse().join``:
     c(l)>c(m)?    d(m,l):  0:
'').join``

You can clearly see where this can be golfed in the ?: sequence.

ES5 Snippet:

function t(d) {
    var y = 'abcdefghijklmnopqrstuvwxyz';
    return (d+'').toLowerCase().split('').map(function (l,i,a) {
        var m = a[i - 1],
            c = function (s) {
                return y.search(s)
            },
            d = function (s,e) {
                return y.slice( c(s), c(e) ).slice(1);
            };
       return m ?
              l == m           ? l + 'Z' + l :
              c(m) + 1 == c(l) ? m + 'R' + l :
              c(l) + 1 == c(m) ? l + 'L' + m :
              c(m) > c(l)      ? d(l,m).split('').reverse().join('') :
              c(l) > c(m)      ? d(m,l)                              :
              0 : ''
    }).join('');
}

// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(document.getElementById('input').value)
};

Encoding Snippet

<input placeholder="Text here..." id="input"><button id='go'>Encode!</button>

Output:

By setting y, can you use a different alphabet/set of characters?

@phase yeah, that contains all the characters the program uses.

Haskell, 168 bytes
import Data.Char
s=succ
b#a|a==b=[a,'Z',b]|s a==b=[a,'R',b]|a==s b=[a,'L',b]|a>b=reverse$a#b|a>=zipWith(#)).map toLower.filter isLetter

running:
λ: e "att"
"bcdefghijklmnopqrstZt"
λ: e "brep"
"cdefghijklmnopqqponmlkjihgffghijklmno"
λ: e "Optimizer"
"oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq"
λ: e "aabbcfcBBAa"
"aZaaRbbZbbRcdeedcLbbZbbLaaZa"

Nice. 1 byte to save: use both id=<< instead of concat and a list comprehension instead of map and filter: e x=id=<<(tail>>=zipWith(#))[toLower i|i<-x,isLetter i]

Python 343 334 bytes
import sys,re,string
j=''.join
a=string.ascii_lowercase
for l in sys.stdin:
 s,L=re.sub('[^a-z]','',l.lower()).strip(),[]
 for i,c in enumerate(s[:-1]):o=s[i+1:i+2]or c;b,d=a.index(c),a.index(o);L.extend(j(e[1])for e in[(c==o,[c,'Z',c]),(c<o,(a[b+1:d],[c,'R',o])[b+1==d]),(c>o,(a[d+1:b][::-1],[c,'L',o])[b-1==d])]if e[0])
 print(j(L))

Code on ideone.
First golf ever. Any suggestions would be great.

Welcome to the site! A couple of suggestions: Using semicolons to separate your lines instead of newlines is typically shorter, as it avoids indentation. Also, you can alias ''.join to something shorter, like j, which saves bytes because you use it twice. Take a look at this page if you want more tips.

Hi, thanks! How would I go about aliasing a built-in's method invocation to save space? For example this is illegal in all pythons str.j=str.join since 'str' is a built-in type. I could do something like j=lambda L:''.join(L) (21 bytes), but the definition alone is as twice as long as ''.join(L) (10 bytes).

It's very simple: j=''.join

Super! I overthought that one! Thanks a bunch!

K5, 77 bytes
ouch
,/{$[(p:d>0)&3>d:1+x-y;"LZR"@d;`c$$[p;1_y+!x-y;|1_x+!y-x]]}':{(x;x+32)@x<97}'

Explanation coming after more golfing.

Haskell, 185 bytes
import Data.Char
s=succ
p=pred
f(a:b:c)|b==s a=q 'R'|a==s b=q 'L'|a==b=q 'Z'|ab=[p a,p$p a..s b]++n where q m=a:m:b:n;n=f(b:c)
f _=[]
g x=f[toLower e|e<-x,isLetter e]

Usage: g "brep" -> "cdefghijklmnopqqponmlkjihgffghijklmno".
How it works: g throws away all non-letters and converts the letters to lower case and calls f to do the encryption. Depending on the first two characters f inserts R, L or Z or builds the sequence in-between and and appends the result of a recursive call of itself with the tail of the input.


text:
Average Color of an Image
Average color of an image
Scientists have been able to determine the average color of the universe but in how many bytes can we find the average color on an image?
Your task
Your input will be a single image which you will need to find the average of the colors in the image and output a hex color-string (#??????). The image can be any of the following formats

JPEG/JFIF

JPEG 2000

TIFF
GIF
BMP
PNG
PNM

PPM

The input can also be taken as a URL/URI to the image.
Build-in functions which calculate averages or sample the image at once such as ImageMeasurements are not allowed.
Examples
Results will differ slightly depending on how you calculate the average and which color models you use. I've added RGB and LCH (HSV) values for the images below.
 output: #53715F RGB, may also be #3B7D3D LCH (HSV)

 output: #8B7D41 RGB, #96753C LCH (HSV)

What image formats do we have to handle? Specifically, can we choose to handle only PPM?

Can I have a smaller test case please? My script is very slow, and while I will run it on the large case, I don't to waste that time if it is wrong. Or even just the script you calculated it with.

@Maltysen I've added a 240x140 example. Hopfully that's small enough

Should we always round down? In the first example, the 95.6..., which you have rounded to 95 in the specified output.

@Dennis Yeah, you can just truncate off (round down) the decimal

Must the colourspace used for the average be uniform (e.g. L*a*b*) or can it be the colourspace of the input image (i.e. YUV for JPEG, etc.)? What about gamma?

PS There's no point posting a question in the sandbox unless you're going to leave it there for at least 24 hours, so that people in other time zones can see it, and realistically you need to give it 72 hours because not everyone checks the sandbox obsessively.

@PeterTaylor I've updated the question, your results will obviously depend on which color model you use.

You may want to add in the fact that you're assuming the images are unsigned 8-bit integer per channel... or 24-bit RGB images. There are some images... like in TIF... especially in medical image stacks where the bit precision is larger... 16-bit or 32-bit perhaps.

Pyth - 23 22 19 18 16 bytes
Transposes to get all channels, then sums, divides, and hexifies each. Finishes by concatenating and prepending a #.
+\#sm.H/sdldCs'z

Takes an image file name (any type) from stdin and outputs to stdout. VERY SLOW.
+               String concat
 \#             "#"
 s              String concat all channels
 m              Map
  .H            Hex string
    /  ld       Divided by length of channel
     sd         Sum of channel
  C             Transpose to separate into channels
   s            Concatenate all rows
    'z          Read image with filename input

Sample run
>>>pyth avg.pyth
V5VAR.jpg
#8b7d41

You might want to specify the image type, if any.

@isaacg good point. It takes anything.

How does it take anything, does it decode the jpeg to a bitmap?

@AlecTeal According to the documentation Pyth checks whether the file is an image and automatically converts it into a bitmap. Searching the GitHub repository it looks like it uses the PIL library to handle images.   Look here for the exact source.

@Bakuriu - I didn't upvote this answer because I wasn't aware how Pyth handled images so it looked a bit fishy to me... but now that you provided insight there, this gets my vote.  Thanks for the clarification!

Bash, 46 bytes
ImageMagick scales image to one pixel which contains average of the colors in the image then outputs it as text.
convert $1 -scale 1x1\! txt:-|egrep -o '#\w+'

That's smart! +1

MATLAB - 68 bytes
The image is read in with imread combined with uigetfile to open up a GUI to choose the image you want to load in. The assumption with this code is that all images are RGB, and to calculate the average colour, we sum over each channel individually then divide by as many elements as there are in one channel, which is the total number of pixels in the RGB image (numel(I)) divided by 3.  Because the average can possibly generate floating point values, a call to fix is required to round the number down towards zero. sprintf combined with the hexadecimal formatting string (%x) is used to print out each integer value in the average into its hex equivalent.  However, the 02 is there to ensure that an extra 0 is padded to the left should the average value for any channel be less than 16*.
I=imread(uigetfile);
['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]

Sample Runs
The nice thing about imread is that you can read in images directly from URLs.  As a reproducible example, let's assume you have downloaded the images on your computer and have run the above code... but for demonstration, I'll read the images directly from Code Golf:
First Image
>> I=imread('https://i.stack.imgur.com/dkShg.jpg');
>> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]

ans =

#53715f

Second Image
>> I=imread('https://i.stack.imgur.com/V5VAR.jpg');
>> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]

ans =

#8b7d41

*Note: This was a collaborative effort made by StackOverflow users on the MATLAB and Octave chat room.

CJam, 27 bytes
'#[q~]5>3/_:.+\,f/"%02X"fe%

This read a PPM image from STDIN.
CJam has no built-in image processing, so this code expects an ASCII Portable PixMap (magic number P3) with full 24-bit palette (maximum value 255) and no comments.
Test run
$ cjam avg.cjam < dkShg.ppm
#53715F

How it works
'#     e# Push that character.
[q~]   e# Evaluate the input and collect the results in an array.
5>     e# Discard the first first results (Pi, 3, width, height, range).
3/     e# Split into chunks of length 3 (RGB).
_:.+   e# Push a copy and add across the columns (RGB).
\,f/   e# Divide each sum by the length of the array (number of pixels).
"%02X" e# Push that format string (hexadecimal integer, zero-pad to two digits).
fe%    e# Format each integer, using the format string.

HTML5 + JavaScript (ES6), 335 bytes
This is not going to win but I had fun doing it anyways.
Uses the HTML5 Canvas API. Input is a URL of a CORS-enabled image.
f=(u,i=new Image)=>{i.crossOrigin='';i.src=u;i.onload=e=>{x=(c=document.createElement('canvas')).getContext('2d');a=w=c.width=i.width;a*=h=c.height=i.height;x.drawImage(i,0,0);for(d=x.getImageData(m=0,0,w,h).data,r=[0,0,0];m<d.length;m+=4){r[0]+=d[m];r[1]+=d[m+1];r[2]+=d[m+2]}console.log('#'+r.map(v=>(~~(v/a)).toString(16)).join``)}}

Demo
As it is ES6, it currently only works in Firefox and Edge.

f = (u,i = new Image) => {
  i.crossOrigin = '';
  i.src = u;
  i.onload = e => {
    x = (c = document.createElement('canvas')).getContext('2d');
    a = w = c.width = i.width;
    a *= h = c.height = i.height;
    x.drawImage(i, 0, 0);
    for (d = x.getImageData(m = 0, 0, w, h).data, r = [0, 0, 0]; m < d.length; m += 4) {
      r[0] += d[m]
      r[1] += d[m + 1];
      r[2] += d[m + 2];
    }
    console.log('#' + r.map(v => (~~(v/a)).toString(16)).join``)
  }
}

// Snippet stuff
console.log = x => document.body.innerHTML += x + '<br>';

f('http://crossorigin.me/https://i.stack.imgur.com/dkShg.jpg');

f('http://crossorigin.me/https://i.stack.imgur.com/V5VAR.jpg');

Hey, I like that it's runnable directly in your answer because it's HTML + JS :) +1.

Can't you replace new Image with Image()?

@IsmaelMiguel TypeError: Constructor Image requires 'new'

Crap. But you can create W='width' and H='height' and use i[H] or i[W]

@IsmaelMiguel That uses more characters

I really can't see anything to squeeze out of there.

Python [3] + SciPy, 144 133 121
Loads pixel data, sums for each channel, divides by size*, formats.
Values are rounded towards zero.
*size = width * height * channels, thus multiplied by 3
from scipy import misc,sum
i=misc.imread(input())
print('#'+(3*'{:2x}').format(*sum(i.astype(int),axis=(0,1))*3//i.size))

Why not use input() for taking the path? It'll save you 20 bytes.

Thanks! I've managed to save 11 bytes though.

You only need one import, import scipy. Change m.imread to misc.imread.

Doesn't work without importing misc, NameError: name 'misc' is not defined. Tried from scipy import*, doesn't work either.

@TrangOul What about from scipy import sum, misc as m? You save when you use sum as well, then.

R, 90 bytes
rgb(matrix(apply(png::readPNG(scan(,"")),3,function(x)sum(x*255)%/%length(x)),nc=3),m=255)

Path to PNG file is read from STDIN. Package png needs to be installed.
Step-by-step:
#Reads path from stdin and feeds it to function readPNG from package png
p = png::readPNG(scan(,""))
#The result is a 3d matrix (1 layer for each color channel) filled with [0,1] values
#So next step, we compute the mean on each layer using apply(X,3,FUN)
#after moving the value to range [0,255] and keeping it as an integer.
a = apply(p,3,function(x)sum(x*255)%/%length(x))
#The result is then moved to a matrix of 3 columns:
m = matrix(a, nc=3)
#Which we feed to function rgb, while specifying that we're working on range [0,255]
rgb(m, m=255)

# Example:
rgb(matrix(apply(png::readPNG(scan(,"")),3,function(x)sum(x*255)%/%length(x)),nc=3),m=255)
# 1: ~/Desktop/dkShg.png
# 2:
# Read 1 item
# [1] "#53715F"

Cobra - 371
@ref 'System.Numerics'
use System.Drawing
use System.Numerics
class P
    def main
        i,d=Bitmap(Console.readLine?''),BigInteger
        r,g,b,c=d(),d(),d(),d()
        for x in i.width,for y in i.height,r,g,b,c=for n in 4 get BigInteger.add([r,g,b,c][n],d([(p=i.getPixel(x,y)).r,p.g,p.b,1][n]))
        print'#'+(for k in[r,g,b]get Convert.toString(BigInteger.divide(k,c)to int,16)).join('')

C, 259 Bytes
Takes a PPM file with no comments.
double*f,r,g,b;x,y,z,i;char*s="%d %d %d";main(a,_){(a-2)?(feof(f)?0:(fscanf(f,s,&x,&y,&z),r+=(x-r)/i,g+=(y-g)/i,b+=(z-b)/i++,main(0,0))):(f=fopen(((char**)_)[1],"r"),fscanf(f,"%*s%*d%*d%*d"),r=g=b=0.,i=1,main(0,0),printf(s,(int)r,(int)g,(int)b),fclose(f));}

Process
Initial code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    FILE *f = fopen(argv[1],"r");
    int w,h,d,x,y,z,i;
    double r,g,b;
    fscanf(f,"%*s %d %d %d",&w,&h,&d);//get width, height, depth, ignore P6
    r = g = b = 0.0; //zero r, g, and b totals
    for (i=1; i<=w*h; ++i) {
        fscanf(f,"%d %d %d",&x,&y,&z);//get next pixel
        r+=(x-r)/i;//update averages
        g+=(y-g)/i;
        b+=(z-b)/i;
    }
    printf("%d %d %d",(int)r,(int)g,(int)b);//print result
    fclose(f);
    return 0;
}

Trim variables and remove loop:
double r,g,b;
FILE *f;
int i;
int main(int argc, char *argv[])
{
    if (argc==2) { // {./me} {file.ppm}
        f = fopen(argv[1],"r");
        fscanf(f,"%*s%*d%*d%*d");//drop info
        r = g = b = 0.0;
        i = 1;
        main(0,0);//begin load loop
        printf("%d %d %d",(int)r,(int)g,(int)b);
        fclose(f)
    } else {
        if (feof(f)) return 0;
        fscanf(f,"%d%d%d",&x,&y,&z);
        r+=(x-r)/i;
        g+=(y-g)/i;
        b+=(z-b)/i;
        i++;
        main(0,0);
    }
    return 0;
}

From there I combined the various statements into a single return statement. Removed it and any other extraneous type info, renamed variables, and cut the whitespace.

Java, 449 447 446 430 426 bytes
import java.awt.*;interface A{static void main(String[]a)throws Exception{java.awt.image.BufferedImage i=javax.imageio.ImageIO.read(new java.io.File(new java.util.Scanner(System.in).nextLine()));int r=0,g=0,b=0,k=0,x,y;for(x=0;x<i.getWidth();x++)for(y=0;y<i.getHeight();k++){Color c=new Color(i.getRGB(x,y++));r+=c.getRed();g+=c.getGreen();b+=c.getBlue();}System.out.printf("#%06X",0xFFFFFF&new Color(r/k,g/k,b/k).getRGB());}}

Thanks to this answer over on stack overflow for the String.format trick.


text:
Pi Bowling to 10 in 10
Your Goal: Estimate pi to at least 10 decimal places. The format is your choice - it can output as a number, as a string, as an output to STDOUT, etc.
Seems easy, right? But wait, it's not as simple as it seems...
The Rules: You get exactly 10 function calls (this includes operators). These functions cannot be ones that naturally induce or define pi, such as the arc-trig functions or a function converting degrees to radians (this also includes any function that operates as a "solver", such as one that can find roots of sin(x)). If your language has complex number capabilities, this capability cannot be used. All functions must be part of your languages built-in functions or within a standard library (loading the library does not count as an operation, but it must be a standard library, not just a popular one).
All function calls must be crucial to your code - this means that you cannot use division by one, or factorial of two. You also cannot use any literal (except for three digits in the form of one, two, or three integers)*, reading of files of any sort, or a code's ability to convert itself into values (such as a function to get the name of a variable as a string).
*Note: an exception is made for format strings for languages that require them for output. However, only formats, not actual contents, can be found in the format strings, so you can have printf("%f%f",x,y), but not printf("%f.%f",x,y).
Loops may be used, but will eat up your function calls - the 10 function calls are calls, not total functions used. Assignment does not count as an operation, but operations such as array slicing (including obtaining a single value from an array) count, in which case a[1] would count as two bytes (for []).
If you think you've found a loophole for the rules, then it's also against the rules. This is not a challenge for finding the best bending of the rules, or the best way of abusing a minor oversight in the challenge question... if your instinct is to call it a "loophole", then post it as a comment to help close it.
Scoring: This is code bowling, so you're after the highest score. But it's not the total number of bytes in your code that is being counted.
Instead, it's the sum of bytes in the functions being used. That is, if you use 4*cos(2/3) (which happens to be approximately 3.14355), then you have three functions - *, cos, and /, with the total being 5 bytes. If you were to use, for instance (using Julia), sum(map(n->1/n,1:4)), then the operations are sum, map, /, and :, for 8 bytes... but as 1/n is being called four times, it uses 7 function calls (sum, map, four instances of /, and :). User-made functions do not count towards either the function call allowance or the byte count (note: functions used in those user-made functions do count).
Additional emphasis: The point, here, is to find the best way to abuse your language's longest built-in/standard function names in the context of calculating pi. More digits of pi aren't necessary, but I will personally be more likely to upvote an answer that gets more digits than necessary.
Remember, since you're after long function names, you should probably avoid unary and binary operators, as most of these have full function equivalents (in Julia, for instance, * can be replaced by prod).
Quick Summary: You have 10 built-in function calls (includes operators/subroutines/etc). You must estimate pi to 10 decimal places. You can use a total of 3 characters for integer literals (so you can have 1 and 36, or 1 and 2 and 3, or 328, but you can't have 22 and 49). Score is count of built-in function name bytes (if the user defines the name, it doesn't count). No functions that calculate or use pi directly. No complex numbers. This is not a challenge to find loopholes.

Can we count TI-BASIC by displayed characters, not tokens?

I don't understand the scoring example. If the : counts as a function for the purpose of counting bytes, why does it not count as a function for the purpose of number of invocations?

If you think you've found a loophole for the rules, then it's also against the rules.  This doesn't excuse you from making precise rules. Some of the fun of code golf is doing things in a clever and unexpected ways. We should not have to guess your intent to do a challenge.

Could you summarize the rules. eg 10 function calls only, 3 literals only (must be integer 0 to 999), etc

Found a loophole capable of giving infinite scores. In python you can do import function from module as aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...

@PeterTaylor - you're right, that was an oversight. It'll be fixed in a moment.

@xnor - the point was that I had tried to deal with all possible loopholes, but it was possible that I'd missed some. That statement was my way of saying "looking for loopholes that are obviously loopholes and not real opportunities is against the point of this challenge". I may not have closed every loophole, but I was pretty explicit about what the challenge is about.

@Maltysen - I would consider that to be the equivalent of typing aaaaaaaaaaaaaaaaaaaaa = sum in Julia - it's a user-defined function name, and thus not counted.

Since the built-in name would be function, it would count as 8 bytes, no matter how many a characters are used in the user-defined function name. Also, @MickyT - I've added a quick summary, let me know if there's any issue with it.

I was all set for a Monte Carlo approach, until I read the rule about loops. Somehow I don't think I can stick to 10 function calls in several hundred (or thousand) trials...

@TimPederick - yes, that would be quite a challenge. I put the rule about loops in because it's pretty easy to come up with algorithms that use just a few operations within a loop, and with enough iterations, it'll converge. I might try to come up with a code-bowling problem (I'm enjoying the challenge of designing good code-bowling challenges) that could use Monte Carlo or similar approaches soon.

'If you think you've found a loophole for the rules, then it's also against the rules.' You sir, you should be a lawyer.

@Zukki - Can you think of a better way to emphasise it? You wouldn't call it a "loophole" if it was a clearly-acceptable action.

I'm voting to close this as off-topic because, without a clear list of what is and isn't allowed, there is no way to determine if a solution is valid or not.

@Mego - can you be more specific? What's something that is unclear in terms of what is and isn't allowed? I'm particularly confused by the "objective primary winning criterion" issue, given that it's quite clear - you count up the bytes used in the built-in names of function calls and equivalent (operators are functions), and the most bytes wins. The only imperfection is the "loophole" line... and that's nothing more than saying "if you see it as a loophole, don't use it".

@GlenO That loophole line is a big part of the problem - what one person may view as a loophole, another may view as a clever solution. It's entirely arbitrary.

@Mego - it's not intended as an absolute, but a way to ask people to think about the intent of the rules as well as the explicit wording. There are multiple examples in the "Standard Loopholes" listing on Meta where everyone would recognise it as a loophole irrespective of the problem at hand - for instance, "Optimising for the given test cases". Can you give an example of something that some people might think is a loophole, and others would just call a clever solution?

Note that it specifically says "if your instinct is to call it a "loophole", then post it as a comment to help close it." - in other words, I've tried my best to close all loopholes, but if I've missed one, let me know.

R, 34 42 Points
I think I have complied with all the rules and scored it correctly.
Edit  Turns out not complying with the rules in the first place was a bit of a bonus.
Use this formula to calculate pi (63/25)x((17+sqrt(5)*15)/(7+sqrt(5)*15))
# set up the required numbers
a<-5
b<-2
# Calculate 5^.5 * 15                    3 Operations 11 Bytes
c<-prod(sqrt(a),sum(a,a,a))
# Calculate (17 + c) / (7 + C)           3 Operations 7 Bytes
d<-sum(a,a,a,b,c)/sum(a,b,c)
# Calculate (63/25)*d                    3 Operations 19 Bytes
pi<-prod(as.double(paste0(b,'.',a,b)),d)
# Output pi showing all digits           1 Operations 5 Bytes
strwrap(pi)

Test run
> a<-5
> b<-2
> c<-prod(sqrt(a),sum(a,a,a))  # 3 Operations 11 Bytes
> d<-sum(a,a,a,b,c)/sum(a,b,c) # 3 Operations 7 Bytes
> pi<-prod(as.double(paste0(b,'.',a,b)),d) # 3 Operations 19 Bytes
> strwrap(pi)                    # 1 Operations 5 Bytes
[1] "3.14159265380569"

Unfortunately, you've used 5 digits in integer literals - 5, 2, 2, and 63. Also, it might be a misunderstanding on my part of what R does, but it seems like the number it produces is 2.607955506546497. I'm guessing that strwrap isn't just outputting the number calculated (an explanation and the final output would be helpful).

OK, regarding the "number it produces" part, I just realised I was thinking of the second part of the product for c as a product itself (so a^3 rather than 3a). Now the calculation makes sense, it's just the number of integer literal digits.

@GlenO  Sorry about the numbers.  The second 2 snuck in when I should have used b and I mistook the rule around the numbers.  Will see if I can still make it work or delete

C#
Exactly 10 function calls and 3 numeric literals.
using System;
using System.Linq;

namespace ConsoleApplication2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            /*3:*/
            int a = 3; //0 calls: 0
            /*14->15:*/
            int b = 14; //0 calls: 0 + 0 = 0
            /*14:*/
            int c = (b)++; //1 call: 0 + 1 = 1
            /*926:*/
            int d = 926; //0 calls: 1 + 0 = 1
            /*53:*/
            int e = (a*c) + (a*a); //3 calls: 1+3 = 4
            //3*14 + 3*3 = 42+9 = 51
            e++; //1 call: 4 + 1 = 5
            e++; //1 call: 5 + 1 = 6
            /*5:*/
            char f = e.ToString().ToCharArray().First(); //3 call: 6 + 3 = 9

            Console.WriteLine("{0}.{1}{2}{3}{4}{5}", a, c, b, d, e, f); //1 call: 9 + 1 = 10
        }
    }
}

Outputs: 3.1415926535

"Three numeric literals" isn't the rule. Three digits in numeric literals is the rule (so the total number of digits in your code that are used for numeric literals must be no more than 3). Technically is a string literal, but I think I'll make a special exception for languages that can't output without a format string, as long as it's only the format (which means the decimal place has to go). That being said, props for thinking of a non-numeric way to answer. It might just require some more tweaking to cut back on use of literals.

C, 23 bytes
I think this is correct now...
#include <stdio.h>
#include <math.h>

main()
{
    double pi= (double)22 / 7; /* 1 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */
    pi+=sin(pi); /* 1 + 3 bytes = 4 */

    printf("%.10f", pi); /* 6 bytes = 6 */
    return 0;
}

Main is effectively just a user-named function (it just happens to be a special one). That being said, I count twelve operations in your loop - four instances each of ++, <, += (which counts for the + part), and sin (some languages wouldn't use operations for some loops - for instance, Julia has iterators - but C does). You're better off writing it as a sequence of instructions, rather than a loop (true of any language, probably). Writing it as a sequence also gives it more of a "code-bowling" feel, anyway, since you're making the code longer.

That's why I said I could unroll the loop in the comment. I'll do so. Thanks for the clarification :)

Racket, 72 bytes
Gotta love those verbose built-in names!
((lambda() ; lambda is a Racket-defined function too, 6 bytes
  (define-values (a b) (integer-sqrt/remainder 491)) ; 13 (define-values) + 22 (integer-sqrt/remainder) = 35 (on this line alone).  a and b are 22 and 7 respectively
  (define-values (q) (/ a b)) ; 13 (define-values) + 1 (/) = 14
  (define-values (c) (+ (sin q) q)) ; 13 + 1 + 3  = 17
  (+ (sin c) c) ; 1 + 3 = 4
  )) ; total: 6 + 35 + 14 + 17 + 4 = 72

With the amount of precision that in-exact numbers in Racket have, this is actually equal to pi such that (- pi (lambda...) outputs 0.0.
Also, I know this is a realllllllllllly old challenge.  But all of the current challenge answers do horribly in comparison to this bowl, so I had to do it.