text:
Arithmetic Progressions
Your task is to analyse the input and output the formula for the n-th term if it is an arithmetic sequence, otherwise it should print "NAAP".

Input
Input (from STDIN) will consist of few numbers, between 4 to 10 numbers where each number will be in the range between -1000 and 1000 inclusive, separated by a delimiter (a space or a comma or a semi-colon [whichever is to your preference]). Here are some example inputs.
12,14,16,18       //valid
-3 4 5 1 -2 -4    //valid
45;35;-35         //invalid (only three numbers are present instead of the minimum of 4 numbers)
2,32;21,321       //invalid (it uses two different delimiters: `,` and `;`)

Output
The program should first check whether the input is an arithmetic progression or not.
Arithmetic Progressions (AP) in a nutshell: Every AP will have a common difference. This is the difference between the $n$ and ${n-1}$ th terms (basically $a(n+1) - a(n)$ where a is the function for the sequnce). This difference stays the same for any value of $n$ in an AP. If there is no common difference, then it is not an arithmetic sequence. To calculate the value of the n-th term, use this formula $a(n) = a(1) + (n-1)d$ where $a(1)$ is the first term and $d$ is the common difference.
If it is not an arithmetic progression, then the program should print the error message "NAAP" (short for "Not An Arithmetic Progression").
If it is an arithmetic progression, then the program should print the simplified n-th term of the sequence to STDOUT.
Example:
> 1,3,5,7,9
2n-1

Explanation: This is an AP because there is a common difference ($3 - 1 = 2$). Then you use the formula $a(n) = a(1) + (n-1)d$
$$a_n = a_1 + (n-1)d$$
$$a_n = 1 + (n-1)2$$
$$a_n = 1 + 2n - 2$$
$$a_n = 2n - 1$$
Therefore output is 2n-1 (notice the absence of spaces)

Standard loopholes are disallowed by default.
You are allowed to create a function if you want (with the array of numbers as your parameter). If not, then you must create a full program that takes input as a string or an array and outputs accordingly.
Test cases:
1.
1,3,5,7,9
2n-1

2.
1 3 12312 7 9
NAAP

3.
-6;8;22;36;50
14n-20

4.
5,1,-3,-7,-11,-15
-4n+9

5.
-5,-7,-9,-11,-13,-15
-2n-3

6.
3,3,3,3,3,3,3,3,3
0n+3

7.
-4,-5,-6,-7
-1n-3

This is code-golf so the shortest code in bytes wins!
(sorry for bad math-jax)
Any suggestions are welcome!

You should probably keep your post in the sandbox for more than an hour...

@Mego It has been more than one hour.

One hour is a really short time. Not everybody checks the sandbox constantly. 24 hours is a good minimum.

http://i.imgur.com/yS4JpMM.png

@Mego Sorry, I am new to the "Sandbox" concept...

Sorry, but although MathJax works on Meta, it doesn't work on the main PPCG site...

You should add test cases with decreasing sequences.

Are 0,0,0,0 and 3,1,-1,-3,-5 arithmetic progressions? If so, I think they'd be good test cases, since they broke a method I was trying.

@ThomasKwa Done.

@xnor Yes, they are AP.

Pyth, 30 bytes
?tJ{-VtQQ"NAAP"+hJ%"n%+d"-hQhJ

Test suite
To check whether it's a arithmetic procession, this uses a vectorized subtraction between each element and the previous, -VtQQ. A ternary checks if there are multiple values in the result (?tJ{) and prints NAAP if so. Then, to get the + or - right, the mod-formating %+d is used.

Haskell, 103 bytes
z=(tail>>=).zipWith
f l@(a:b:_:_:_)|and$z(==)$z(-)l=show(b-a)++'n':['+'|b-a<=a]++show(a+a-b)
f _="NAAP"

Usage example:
f [-6,8,22,36,50]   ->   "14n-20"
f [60,70,80,90]     ->   "10n+50"
f [2,3,4,6,7,8]     ->   "NAAP"

As always in Haskell, fancy output formatting (e.g. mixing numbers with strings) eats a lot of bytes (around 40). The program logic is quite compact:
f l@(a:b:_:_:_)           -- pattern match an input list with at least 4 elements,
                          -- call the whole list l, the first two elements a and b
z=(tail>>=).zipWith       -- the helper function z takes a function f and a list l
                          -- and applies f element wise to the tail of l and l

           z(-)l          -- make a list of neighbor differences
     z(==)                -- then compare these differences for equality
 and                      -- and see if only True values occur

       show ...           -- if so format output string

f _="NAAP"                -- in all other cases ( < 4 elements or False values)
                          -- return "NAAP"

Japt, 60 52 51 bytes
V=N¤£X-NgY+1};W=Vg;Ve_¥W} ?W+'n+'+sU<W +(U-W :"NAAP

Try it online!
Input can be given with whichever separator you like, as that's how the interpreter is designed ;)
Ungolfed and explanation
V=N¤  £    X-NgY+1};W=Vg;Ve_  ¥ W} ?W+'n+'+sU<W +(U-W :"NAAP
V=Ns2 mXYZ{X-NgY+1};W=Vg;VeZ{Z==W} ?W+'n+'+sU<W +(U-W :"NAAP

            // Implicit: N = list of inputs, U = first input
V=Ns2       // Set variable V to N, with the first 2 items sliced off,
mXYZ{       // with each item X and index Y mapped to:
X-NgY+1}    //  X minus the item at index Y+1 in N.
            // This results in a list of the differences (but the first item is NaN).
W=Vg;       // Set W to the first item in V (the multiplication part).
VeZ{Z==W}   // Check if every item in V is equal to W.
?W+'n+      // If true, return W + "n" +
'+sU<W      //  "+".slice(U<W) (this is "+" if U >= W, and "" otherwise)
+(U-W       //  + (U minus W [the addition part]).
:"NAAP      // Otherwise, return "NAAP".
            // Implicit: output last expression

TI-BASIC, 70 bytes
Input X
ΔList(∟X->Y
If variance(Ans
Then
∟X(1)-min(Ans
Text(0,0,min(∟Y),"n",sub("+-",(Ans<0)+1,1),abs(Ans
Else
"NAAP

To remedy TI-BASIC's lack of number-to-string conversion, this uses output on the graphscreen (Text() if the progression is arithmetic, which automatically concatenates the arguments together.
This assumes that negative numbers are entered using TI-BASIC's high-minus character (which looks a little like ⁻), not the binary minus sign. However, output uses the binary minus sign.

Matlab, 103 bytes
x=str2num(input('','s'));y=diff(x);if range(y) disp('NAAP'),else fprintf('%gn%+g\n',y(1),x(1)-y(1)),end

CJam, 38 bytes
{:T2ew::-):U-"NAAP"UW*"n%+d"T0=U+e%+?}

This is an anonymous function that takes an array on the stack as input, and leaves a string on the stack as output. Try it online with additional I/O code for testing.
Explanation:
:T      Save a copy of input in variable T for output generation.
2ew     Generate list of pairs of sequential elements.
::-     Reduce all pairs with subtraction operator.
)       Pop last value from list of differences.
:U      Save difference value in variable U for output generation.
-       Set difference. This will leave an empty list (falsy) if all values are the same.
"NAAP"  First value for ternary operator, for case where not all values are the same.
UW*     Start generating output for success case. Need to flip sign of difference saved
        in variable U, since it was 1st value minus 2nd, and we need the opposite.
"n%+d"  Push format string for printf operator. The + sign in the format specifies that
        the sign is always generated, saving us from needing different cases for the
        value being negative or positive.
T0=     Extract first value from original input saved in variable T.
U+      Add the difference (with the "wrong" sign) to it.
e%      "printf" operator.
+       Concatenate two parts of result.
?       Ternary operator for picking one of the two output cases.

JavaScript (ES6), 91 bytes
x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

Explanation
x=>(
  s=x.split`,`,       // s = array of input numbers
  m=s[1]-s[0],        // m = the multiplication part of the formula
  a=s[0]-m,           // a = the addition part of the formula
  s.some((n,i)=>      // check if the rest of the numbers follow this sequence
    n!=m*i+m+a
  )?"NAAP":
  m+"n"+(a<0?a:"+"+a) // output the formula
)

Test

<input type="text" id="input" value="5,1,-3,-7,-11,-15" /><button onclick='result.innerHTML=(

x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

)(input.value)'>Go</button>

Perl 6, 123 102 101 bytes
EDIT: Don't negate difference
EDIT: use anonymous sub, logical operators and string interpolation. Thanks  Brad Gilbert b2gills

sub{my@b=@_.rotor(2=>-1).map({[-] $_}).squish;$_=@_[0]+@b[0];@b.end&&"NAAP"||"@b[0]n{'+'x($_>=0)}$_"}

Test program (reads from stdin):
my $f = <the code above>
$f(split(/<[;,]>/, slurp)).say

Explanation:
my @b =
  @_.rotor(2=>-1)  # sliding window of 2: (1,2,3,4) => ((1,2),(2,3),(3,4))
  .map({[-] $_})  # calculate difference (subtract all elements and negate)
  .squish;         # remove adjacent elements that are equal

@b.end        # @b.end is last index, @b.end = 0 means @b has only 1 element
&& "NAAP"     # true branch
|| "@b[0]n{'+'x($_>=0)}$_" # string for an+b,
        # {'+'x($_>=0)} inserts a plus sign using the repetition operator x

Typically you would use one of the lambda expression forms so that you can remove the sub f. Also if you used @_ instead of @a you would save several bytes. {my@b=@_.rotor.... Also you shouldn't put parens around the condition of an if statement, this isn't Perl 5. If you changed that if to @b.end&&"NAAP"||$_=... you would save a few more bytes. You can also do away with that last if statement if you used "@b[0]n{'+'x($_>=0)}$_" instead, saving 4 bytes.

You don't need sub at the beginning, without that it becomes an anonymous block. Also just so you know, I wouldn't have thought of using .map({[-] $_}) I would have probably used ».map(*-*).flat which is longer, now I have to go through my own entries to see if I can shorten it with your trick.

Ruby, 95 78 76 bytes
->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}

78 bytes
->s{puts s.reduce(:+)==s.size*(s[-1]+i=s[0])/2?"%dn%+d"%[v=s[1]-i,i-v]:"NAAP"}

95 bytes
->s{puts s.reduce(:+)==s.size*(s[0]+s[-1])/2?"#{v=s[1]-s[0]}n#{"+"if (i=s[0]-v)>0}#{i}":"NAAP"}

Ungolfed:
-> s {
  i,j=s
  puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"
}

Usage:
->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}[[-6,8,22,36,50]]

=> 14n-20

Python 3, 92 bytes
Based on my answer from Find the Sequence
def m(t):s=str;a=t[0];b=t[1];q=b-a;return((s(q)+'n'+'+'*(0<a-q)+s(a-q)),'NAAP')[t[2]/b==b/a]


text:
Euchre bots (card game)
The idea of this challenge is simple: create a bot to play the card game Euchre.
For those of you who don't already know them, I've written out the rules to Euchre here as they pertain to this challenge.
I recommend using python or something similar, but the only real restriction is that it has to be compatible with the controller code
Input:
Your euchre bot will get different kinds of input depending on the current phase of the game or round. Generally speaking, you'll get the game phase on the first line followed by a comma and a the number of points your team has, and then the relevant data on the following lines.
Chronologically, your bot will get input in the following order:
Ordering Trump:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    ordering        // the phase of the game
    th              // the turned up card
    p,p             // each previous player’s decision

Naming Trump:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    naming          // the phase of the game
    p               // each previous player’s decision

Dealer Discarding:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    discard         // the phase of the game
    th              // the card you will pick up

Going alone:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    alone           // the phase of the game
    h               // the trump suit
    n,n             // each previous player’s decision

Your turn:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    turn            // the phase of the game
    h               // the trump suit
    td,8h,p         // each previous player’s card

Trick data:
                    // the cards in your hand (none, since this happens at the end of a trick)
    2               // number of points your team has
    1               // number of tricks your team has taken
    trick           // the phase of the game
    0               // the index of the following list that is your card
    js,tc,4d,js     // the cards played during the trick in the order they were played

Output:
Your euchre bot will have different outputs depending on the current phase of the game or round.
Ordering Trump:
    p   //for pass
    OR
    o   //for order up

Naming Trump:
    p           //for pass
    OR ANY OF
    c,s,h,d     //the suit you want to name

Going alone:
    n   // no
    OR
    y   // yes

Your turn:
    js  //the card you want to play

Scoring:
Your bot's score is the total number of games it wins.
Your bot will play against every other bot, and it will always be partnered with a copy of itself.
Notes:
Here's a simple template in python2.7:
#!/usr/bin/python2.7
import sys

data = sys.stdin.readlines()

hand = data[0].strip().split(',')   # Hand as a list of strings
points = int(data[1])       # Number of points
tricks = int(data[2])       # Number of tricks

out = ''

if data[3] == 'ordering':
    card = data[4]              # The upturn card
    prev = data[5].strip().split(',')   # The previous player's decisions as a list
    # Ordering logic
    out =       # 'o' or 'p'
elif data[3] == 'naming':
    prev = data[4].strip().split(',')   # The previous player's decisions as a list
    # Naming logic
    out =       # 'p', 'h', 's', 'c', or 'd'
elif data[3] == 'discard':
    card = data[4]              # The card you'll take
    # Discarding logic
    out =       # The card you want to discard
elif data[3] == 'alone':
    trump = data[4]             # The trump suit
    prev = data[5].strip().split(',')   # The previous player's decisions as a list
    # Alone logic
    out =       # 'y' for yes, 'n' for no
elif data[3] == 'turn':
    trump = data[4]             # The trump suit
    prev = data[5].strip().split(',')
    # Turn logic
    out =       # The card you want to play
elif data[3] == 'trick':
    trump = data[5]
    cards = data[6].strip().split(',')
    my_card = cards[int(data[4])]
    # Data logic

print(out)

There will always be 4 total responses. If someone goes alone, then their partner's response will be "p" on their turn.
I tried to shave down the amount of redundant input, so to be extra clear:
2a. Both your position relative to the dealer/leader and the card your partner played can be determined by the number of previous outputs.
    There is 1 player between you and your partner. There
    For instance, if you get "td,8h,p" as the last line on your turn, you can see that your partner played an 8h, and the other team has a player that is going alone.
If you are curious, the deal is done in the traditional way (in two rounds alternating packets of 2 and 3 cards) but that's not really relevant to your bot, so...
If the second player decides to order up in the trump phase, that phase will continue, but their outputs will pretty much be ignored. In other words, whoever orders up first is on the Namers team regardless of any other output.
The following are the defaults for the various game phases. If you don't output a valid response for that round, then your response is changed to what's below.
Ordering Trump:     p
Naming Trump:       p
Discarding:         (the first card in your hand)
Going Alone:        n
Your Turn:          (the first legal card in your hand)
Here's the controller code for your testing purposes.
6a. Notice you can pass in either 2 or 4 bot names, if you give it 4 bots then they get partnered up randomly, and with 2 they are partnered up with copies of themselves.
6b. You need a 'bots' directory in the same directory as the controller code, and your bot code needs to be in the bots directory.
For those that want their bot to remember what cards were played, you are given the opportunity during the "trick" phase, which tells your bot which cards were played. You can write to a file in the bots directory as long as that file doesn't exceed 1kb.

Scoreboard:
Old Stager:  2
Marius:      1
Random 8020: 0

I'd recommend including sample bots to make it easier for people to write their bots.

@NathanMerrill Added some code for a random bot

Post it as a submission.  However, the problem with that random bot is that it ignores the majority of the input you are giving it.  People love to copy/paste (then modify) code, so the more comprehensive your initial bots are, the more submissions (and better submissions) you will recieve.

@NathanMerrill Added a template instead, thanks for the tips

There is a bug in your controller. After a couple of rounds all players are "sitting out" because the "playing" flag is never set back to "true".

Am I right to assume that unless the bot is the last player of the turn, it has no way of knowing what was played in the last turn?

@plannapus I assume it's even worse than that, all bots are affected by a severe case of amnesia, forgetting everything that happened before current turn.

@Sleafar well if there was a way of knowing what was played during the current turn, the bot could write it to a file, in order to keep track.

@plannapus Based on the observation you mentioned, I assume this is not allowed.

One more bug. The decisions of other players are provided as this: ['ad', 'jd', 'qd'], instead of the specified format.

May I write to my own file?

@Sleafar I've fixed the first bug (you'll have to download the controller code again), but the second one I can't reproduce. If you're using the template, then it programmatically breaks up the input into items of a list, but the actual input has the format "9h,qs,as,jc,ks"

@NotthatCharles I've updated the rules to explicitly allow writing to a file

@plannapus Fixed just now, thanks for catching it

@TheBeanstalk Writing to a file only makes sense if every player has the information what was played by the other players. Currently the player going first has the least information about each round. The input bug occurs in Python 2.7.8 on Windows. Your template doesn't work as well because the splitted lines contain a '\n' at the end.  I've implemented a workaround for both problems in the Random Bot below.

Yes, as @Sleafar said, it'd be useful (and fair) to give players information about what happened in the previous round of play.

@Sleafar It hadn't occurred to me to add that in when first creating this challenge, but I absolutely agree. The challenge has been updated to include a new phase, and I've fixed the input issue

Marius
I wrote that bot in R. I did some tests with your controller and they seem to communicate correctly.
#!/usr/bin/Rscript
options(warn=-1)
infile = file("stdin")
open(infile)
input = readLines(infile,5)
hand = strsplit(input[1],",")[[1]]
phase = input[4]
if(!phase%in%c("discard","naming")) input = c(input,readLines(infile,1))
other_o = c("a","k","q","j","t","9")
alone = "n"
ord = "p"
trumpify = function(color){
    tr_suit = switch(color,
            "c" = c("c","s",rep("c",5)),
            "s" = c("s","c",rep("s",5)),
            "h" = c("h","d",rep("h",5)),
            "d" = c("d","h",rep("d",5)))
    paste(c("j","j","a","k","q","t","9"),tr_suit,sep="")
    }

if(phase%in%c("ordering","alone")){
    flip = input[5]
    if(phase=="ordering") trump = trumpify(substr(flip,2,2))
    if(phase=="alone") trump = trumpify(flip)
    hand_value = sum((7:1)[trump%in%c(hand,flip)])
    if(hand_value>13) ord = "o"
    if(hand_value>18) alone = "y"
    if(phase=="alone") cat(alone)
    if(phase=="ordering") cat(ord)
    }

if(phase=="naming"){
    name = "p"
    colors = unique(substr(hand,2,2))
    col_values = sapply(colors,function(x)sum((7:1)[trumpify(x)%in%hand]))
    if(any(col_values>13)){name = colors[which.max(col_values)]}
    cat(name)
    }

if(phase=="discard"){
    flip = input[5]
    new_hand = c(hand,flip)
    trump = trumpify(substr(flip,2,2))
    discardables = new_hand[!new_hand%in%trump]
    if(length(discardables)){
        val = sapply(substr(discardables,1,1),function(x)(6:1)[other_o==x])
        d = discardables[which.min(val)]
    }else{d = tail(trump[trump%in%new_hand],1)}
    cat(d)
    }

if(phase=="turn"){
    trump = trumpify(input[5])
    fold = strsplit(gsub("[[:punct:]]","",input[6]),",")[[1]]
    if(length(fold)&!any(is.na(fold))){
        fold_c = substr(fold[1],2,2)
        f_suit = if(fold_c!=input[5]){paste(other_o,fold_c,sep="")}else{trump}
        l = length(f_suit)
        current = (l:1)[f_suit%in%fold]
        if(any(hand%in%f_suit)){
            playable = hand[hand%in%f_suit]
            val = sapply(playable,function(x)(l:1)[f_suit==x])
            if(all(max(val)>current)){
                play = playable[which.max(val)]
            }else{play = playable[which.min(val)]}
        }else if(any(hand%in%trump)){
            playable = hand[hand%in%trump]
            val = sapply(playable,function(x)(7:1)[trump==x])
            if(!any(fold%in%trump)){
                play = playable[which.min(val)]
            }else{
                trumped = fold[fold%in%trump]
                val_o = max((7:1)[trump%in%trumped])
                play = ifelse(any(val>val_o), playable[which.min(val[val>val_o])], playable[which.min(val)])
            }
        }else{
            val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
            play = hand[which.min(val)]
            }
    }else{
        col = c("c","s","h","d")
        non_tr = col[col!=input[5]]
        aces = paste("a",non_tr,sep="")
        if(any(hand%in%aces)){
            play = hand[hand%in%aces][1]
        }else if(any(hand%in%trump)){
            playable = hand[hand%in%trump]
            val = sapply(playable,function(x)(7:1)[trump==x])
            play = playable[which.max(val)]
        }else{
            val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
            play = hand[which.max(val)]
        }
    }
    cat(play)
}

I'll probably modify it later since I didn't implement a "turn" logic for when the bot is defending, but I'm posting it now so that people have another bot to test against.
For now, it only implements very basic strategies such as leading with an ace, a trump or any other high card; following with a higher card when possible or playing the lowest valued card if not; ordering when hand has high value and naming the color in which the hand would have had the highest value; going alone when hand has very high value. The "value" of each card is computed very simply: value of trumps starts from 7 for the first jack and decreases along the trump suit.

Old Stager
This bot follows some simple rules which served him well for a long time:

Intuitively assign a score to each card
Choose the trump if the hand score is good enough
In case of a really good hand play alone
Choose best card when playing first
Choose a better card than the opponents if they are winning
Choose worst card if the partner is winning or if winning is not possible

I increased the target score from 10 to 100 for testing in the controller. The results are still very random, but way more stable than before.
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, math

base = 1.2
playThreshold = 27.0
aloneThreshold = 36.0
sameColor = { 'd' : 'h', 'h' : 'd', 's' : 'c', 'c' : 's' , '' : '', 'n' : 'n' }
cardValue = { 'p' : 0, '9' : 1, 't' : 2, 'j' : 3, 'q' : 4, 'k' : 5, 'a' : 6 }

class Card(object):
    def __init__(self, name, trump):
        self.name = name
        self.value = cardValue[name[0:1]]
        self.suit = name[1:2]
        self.trump = False
        self.updateScore(trump)
    def updateScore(self, trump):
        self.score = self.value
        if self.suit == trump:
            self.trump = True
            self.score += 6
        if self.value == 3:
            if self.suit == trump:
                self.score = 14
            if self.suit == sameColor[trump]:
                self.trump = True
                self.score = 13

class Cards(object):
    def __init__(self, cards, trump):
        self.list = []
        self.score = 0.0
        if cards:
            for c in cards.split(','):
                self.append(Card(c, trump))
    def append(self, card):
        self.list.append(card)
        self.score += math.pow(base, card.score)
    def updateScore(self, trump):
        self.score = 0.0
        for card in self.list:
            card.updateScore(trump)
            self.score += math.pow(base, card.score)
    def best(self):
        card = self.list[0]
        for i in self.list[1:]:
            if i.score > card.score:
                card = i
        return card
    def worst(self):
        card = self.list[0]
        for i in self.list[1:]:
            if i.score < card.score:
                card = i
        return card
    def better(self, ref):
        card = None
        for i in self.list:
            if i.score > ref.score and (card is None or i.score < card.score):
                card = i
        return card

def ordering(hand, card, decisions):
    if len(decisions) == 3:
        hand.append(card)
    return 'o' if hand.score > playThreshold else 'p'

def naming(hand):
    result = 'p'
    score = playThreshold
    for trump in ['d', 'h', 's', 'c']:
        hand.updateScore(trump)
        if hand.score > score:
            result = trump
            score = hand.score
    return result

def turn(hand, decisions):
    bestIndex = -1
    for i, d in enumerate(decisions.list):
        if d.suit:
            bestIndex = i
            break
    if bestIndex == -1:
        return hand.best()
    else:
        suit = decisions.list[bestIndex].suit
        for i in range(2, len(decisions.list)):
            if (decisions.list[i].suit == suit or decisions.list[i].trump) and decisions.list[i].score > decisions.list[bestIndex].score:
                bestIndex = i
        matching = Cards('', '')
        for card in hand.list:
            if card.suit == suit:
                matching.append(card)
        if not matching.list:
            if bestIndex == len(decisions.list) - 2:
                return hand.worst()
            for card in hand.list:
                if card.trump:
                    matching.append(card)
            if not matching.list:
                return hand.worst()
        if bestIndex == len(decisions.list) - 2:
            return matching.worst()
        card = matching.better(decisions.list[bestIndex])
        if card:
            return card
        return matching.worst()

output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))

if input[3] == 'ordering':
    output = ordering(Cards(input[0], input[4][1:2]), Card(input[4], input[4][1:2]), input[5].split(','))
elif input[3] == 'naming':
    output = naming(Cards(input[0], 'n'))
elif input[3] == 'discard':
    output = Cards(input[0], input[4][1:2]).worst().name
elif input[3] == 'alone':
    output = 'y' if Cards(input[0], input[4]).score > aloneThreshold else 'n'
elif input[3] == 'turn':
    output = turn(Cards(input[0], input[4]), Cards(input[5], input[4])).name

print(output)

Random 8020
A simple random bot, which will pass 80% of the time. Uncomment the last line to see the (cleared up) input and output.
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, random

output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))
hand = input[0].split(',')

if input[3] == 'ordering':
    output = random.choice(['p', 'p', 'p', 'p', 'o'])
elif input[3] == 'naming':
    output = random.choice(['p', 'p', 'p', 'p', random.choice(hand)[1:2]])
elif input[3] == 'discard':
    output = random.choice(hand)
elif input[3] == 'alone':
    output = random.choice(['n', 'n', 'n', 'n', 'y'])
elif input[3] == 'turn':
    output =  random.choice(hand)
    if input[5]:
        suited = filter(lambda x: input[5][1:2] in x, hand)
        if suited:
            output = random.choice(suited)

print(output)
#print(input, " --> ", output, file=sys.stderr)

source: Stack Exchange

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

sort: votes


text:
Make a program that outputs its own MD5 hash
Challenge: make a program that outputs a MD5 hash of its source code.
You should not use tricks that would be considered cheating in a quine sense (discussed here).
Using built-in functions and external libraries is allowed. The program should be a full program (not a function/subroutine). Code-golf: shortest solution (byte count) wins.

Please include sufficient information regarding MD5 hashes directly in the post such that Wikipedia could be used as a supplement rather than a necessary resource. Challenges should be as self-contained as possible.

This is a borderline duplicate of the plain quine challenge. A large portion of the answers can simply be copied over here with print() replaced with print(md5()).

In what format should the hash be printed? Hex with lowercase letters, or with uppercase, or base64, or binary, or raw binary?

Its a good question, but definitely a dup of http://codegolf.stackexchange.com/questions/8947/cryptographic-quine-variant.  Perhaps that one needs some more answers :)

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


text:
Normal and inverted exclamation and question mark pairs
Challenge
¡We're going to give exclamation and question marks inverted buddies!
Given a body of text containing sentences ending in ., ?, or !, prepend inverted question marks, ¿, to interrogative sentences (sentences ending in ?) and inverted exclamation marks, ¡, to exclamatory (sentences ending in !). Sentences ending in . are to be ignored.
Sentences will be separated by whitespace (spaces, tabs, and/or newlines) and will only contain alphanumerics, commas, apostrophes, and spaces. Every sentence will have at least one word. The first word of every sentence is guaranteed to be capitalized. Input can start and end with any whitespace.
Example
Input:
  Hello there!      What is your name?
My name is Ron. What's your name?
My name is Alex.  Nice to meet you!
Nice to meet you to!  How was your break?
It was great, I spent all my time code golfing!
What's that?
        Wow, you're such a n00b! Here, let me show you.

Output:
  ¡Hello there!      ¿What is your name?
My name is Ron. ¿What's your name?
My name is Alex.  ¡Nice to meet you!
¡Nice to meet you to!  ¿How was your break?
¡It was great, I spent all my time code golfing!
¿What's that?
        ¡Wow, you're such a n00b! Here, let me show you.

Rules

All default Code Golf rules apply.
The program with the shortest amount of bytes wins.

Bonus (17% off) - Parse multiple marks
A sentence can also end in multiple exclamation/question marks. Give each of these marks a paired inverse exclamation/question mark for an extra 17% off your byte count.
Example
Input:
I am a man in a can doing a dance?? Maybe...
              Doing it for the views??!???!

Output:
¿¿I am a man in a can doing a dance?? Maybe...
              ¡¿¿¿¡¿¿Doing it for the views??!???!

Incorrect output:
¿¿I am a man in a can doing a dance?? Maybe...
              ¿¿¡¿¿¿¡Doing it for the views??!???!

Do we get to choose what sort of whitespace separates the sentences, or do we have to support all 3 types?

@Mego All three types should be supported.

No, a sentence will always have at least one word in it and will end with one of the three allowed punctuation characters. I'll add that to the challenge.

Retina, 39 37 34 bytes
\w[^.]*?([!?])
$1$0
T`?!`¿¡`\S\b

Try it online.
Explanation
\w[^.]*?([!?])
$1$0

This matches a sentence ending in an exclamation or question mark, and prepends that punctuation character to the sentence. Now we know that all the ! or ? which are immediately followed by a non-space character must be those we inserted, because the original ones should be separated from the next character by a space.
T`!?`¡¿`\S\b

This transliteration stage turns all ! and ? into ¡ and ¿, respectively, provided they're found in a match of \S\b, which applies only to the ones we just inserted. Replacing both in two separate substitutions in the same byte count, but I prefer the semantics of a transliteration stage here.

Javascript (ES6), 86 79 66 63 bytes
i=>i.replace(/\w[^.!?]*[!?]/g,k=>(k.slice(-1)>'>'?'¿':'¡')+k)

Ungolfed:
func = inp => inp.replace(/\w[^.!?]*[!?]/g, sentence => (sentence.slice(-1) > '>' ? '¿' : '¡') + sentence)

Usage:
console.log(func(`Hello there!      What is your name?
My name is Ron. What's your name?
My name is Alex.  Nice to meet you!
Nice to meet you to!  How was your break?
It was great, I spent all my time code golfing!
What's that?
            Wow, you're such a n00b! Here, let me show you.`))

Will implement bonus solution soon.
Thanks to:
@user81655, 86 => 79 bytes

A few improvements which save 9 bytes: i=>i.replace(/[A-Z][^.!?]*[.!?]/g,k=>(r=k.slice(-1))<'.'?'¡'+k:r>'.'?'¿'+k:k)

@user81655 It looks like it saves 7 bytes instead of 9, but regardless, thanks for that!  Was able to remove even more bytes by skipping checking for sentences ending in ..

Mathematica, 101 92 91 bytes
StringReplace[#,RegularExpression@"[A-Z][^.]*?([?!])":><|"?"->"¿","!"->"¡"|>@"$1"<>"$0"]&

Would you explain how this works?

@DavidC It's tricky.

Mathematica 137 bytes
Not the shortest, but it was fun to do.
TextSentences breaks up the input text into sentences and StringPosition finds the beginning and end positions of each sentence in the text.  The upside down punctuation is inserted at the beginning of each sentence as required.
w=StringPosition;f[x_,y_,q_]:=StringInsert[x,q,x~w~y/.{a_,a_}->a/.(x~w~#&/@TextSentences@#&@x/.{{c_,d_}}:>d->c)];f[f[t,"!","¡"],"?","¿"]&

Usage, assuming the text is input at t,
f[f[#,"!","¡"],"?","¿"]&[t]

Cool, a solution that doesn't use RegExp!

Sed, 61 bytes
s/\(\s*\)\([^.!?]*!\)/\1¡\2/g;s/\(\s*\)\([^.!?]*?\)/\1¿\2/g

Test run :
$ echo """Hello there!      What is your name?
My name is Ron. What's your name?
My name is Alex.  Nice to meet you!
Nice to meet you to!  How was your break?
It was great, I spent all my time code golfing!
What's that?
        Wow, you're such a n00b! Here, let me show you.""" | sed 's/\(\s*\)\([^.!?]*!\)/\1¡\2/g;s/\(\s*\)\([^.!?]*?\)/\1¿\2/g'
¡Hello there!      ¿What is your name?
My name is Ron. ¿What's your name?
My name is Alex.  ¡Nice to meet you!
¡Nice to meet you to!  ¿How was your break?
¡It was great, I spent all my time code golfing!
¿What's that?
        ¡Wow, you're such a n00b! Here, let me show you.

This is technically 61 bytes as the inverted characters count as 2 bytes.

@usandfriends right, fixed

If you use the -r flag to (GNU) sed, you don't need to escape the ( and ) which should save you 8.  You do need to add an extra point for use of this non-default option though.

@DigitalTrauma I knew that trick and tried it but it didn't return the same output : "¿¡Hello there!      ¿What is your name?¿" instead of "¡Hello there!      ¿What is your name?"

Python 2, 127.82 (154-17%) bytes
import re
print re.sub("([A-Z][\w ,']*)([\.!\?]+)",lambda m:''.join({'!':'¡','?':'¿','.':''}[c]for c in m.group(2))[::-1]+m.group(1)+m.group(2),input())

, 36 chars / 53 bytes
ïċ/\w⁅.!?]*[!?]⌿,⇏(aē-1>⍘>?⍘¿:⍘¡)+a)

Try it here (Firefox only).

Jelly, 41 bytes
0ị⁾!?iị“¡¿ ”t⁶
e€“!?.”kµOe€“µ½ ‘«\nƝkjÇ)F

Try it online!
Bah, who needs regex?
How it works
e€“!?.”kµOe€“µ½ ‘«\nƝkjÇ)F - Main link. Takes a string S on the left
  “!?.”                    - Yield "!?."
 €                         - For each character in S:
e                          -   Is it in "!?."?
       k                   - Split S after occurrences of any of "!?."
        µ                  - Call this list of lists of characters L and use it as the argument
                        )  - For each list of characters C in L:
         O                 -   Convert to a list of char codes
            “µ½ ‘          -   Yield [9, 10, 32]
           €               -   For each char code in C:
          e                -     Is it in [9, 10, 32]?
                               This yields 1s at whitespace characters else 0
                               However, we only want to consider leading whitespace,
                               not whitespace in the string, when inserting ¡¿
                  \        -   Scan:
                 «         -     Minimum
                               This changes all non-leading 1s to 0s
                     Ɲ     -   Over overlapping pairs:
                    n      -     Does not equal?
                               This turns the leading run of 1s into 0s with a final 1
                      k    -   Split C at this 1
                        Ç  -   Call the helper link on C
                       j   -   Join the split C on the helper link
                         F - Flatten into a single string

0ị⁾!?iị“¡¿ ”t⁶ - Helper link. Takes a list of characters C on the left
0ị             - Last character of C, c
  ⁾!?          - "!?"
     i         - Index of c in "!?" or 0 (for sentences ending with ".")
       “¡¿ ”   - "¡¿ "
      ị        - 1-index into this string. "." -> " "
             ⁶ - " "
            t  - Trim spaces. "." -> ""

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


text:
Crack the safe!
Inspired by https://puzzling.stackexchange.com/questions/24334/to-catch-a-thief
You are given an n by n (n itself is optional input) grid filled with 0s and 1s (or any other character of your choice). You aim is to make every cell the same (either 0 or 1). You can make a series of moves as defined below (note dissimilarity with Puzzling SE link):

Select a cell.
Every cell in the same row and column (except the cell itself) gets changed into its opposite. 0 to 1 and 1 to 0.

Output the minimum number of moves required to complete the task. If unsolvable, output anything except a non-negative integer. Shortest code wins.
Sample data
1 0 0
0 0 0
0 0 0

-1
1 1 1
1 1 1
1 1 1

0
1 0 1
0 1 0
1 0 1

1
1 1 1 1
0 0 0 0
0 0 0 0
1 1 1 1

2
0 1 0 1
1 0 1 0
1 0 1 0
0 1 0 1

2

What to do in case the puzzle is unsolvable? E.g. 1000 (rearranged as a square, doesn't matter how).

Related.

@orlp Any output that is not a number will do.

Do we need to parse the input or can it be any already filled array datatype?

@coredump Input can be given in any format.

What is the solution to the first test case?  I'm getting no solutions for it.

@cardboard_box Top-right corner, centre, bottom-right corner.

@ghosts_in_the_code That definitely doesn't work. None of those three invert the center, for instance.

Maybe you should just update the first example to not-solvable, and have a new one that really does take 3 turns.  Having one whose lowest is 3 is a non-trivial example.

@DaleJohnson Can you prove it is unsolvable?

@ghosts_in_the_code I have proven it to be unsolvable in the chat. It's possible to do so by constructing a system of linear equations in GF(2) that corresponds to flipping a cell for every location. Then you can see that it has no solutions for [1, 0, 0, 0, 0, 0, 0, 0, 0]. I'm not aware of an elegant simple proof though.

There are 512 distinct boards in the 3 x 3 configuration.  I have examined them all, starting from all zeros, and none of them end up as 1,0,0 0,0,0 0,0,0.  Each of the 512 boards correspond to a series of 9 boolean choices (hence 2^9) and actions can be made in any order.

Matlab 171 bytes
The input should be a 2d matrix, so you would call it like  c([1,1,1,1;0,0,0,0;0,0,0,0;1,1,1,1]) (semicolons start a new row). This function just bruteforces all possible moves, so we get a runtime of O(2^(n^2)).
How it is done
This is done by choosing all possible ways to fill another matrix of the same size with ones and zero, this is basically counting in binary wich where each entry of the matrix represents a certain power of 2.
Then we perform the moves on those cells that are 1, this is done by the sum (mod 2) of two two dimensional convolution with an vector of ones of size 1xn and nx1.
Finally we decide if those moves actually produced the desired result, by computing the standard deviation over all entries. The standard deviation is only zeros if all entries are the same. And whenever we actually found the desired result we compare it with the number of moves of previous solutions. The function will return inf if the given problem is not solvable.
Math?
It is actually worth noting that all those moves together generate an abelian group! If anyone actually manages to calssify those groups please let me know.
Golfed version:
function M=c(a);n=numel(a);p=a;M=inf;o=ones(1,n);for k=0:2^n-1;p(:)=dec2bin(k,n)-'0';b=mod(conv2(p,o,'s')+conv2(p,o','s'),2);m=sum(p(:));if ~std(b(:)-a(:))&m<M;M=m;end;end

Full version (with the output of the actual moves.)
function M = c(a)
n=numel(a);
p=a;
M=inf;                                               %current minimum of number of moves
o=ones(1,n);
for k=0:2^n-1;
    p(:) = dec2bin(k,n)-'0';                         %logical array with 1 where we perform moves
    b=mod(conv2(p,o,'same')+conv2(p,o','same'),2);   %perform the actual moves
    m=sum(p(:));                                     %number of moves;
    if ~std(b(:)-a(:))&m<M                           %check if the result of the moves is valid, and better
        M=m;
        disp('found new minimum:')
        disp(M)                                      %display number of moves of the new best solution (not in the golfed version)
        disp(p)                                      %display the moves of the new best solution                               (not in the golfed version)
    end
end

Perl 5, 498 bytes
This accepts 'n' and the desired result, and outputs the count, or 'X' if none.
For example:
perl ./crack.golf.pl 3 000111111

gives 2.  It will only work when n^2 <= 64, so n <= 8.  Although it's pretty slow even with n as low as 5.  It builds a n^3 bit array, and sorts a 2^(n^2) array beforehand, because why not?
I have wasted a couple of linefeeds here for readability:
$n=shift;$y=shift;$p=$n*$n;@m=(0..$n-1);@q=(0..$p-1);@v=(0..2**$p-1);@d=map{0}(@q);@b=map{$r=$_;map{$c=$_;$d[$r*$n+$_]^=1 for(@m);$d[$_*$n+$c]^=1 for(@m);$j=0;$k=1;
map{$j|=$k*$d[$_];$k<<=1;}@q;@d=map{0}(@q);$j;}@m}@m;for$k(sort{$a->[0]<=>$b->[0]}map{$z=0;map{$z+=$_}split(//,sprintf"%b",$_);[$z,$_]}@v){$l=sprintf"%0${p}b",$k->[1];
@m=map{$_}split(//,$l);$s=0;for(@q){$s^=$b[$_]if$m[$_];}$z=0;map{$z+=$_}split(//,sprintf"%b",$_);if($y eq sprintf"%0${p}b",$s){print"$k->[0]\n";exit 0;}}print"X\n";


text:
Find the sum of all possible base representations
The objective of this challenge is to write a program to convert an inputed string of what can be assumed as containing only letters and numbers from as many bases between 2 and 36 as possible, and find the base 10 sum of the results.
The input string will be converted to all the bases in which the number would be defined according to the standard alphabet for bases up to 36: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ. For example, the input 2T would be valid in only bases 30 and up. The program would convert 2T from bases 30 through 36 to decimal and sum the results.
You may assume that the input string contains only letters and numbers. Your program may use uppercase or lowercase; it can, but does not need to, support both.

Test cases
Sample input: 2T
Chart of possible bases
Base   Value
30     89
31     91
32     93
33     95
34     97
35     99
36     101

Output: 665
Sample input: 1012
Chart of possible bases:
Base   Value
3      32
4      70
5      132
6      224
7      352
8      522
9      740
10     1012
11     1344
12     1742
13     2212
14     2760
15     3392
16     4114
17     4932
18     5852
19     6880
20     8022
21     9284
22     10672
23     12192
24     13850
25     15652
26     17604
27     19712
28     21982
29     24420
30     27032
31     29824
32     32802
33     35972
34     39340
35     42912
36     46694

Output: 444278
Sample input: HELLOworld
Chart of possible bases
Base   Value
33     809608041709942
34     1058326557132355
35     1372783151310948
36     1767707668033969

Output: 5008425418187214
An input of 0 would be read as 0 in all bases between 2 and 36 inclusive. There is no such thing as base 1.

This is code golf. Standard rules apply. Shortest code in bytes wins.

Are builtins for base conversion allowed?

Important test case: 0

Dang it, I was going to post a very similar challenge.

@ThomasKwa Yes.

@MartinBüttner Why is 0 an important test case? 0 is 0 in every base, and there's no such thing as base 1.

@Eridan because some languages might try converting that from base 1 and fail.

Isn't base 1 unary ? Like, 0, 00, 000... ?

@Quentin Not according to the usual formulation of bases. 000 would be 01^2 + 01^1 + 0*1^0 = 0.

The HELLOworld implies that the program must be able to output greater than 32-bit integers.  Is this correct or can we just 32 bit outputs?  If not, do we do just up to 64 bit integers, or do we need to arbitrary precision?

@immibis Mh. I'm used to the "number of different symbols" approach, with which a unary zero would be "" (nothing). But I'm probably confused.

@Quentin By that (looser) definition, this program should also consider the number in modified-unary where 1, 2, 3, 4, ..., Z mean the same as 0. (Where the "decimal" number 184172 and the "binary" number 011001 are both six)

@immibis Makes no sense indeed :)

Python 3, 72 71 69 bytes
Thanks to FryAmTheEggman for saving a byte!
Thanks to DSM for saving 2 bytes!
N=x=0
y=input()
while N<36:
 N+=1
 try:x+=int(y,N)
 except:0
print(x)

@ThomasKwa that will add a zero, which will not work for purely numeric inputs as that functions as checking if it's base 10 (which will make some results too large)

@FryAmTheEggman Thanks! I have adjusted it

Just checked for you. The try except will let you do range(37). Two bytes!

@Sherlock9 It won't work for purely numeric inputs, these will be interpreted as base 10 numbers.

Oh right, darn. @Adnan

By my count, if you switch to x=N=0 and while N<36: N+=1, you save two bytes against the range.

@DSM That is quite clever!

A few years to late, but moving the N+=1 into the try saves a byte: Try it online!

Pyth, 20 19 11 bytes
sm.xizd0S36

Blatantly stole Adnan's idea from his Python answer.
Try it here

@orlp You can remove the S char

Nope. Test 1012.

Pure Bash, 26
((s+={36..2}#$1,))
echo $s

Try it online!

Old answer from 5 years ago:
Pure Bash (no utilities), 38
Assuming built-in base conversions are allowed:
for((b=36;s+=$b#$1;b--));{ :;}
echo $s

This will output an error to STDERR.  I'm assuming this is OK as per this meta answer.
Test output:
$ for t in 0 2T 1012 HELLOworld; do ./basesum.sh $t; done 2> /dev/null
0
665
444278
5008425418187214
$

I've just written the same answer in zsh and I'm very sad that you got it first!!

Seriously, 65 bytes
,û;╗rk`"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`MSd:37:@x`╜¿`MΣ.

Contains unprintables, hexdump:
2c963bbb726b6022303132333435363738394142434445464748494a4b4c4d4e4f505152535455565758595a22a175604d53643a33373a407860bda8604de42e7f

Unfortunately I don't have a good way to filter from a list based on types. Note to self: add that.
Takes input like "2T"
Try it online (you will have to manually enter input)
Explanation:
,û    get input and convert to uppercase
;╗    make a copy and save to register 0
rk    explode string into list
`"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu`M  map the function over the list:
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"íu    get the character's index in the string and add one to get a value in [1,36]
Sd    get maximum element (maximum base aka max_base) from list by sorting and popping the last element off and pushing it to the stack
:37:@x  push range(max_base,37)
`╜¿`M  map the function over the list:
    ╜¿    convert value in register 0 to an int, interpreting it as a base-n int (n is value from list)
Σ.    sum and print
0x7f  quit

Perhaps Seriously should have a command that produces the alphabet and/or the numbers 0-9?

@Eridan It seriously should - getting that index costs half the bytes.

Mathematica, 57 bytes
#~Sum~{x,Max@CoefficientList[#,x]+1,36}&@FromDigits[#,x]&

You can use infix form for the FromDigits.

Matlab, 98 bytes
function y=f(s)
[~,m]=max(bsxfun(@eq,s,[48:57 65:90]'));y=0;for n=max(m):36
y=y+base2dec(s,n);
end

Octave, 75 73 bytes
function v=u(a) m([48:57 65:90])=0:35;v=sum(polyval(t=m(a),max(t)+1:36));

Explanation:
function v=u(a)
   m([48:57 65:90])=0:35; %// create a map: '0'-'9' = 0-9
                          %//               'A'-'Z' = 10-35
   t=m(a);                %// convert string to mapped values
   b=max(t)+1;            %// find minimum base
   p=polyval(t,b:36);     %// calculate polynomial for each base (vectorized)
   v=sum(p);              %// and return the sum of the resulting vector

polyval has an advantage over base2dec in that it's vectorized, so no for loop is required.
Only '0'..'9' and upper-case 'A'..'Z' are supported as input.

Very clever use of polyval to vectorize!

R, 44 bytes
sum(sapply(2:36,strtoi,x=scan(,"")),na.rm=T)

Try it online!
R has a builtin, strtoi, to convert from a string to an integer in base 2:36 using only digits and capital letters, returning NA if it's invalid in that base. We can then sum them up, removing the NAs with na.rm=T.
Luckily, sapply is smart enough about named arguments to make this work.

Desmos, 85 bytes
f(x)=x+3.5sign(60-x)-51.5
l=i.length
\sum_{n=f(i).max+1}^{36}\sum_{m=1}^lf(i[m])n^{l-m}

View it on Desmos (includes a bonus version that costs 2 extra bytes)
Explanation:
Input is through an array of integers i, as Desmos doesn't support strings. Capital letters are required.
The first function transforms a codepoint to the value in base-36, or any other base that it's valid in. The second function simply stores i.length, as it's expensive to call.
The third function can be understood as such:
\sum_{n=f(i).max+1}^{36}    Iterate n from 1+the largest codepoint value, which will be the smallest valid base, to 36, the largest valid base
\sum_{m=1}^l                Iterate m over the indices of i (Desmos is 1-indexed)
f(i[m])                     Find the value of the mth character
n^{l-m}                     Multiply by the base to the power of its distance to the right
                            Add everything up (due to using sums earlier)

Jelly, 13 bytes
ØBiⱮµ’ḅṀr36ƊS

Try it online!
Works only for uppercase letters.
Explanation
ØBiⱮµ’ḅṀr36ƊS   Monadic link
   Ɱ            Map over argument:
  i             Find 1-based index in...
ØB              ...base digits: "0123456789ABCD...YZabcd...yz"
    µ           Use as argument to new monadic chain
     ’          Decrement (to get 0-based indices)
      ḅ         Convert to base... (auto-mapped)
           Ɗ    ...treat 3 preceding atoms as a single link:
       Ṁ        Maximum [of argument, which is the 1-based indices]
        r36     Inclusive range to 36
            S   Sum

Scala, 64 bytes
Requires uppercase input
s=>(s.map(_%55%48).max+1 to 36).map(b=>(0L/:s)(_*b+_%55%48)).sum

Try it in Scastie
-7 bytes by using a Long (0L) instead of a BigInt (BigInt(0))
This might have been shorter if I'd used try/catch with BigInt(number, base), but I didn't want to do that. Still wish I could inline n, but I need it to determine the first valid base. Apparently, it's one byte shorter by not doing val n=s.map(_%55%48) and reusing n.
Explanation:
s =>                        //Input
  (s.map(_ % 55 % 48)       //Turn the characters into numbers 0-35
    .max+1                  //The maximum of that (minimum base)
      to 36)                //Range of bases up to 36
  .map(b =>                 //For each base b, interpret the input in that base
    (BigInt(0)              //Starting with 0,
              /:s)          //Fold left over the input
    (_ * b +                //Multiply the accumulator by the base
      _ % 55 % 48)          //And add the next digit (put it in the range [0, 35])
  ).sum                     //Take the sum

Husk, 22 bytes
or 21 bytes with only lowercase input
§ṁ`Bö-1…36→▲mö%48%87c_

Try it online!
§ṁ`Bö-1…36→▲mö%48%87c_
§                       # fork: apply 2 functions to same argument
 ṁ`B                    # function 1:
 ṁ                      # sum of elements of argument
  `B                    # interpreted as base N, with N given by
    ö-1…36→▲            # function 2:
    ö                   # combine 4 funcitions:
     -1                 # remove elements equal to 1 from
       …36              # series from 36 to
          →             # one less than
           ▲            # max value of argument
            mö%48%87c_  # fork argument:
            mö          # map 4 functions over input:
                     _  # convert to lowercase
                    c   # get ASCII value
                 %87    # MOD 87
              %48       # MOD 48

Haskell, 77 bytes
f s|d<-[mod(fromEnum c+30)39|c<-s]=sum[foldl1((+).(b*))d|b<-[2..36],all(+f#_:e>)37,>\fb:+

Requires upper case letters.
Test it here.
CJam doesn't have built-in base-36 conversion from strings, so we have to letters out the strings ourselves. I've been trying all sorts of divmod shenanigans, but it seems to be shortest to build a string of all 36 digits and just find the index of each character in that string.

q{'0-_9>7*-}% is just as short.

@PeterTaylor Oh, right...

C function, 93 (32 bit integer output only)
Assuming its OK for the output to only go up to INT_MAX, then we can do this:
i,n,x;f(char *s){char *e;for(i=36,x=0;n=strtol(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%d\n",x);}

The last testcase implies that this is probably not sufficient.  If so, then with 64-bit integers we have:
C function, 122
#include<stdlib.h>
f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);}

Unfortunately the #include <stdlib.h> is required so the return type of strtoll() is correct.  We need to use long long to handle the HELLOworld testcase.  Otherwise this could be a fair bit shorter.
Test driver:
#include<stdlib.h>
f(char *s){long long i=36,n,x=0;char *e;for(;n=strtoll(s,&e,i--),!*e&&i;)x+=*e?0:n;printf("%lld\n",x);}

int main (int argc, char **argv)
{
    f("0");
    f("2T");
    f("1012");
    f("HELLOworld");
}

Test output:
$ ./basesum
0
665
444278
5008425418187214
$

In C can you remove the space in #include <stdlib.h> like you can in C++?

@AlexA. Yes - I didn't know that - thanks!

Japt -x, 17 16 bytes
36õ2 k@kUnXXÃ£nX

Try it

Factor, 38 bytes
[ 37 iota [ base> ] with map sift Σ ]

Try it online!
Explanation:
It's a quotation (anonymous function) that takes a string from the data stack as input and leaves an integer on the data stack as output.

37 iota Create a range from 0 to 36 inclusive.
[ base> ] with map Convert the input to base 10 from each base between 0 and 36. If the input can't be converted from particular base, base> returns f.
sift Remove all the f from a sequence.
Σ Sum.

Pyth, 16 bytes
V36 .x=+ZizhN ;Z

Try it online
Explaination:
                 # Implicit: Z = 0, z = input
V36              # For N in range 36
    .x           # Try except
      =+Z        # Z = Z + izhN
         izhN    # Convert z from base N+1 to decimal
              ;  # Infinite ), for closing the for loop
               Z # Print Z

Japt, 26 bytes
1+U¬r@XwYn36}0)o37 £UnX} x

Try it online!
Ungolfed and explanation
1+U¬ r@   XwYn36}0)o37 £    UnX} x
1+Uq rXYZ{XwYn36}0)o37 mXYZ{UnX} x

           // Implicit: U = input string
Uq rXYZ{   // Split U into chars, and reduce each item Y and previous value X by:
XwYn36     //  Choosing the larger of X and parseInt(Y,36),
}0         // starting at 0.
1+   )o37  // Add 1 and create a range from this number to 36.
mXYZ{UnX}  // Map each item X in this range to parseInt(U,X)
x          // and sum.
           // Implicit: output last expression

Python 3, 142 bytes
Adnan has me soundly beat with their solution, but I did want to add my own attempt.
def f(s):
 t=0
 for x in range(37):
  n=0
  for i in s:
   try:m=int(i)
   except:m=ord(i)-55
   if x<=m:n=0;break
   n=n*x+m
  t+=n
 return t

This function only handles uppercase inputs. Add .upper() to for i in s, and it will handle both uppercase and lowercase.

Scala 2.11, 93 bytes
This is run on the scala console.
val i=readLine
var s=0
for(j<-2 to 36)try{s=s+Integer.parseInt(i,j)}catch{case _:Exception=>}

Haskell, 97 bytes
i c|'_'<c=fromEnum c-87|1<2=read[c]
f s=sum$map((`foldl1`map i s).((+).).(*))[1+i(maximum s)..36]

Supports only lowercase characters. Usage example:
f "2t"           -> 665
f "helloworld"   -> 5008425418187214

It's so massive, because I have to implement both char-to-ASCII and base conversion myself. The corresponding pre-defined functions are in modules which require even more expensive imports.
How it works: i converts a character c to it's digit value (e.g. i 't' -> 29). f calculates the value of the input string for every possible base and sums it. A non-pointfree version of the inner loop is map (\base -> foldl1 (\value digit -> value*base + digit) (map i s)) [ ...bases... ].

JavaScript (ES6), 86 bytes
s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`)

Explanation
s=>
  eval(`                     // use eval to enable for loop without return keyword or {}
    p=parseInt;
    b=2;                     // b = minimum base of s
    [...s].map(d=>           // iterate through each digit d
      (v=p(d,36))            // get it's base-36 value
        >b?b=v:0             // set b to the max value
    );
    for(r=0;++b<37;)         // r = sum of all base values
      r+=p(s,b)              // add each base value from b to 36 to r
  `)                         // implicit: return r

Test

<input type="text" id="input" value="HELLOworld" />
<button onclick="result.textContent=(

s=>eval(`p=parseInt;b=2;[...s].map(d=>(v=p(d,36))>b?b=v:0);for(r=0;++b<37;)r+=p(s,b)`)

)(input.value)">Go</button>

&&b=v saves 1 byte over ?b=v:0.

@Neil Did you test it? I'm pretty sure that would be an invalid left-hand of assignment.

Sorry I confused it with a similar case in another golf.

Ceylon, 100 96 bytes
Integer b(String s)=>sum(((any(s*.letter)then 11else 2)..36).map((r)=>parseInteger(s,r)else 0));

I first had this simpler version taking just 69 bytes:
Integer b(String s)=>sum((2..36).map((r)=>parseInteger(s,r)else 0));

But this fails with the first test case, returning 2000000000665 instead of 665. (The reason is that the T in 2T is parsed as Tera, i.e. multiplies the 2 with 10^12, when the radix is 10.)
Therefore we need to catch this case separately. Thanks to Neil for suggesting a different way of doing this which saved 4 bytes.
Formatted:
// Find sum of all possible base representations.
//
// Question:  https://codegolf.stackexchange.com/q/65748/2338
// My Answer: https://codegolf.stackexchange.com/a/65836/2338

Integer b(String s) =>
// take the sum of ...
        sum(
    // span from 2 to 36. (Though
    // if there are letters in there, we start at 11,
    // because the other ones can't be valid.
    // Also, parseInteger(s, 10) behaves a bit strange in Ceylon.)
    ((any(s*.letter) then 11 else 2) .. 36)
    // map each r of them to ...
        .map((r) =>
            // try parsing s as a number using base r
            parseInteger(s, r)
            // if that didn't succeed, use 0.
                    else 0
    )
);

Can you perhaps shorten the code by starting from base 11 if the string contains a letter, thus avoiding having to special-case base 10?

Perl 6, 35 bytes
{[+] map {+(":$^a"~"<$_>")||0},^37}

usage:
# store it somewhere
my &code = {[+] map {+(":$^a"~"<$_>")||0},^37}

say code 'HELLOworld' # 5008425418187214

say map &code, <2T 1012>
# (665 444278)

say code 'qwertyuiopasdfghjklzxcvbnm1234567890'
# 79495849566202185148466281109757186006261081372450955140

K (ngn/k), 38 35 bytes
{+/t{y/x}/:(|/t:x+7*3>x-:55)_1+!36}

Try it online!
Takes capitalized input, e.g. "2T".

t:x+7*3>x-:55 map input from characters to 0..35, storing in t
(|/t...)_1+!36 identify the valid bases (those larger than the largest value in the input)
t{y/x}/: convert t, interpreted as each valid base, to decimal
+/ take the sum and return


text:
Cover up zeroes in a list
Inspired by this SO question
As input you will be given a non-empty list of integers, where the first value is guaranteed to be non-zero. To construct the output, walk from the start of the list, outputting each non-zero value along the way. When you encounter a zero, instead repeat the value you most recently added to the output.
You may write a program or function, and have input/output take any convenient format which does not encode extra information, as long as is still an ordered sequence of integers. If outputting from a program, you may print a trailing newline. Except for this trailing newline, your output should be an acceptable input for your submission.
The shortest code in bytes wins.
Test Cases
[1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9] -> [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9]
[1, 0, 0, 0, 0, 0] -> [1, 1, 1, 1, 1, 1]
[-1, 0, 5, 0, 0, -7] -> [-1, -1, 5, 5, 5, -7]
[23, 0, 0, -42, 0, 0, 0] -> [23, 23, 23, -42, -42, -42, -42]
[1, 2, 3, 4] -> [1, 2, 3, 4]
[-1234] -> [-1234]

A bit of trivia: The name for this operation in the world of statistics is LOCF (last observation carried forward) imputation.

What happens if the input was [0,0]?

@KριτικσιΛίθος "...where the first value is guaranteed to be non-zero"

What if the input is [1,01]? Using, issac's Pyth answer, compare this and this.

@Eridan 01 is not a valid integer in Pyth input, so isaac doesn't have to account for that. Other answers can accept input like that if they want, just so long as they are consistent (like how isaac's answer will never produce that list as output)

@FryAmTheEggman I don't know the mechanics of Pyth, so I appreciate the explanation, thanks.

Can we error out when finished?

@tfbninja As long as the error doesn't affect your output, you can do whatever you would like. This is a site-wide default, so feel free to assume it is alright in the future!

Pyth, 6 bytes
mJ|dJQ

Demonstration
m ... Q means this maps a function over the input. The function being mapped is J|dJ. That means J = d or J in Python, since J is implicity assigned to the following value on first use. Unlike Python, assignment expressions return the value assigned in Pyth, so the map returns each successive value of J, as desired.

Jelly, 3 bytes
o@\

Try it online!
How it works
o      Take the logical OR of its arguments.
 @     Reverse the argument order of the link to the left.
  \    Do a cumulative reduce, using the link to the left.

My brain cannot comprehend... Dennis has finally found a way to permanently out golf us. Like he hadn't already. ಠ_ಠ

The explanation no longer aligns with the program

Ruby, 25 bytes
->a{a.map{|x|x==0?a:a=x}}

This is actually really evil.
Specifically, the snippet x==0 ? a : (a=x).
If I had used any other variable name for a (the previous nonzero value)—let's say y—I would have to declare it outside the map (because y=x would only have a scope of inside that single map iteration). That would use four chars more (y=0;).
But if I use the variable name a... yep, you guessed it. I'm actually reassigning to the argument that we got as input (the original array).
map doesn't care because it only cares about the original value of the thing its being called on, so this actually works.

Haskell, 21 bytes
a%0=a
a%b=b
scanl1(%)

The (anonymous) function we make is in the last line. The first two lines define a helper function.
scanl1(%) [1,0,2,0,7,7,7,0,5,0,0,0,9]
[1,1,2,2,7,7,7,7,5,5,5,5,9]

The binary function % outputs the second argument, unless it's 0, in which case it outputs the first argument instead. scanl1 iterates this function over the input list, outputting the result at each step.

J, 8 bytes
{:@-.&0\

This is a unary function, invoked as follows.
   f =: {:@-.&0\
   f 2 0 0 4 0 _1 0
2 2 2 4 4 _1 _1

Explanation
{:@-.&0\
       \  Map over non-empty prefixes:
   -.      remove all occurrences
     &0    of the number 0 and
{:@        take the last element.

Can you replicate by absolute value instead of removing 0s?

@ThomasKwa That was my first attempt. It's {:@(#~|)\, so one byte longer.

Sed, 8
/^0$/g
h

/^0$/ matches a zero on a line - if so g copies the hold space to the pattern space
h copies the pattern space to the hold space

Integers are newline separated.  e.g:
$ printf -- "-1\n0\n5\n0\n0\n7\n" | sed -f zerocover.sed
-1
-1
5
5
5
7
$

Javascript ES6, 19 bytes
s=>s.map(i=>p=i||p)

Straightforward solution, loop through input, assign p to current element i or to p if i is 0 and output it.
Example run (assigning anonymous function to f):
>> f([1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9])
<< Array [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9]

Whenever I run this I get an error saying "can't find variable p"

@Downgoat That's because the interpreter is a Strict Mode only interpreter. If you don't run that code in strict mode, it should work.

@wizzwizz4 ohh,r okay

@wizzwizz4 Strict mode is silly.

@SuperJedi224 It's not silly. It's very useful; it makes sure your code is not ambiguous, and will work even with a major update, and doesn't use undefined behaviour, etc. But what's silly is enabling it by default, since Strict mode doesn't specify a way to turn itself off, and if you don't put the strict mode string at the beginning, you don't want it and/or are code-golfing.

Dyalog APL, 12 10 9 bytes
(⊃0~⍨,⍨)\

Inspired by @Zgarb's J answer.
(⊃0~⍨,⍨)\      Monadic function:
        \      Cumulative reduce by
(⊃0~⍨,⍨)       the dyadic function:
     ,⍨           Arguments concatenated in reverse order
  0~⍨             With zeroes removed
 ⊃                Take the first element

Try it here.

Retina, 15 bytes
+`(\S+) 0
$1 $1

Try it online.
Repeatedly replaces a number followed by a zero with twice that number until the string stops changing.

Java, 78
int[]f(int[]a){for(int i=-1,b=i;++i<a.length;a[i]=b=a[i]==0?b:a[i]);return a;}

Here we just keep track of the last non-zero and shove it in where appropriate. Seems like the obvious way to do it.

76, took off a couple:
int[]f(int[]a){for(int i=0;++i<a.length;a[i]=a[i]==0?a[i-1]:a[i]);return a;}
Try it online!

Python 2, 29 bytes
while 1:x=input()or x;print x

Takes input as numbers given one per line, and outputs in the same format. Terminates with error after finishing.
Using the short-circuiting nature of or, the variable x is updated to the input, unless that input is 0 (which is Falsey), in which case it remains its current value. Then, x is printed. Note that since the first list value is nonzero, x is not evaluated in the right hand side before it is assigned.

This is 6 bytes in Pyth, and suppresses the error: #\nJ|EJ

Pyth, 8 bytes
t.u|YNQ0

Uses .u (cumulative reduce) by | (Python's or), with base case 0.

@isaacg It seems like .u is longer even if J and K are tied up. Is it ever optimal?

It was (at least afaik) here. It usually helps when you would want all the results for some reason.

Prolog (SWI), 54 bytes
[X,0|T]+[X,X|Y]:-[X|T]+[X|Y].
[X|T]+[X|Y]:-T+Y.
[]+[].

Try it online!
Explanation
I'm really happy with this answer.
First we say that the empty list is the solution of the empty list:
[]+[].

Then we say that [X,X|Y] is the solution of [X,0|T], if by removing the second entry of each of the remaining solutions.
[X,0|T]+[X,X|Y]:-[X|T]+[X|Y].

Lastly we say that any thing left over is valid if they start with the same value and the rest of the the two lists match each other.
If that explanation isn't working for you here is the code translated into Haskell:
g(a:0:x)=a:g(a:x)
g(a:x)=a:g x
g x=x

Try it online!

Very concise! I like how some functional and logic programming languages allow you to do such a literal translation of the rules. It's such a natural way to write it!

46 bytes

Japt, 8 7 bytes
N£U=XªU

Pretty simple. Takes input separated by commas. Try it online!
Ungolfed and explanation
N£    U=Xª U
NmXYZ{U=X||U

        // Implicit: N = input, U = first item
NmXYZ{  // Map each item X to:
U=Z||U  //  Set U to (X || U) and return.
        //  If X is non-zero, this sets U to X.
        //  Otherwise, this leaves U as the last non-zero we've encountered.
        // Implicit: output last expression

4-byte version:
Nå!ª

Explanation:
Nå!ª
Nå!||
NåXY{Y||X}

        // Implicit: N = input, U = first item
NåXY{   // Cumulatively reduce N; take each item Y and prev value X,
Y||X}   //  and return Y if it is non-zero; return X otherwise.
        // Implicit: output last expression

Try it online!

Wait, ª is OR, rather than º? Is º AND by any chance?

@cairdcoinheringaahing Nope, º is ((. They were assigned by Unicode value as I found the need for them :P ªnd and ºr is genius though, I might use that for Japt 2.0...

Mathematica 38 bytes
Pattern matching repeatedly replaces ...a,0,... with ...a,a...
#//.{b___,a_/;a!=0,0,e___}:>{b,a,a,e}&

Matlab, 41 46 bytes
This is inspired in my original answer, with the following differences:

Use logical indexing instead of nonzeros.
Double logical negation instead of comparing with 0.
The transpose can be removed, as the output format is flexible
Removing an intermediate variable.

Thanks to Tom Carpenter for item 4, and for his suggestion to use a program instead of a function; together these allowed a reduction of 5 bytes.
x=input('');u=x(~~x);disp(u(cumsum(~~x)))

Example:
>> x=input('');u=x(~~x);disp(u(cumsum(~~x)))
[4 0 3 2 0 5 6 0]
     4     4     3     2     2     5     6     6

You can save one byte by converting it to a program - use x=input('') instead of the function declaration, and disp(u(t) instead of the y= bit. Also, you can save four more bytes by getting rid of the t variable, yielding x=input('');u=x(~~x);disp(u(cumsum(~~x))) for 41.

@TomCarpenter Thanks a lot! Edited

I don't have Matlab, but @(x)x(~~x)(cumsum(~~x)) works in Octave.

@alephalpha Matlab doesn't allow iterated indexing.

Gol><>, 8 bytes
IE;:Z~:N

Input and output are newline separated numbers.
Explanation:
I         push next integer to stack
 E;       halt if EOF
   :Z~    remove top stack element if 0
      :N  print top stack element while also keeping it on the stack
          wrap around code implicitly

Try it online here.

GolfScript, 10 bytes
~{1$or}*]`

This program takes input from stdin, in the form of a GolfScript array literal (e.g. [1 0 2 0]), and writes its output to stdout in the same format (e.g. [1 1 2 2]).
Try it online.
A function (taking and returning a GolfScript array) would be three bytes longer, due to the need to wrap it in a block and assign it to a symbol:
{[{1$or}*]}:f

Of course, if only the function body (i.e. [{1$or}*]) is counted, then I can actually save one byte compared to the stand-alone program.

Perhaps not surprisingly, the new, shorter version turned out very similar to Dennis's CJam entry. It wins by one byte because GolfScript reads the input automatically, and thus doesn't need an extra command for that.

Minkolang 0.14, 12 10 bytes
$I?.nd?xdN

Try it here. Input can be given as in the question, but without brackets.
Explanation
$I      Push the length of the input on the stack.
  ?.    If this is 0, stop. Otherwise, continue.

nd        Take number from input and duplicate it.
  ?x      If this number is 0, dump the top of stack.
    dN    Duplicate the top of stack and output as number

Minkolang is toroidal, so this loops around to the beginning and keeps going until it hits the . and stops.

R, 39 37 33 bytes
function(x)zoo::na.locf(x*(x|NA))

This is an unnamed function that accepts a vector and returns a vector. It requires the zoo package to be installed. Note that it doesn't require zoo to be attached to the namespace since we're referencing it directly.
The name for this operation in the world of statistics is LOCF imputation, where LOCF stands for Last Observation Carried Forward. To accomplish this in R, we can use na.locf from the zoo package, which replaces NA values with the last known non-NA value. We just have to replace the zeros in the input with NAs first.
To do that, we use x|NA, which will be TRUE when x != 0 and NA otherwise. If we multiply this by x, the TRUE elements are replaced by the corresponding elements of x and the NAs stay NA, thereby replacing all zeros. This is then passed to zoo::na.locf which gives us exactly what we want.
Saved 4 bytes thanks to flodel!

O,  31 bytes
[[I',T%T/]{n#}d]{n.{:V}{;V}?}d]

This takes an input separated by , and outputs the same list in [].
7,0,3,0,0,2,-50,0,0 => [7,7,3,3,3,2,-50,-50,-50]

Explanation:

[                             ] Put result into array
 [I',T%T/]{n#}d]                Format input into array of numbers
                {n.{:V}{;V}?}d  Fill in zeros (see below for how this works)

17 bytes
I~]{n.{:V}{;V}?}d

Takes input as a list of numbers separated by spaces using postfix notation and can only handle single digit hexadecimal numbers. Negatives are postfixed with _.
5 4 0 0 1 0 0 => 5 4 4 4 1 1 1
A 3 0 0 1 B 0 => 10 3 3 3 1 11 11
67* 0 0 78* 0 => 42 42 42 56 56
67*_ 4 3_ 0 0 => -42 4 -3 -3 -3

Explanation:

I~]               Puts input into integer array
   {           }d For each number in the input
    n.{;V}{:V}?   If the number is 0, push V
                  If not, set V to the number

You can save two bytes with I~]{n.{:V}{;V}?}d. I wonder if d should just put the value on the stack instead of n...

Are you sure O can handle this? I can't find the way to pass it -42 satisfying the “your output should be an acceptable input for your submission” requirement.

@manatwork I've got a better version now that works for -42, but it adds brackets around the output.

, 7 chars / 12 bytes
ïⓜa=$⋎a

Try it here (Firefox only).
Explanation
        // implicit: ï = input array
ïⓜ     // map over input
  a=    // set a to:
    $   // (if element is truthy (not 0)) element itself
     ⋎a // else whatever a was set to before
        // implicit output

R, 36 bytes
function(x)x[cummax(seq(a=x)*(!!x))]

Let's see how this works using x=
c(1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9)

as an example. Here, !!x will be the logical (True/False) vector:
c(T, F, T, F, T, T, T, F, T, F, F, F, T)

Also, seq(a=x) gives a vector of indices as long as x:
c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

We multiply both, giving:
c(1, 0, 3, 0, 5, 6, 7, 0, 9, 0, 0, 0, 13)

We take the cumulative maximum:
c(1, 1, 3, 3, 5, 6, 7, 7, 9, 9, 9, 9, 13)

Finally, we use that last vector as the indices to extract from x:
c(1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9)

I believe x[cummax(seq(!x)*!!x] is 3 bytes shorter and equivalent.

Rust, 100 bytes
fn f(i:&[i64])->Vec<i64>{let(mut o,mut l)=(i.to_vec(),0);
for x in&mut o{if *x==0{*x=l}else{l=*x}};o}

Stumbled across this challenge, thought I'd try it in my favorite language. Tried using [T]::windows_mut() at first, before finding out that it doesn't exist. And it might've actually been longer than this. Anyway, it turns out that golfed Rust is very ugly and very not-competitive (especially with all those goshdarned esoterics!)1
The newline isn't included in the bytecount; it's only there so you don't have to scroll sideways. It doesn't change the meaning of the code.
Ungolfed:
fn cover_zeroes(input: &[i64]) -> Vec<i64> {
    let mut output = input.to_vec();
    let mut last_nonzero = 0;
    for item in &mut output {
        if *item == 0 {
            *item = last_nonzero;
        }
        else {
            last_nonzero = *item;
        }
    }
    output
}

[1] At least it's not as bad as Java.

"At least it's not as bad as Java"? Ahem... ;)

@Geobits Oh, right. I was counting on you needing that public static void main boilerplate…

Husk, 2 bytes
G|

Try it online!
scan from left with or.

CJam, 11 bytes
q~{1$e|}*]p

Try it online.
How it works
q~             Read and evaluate all input.
  {    }*      Fold; for each element but the first:
   1$e|          Copy the previous element and take their logical OR.
         ]p   Wrap all results in an array and print it.

Powershell, 32 bytes
param($x)$x|%{($t=($_,$t)[!$_])}

$x|%{...} does the script block for each element in $x. ($_,$t) is an array of current element and $t, and [!$_] means that we use !$_ to index into the array. The index will be 0 (false) for non-zero elements and 1 (true) when current element is zero, so $t will be either current element or $t. The parentheses surround the assignment expression so its value is emitted. Without parantheses it would be just a "quiet" assignment to $t.

@TimmyD, you are right, of course. I've added param($x) which turns this into a program. The output is a collection of integers which you can submit as a parameter to the program, e.g. $a = .\program.ps1 1,2,3,4,0,0,5 and then .\program.ps1 $a works as expected.

$args|%{($p=($_,$p)[!$_])} - 26 bytes using $args.

Milky Way 1.2.1, 33 bytes
:y;=<:&{~<?{0b_^;:3≤_;}1-}^<Ω!

This assumes that the list of integers is solely on the stack.

Explanation
:    : :           :              # duplicate the TOS
 y                                # push the length of the TOS
  ;               ;    ;          # swap the TOS and STOS
   =                              # dump a list to the stack
    < <    <                 <    # rotate the stack leftward
        &{~                }      # while loop
            ?{  _     _ }         # if-else statements
              0     3    1        # push an integer
               b                  # == on the TOS and STOS
                 ^          ^     # pop the TOS without output
                     ≤            # rotate the top N stack elements leftward
                          -       # subtract the TOS from the STOS
                              Ω   # push a list made of the top N stack elements
                               !  # output the TOS

I'm pretty sure that TOS and STOS mean Top of Stack and Second-to-Top of Stack, is this right?

Yep @FlagAsSpam

Julia, 33 bytes
g(x,a=0)=[(i!=0&&(a=i);a)for i=x]

This is a function g that accepts an array and returns an array. We start a temporary variable a at 0. For each element i of the input, if i isn't 0 then we assign a to i. If i is 0, a doesn't change at that iteration. We use a as the value in that position in the output array.

Perl 6, 21 bytes
*.map: {$_=($^a||$_)}

usage:
# store the Whatever lambda as a subroutine
# just so that we don't have to repeat it
my &code = *.map: {$_=($^a||$_)}

say code [1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9];
# (1 1 2 2 7 7 7 7 5 5 5 5 9)

say [-1, 0, 5, 0, 0, -7].&code;
# (-1 -1 5 5 5 -7)

say ([1, 0, 0, 0, 0, 0],[-1, 0, 5, 0, 0, -7]).map: &code;
# ((1 1 1 1 1 1) (-1 -1 5 5 5 -7))

Japt, 3 bytes
å!ª

Try it
å!ª     :Implicit input of array
å       :Cumulatively reduce
 !      :Flip the arguments
  ª     :Logical OR

05AB1E, 7 bytes
εĀiyU}X

Try it online!
My first try, using 05AB1E
ε       for each y in input
  Āi    if > 0
    yU  save current value in X
  }
  X     push X
        implicitly close for-loop and print list

Perl 6, 16 bytes
*.map($ [R||]=*)

Try it online!
Maps each element to the reverse logical OR with the previous calculated element. I wish I could do something like {[\R||] $_} but the R operator doesn't quite work that way.

Zsh, 21 bytes
for i;echo $[n=i?i:n]

Try it online!
We use echo instead of <<< because we need to set n. Using <<<$[n=i?i:n] expands $[n=i?i:n] in a subshell, which will prevent n from ever being set.

k4, 15 bytes
{^\?[0=x;0N;x]}

   ?[        ]  / vector conditional ?[cond;true;false]; eg ?[010b;2 2 2;3 3 3] -> 3 2 3
 ^\             / fills nulls (0N) with preceding value

Prolog (SWI), 44 bytes
f(0,B,B).
f(A,_,A).
X*O:-scanl(f,X,0,[_|O]).

Try it online!

Arturo, 32 29 bytes
$=>[0map&'x->(0=x)?[<=]-><=x]

Try it
$=>[          ; a function where input is assigned to &
    0         ; push 0 to stack
    map&'x->  ; map over input, assign current elt to x
    (0=x)?    ; is the current element zero?
    [<=]      ; then duplicate top of stack
    ->        ; otherwise,
        <=x   ; push x and duplicate it
]             ; end function

Thunno 2, 3 bytes
Ʋs|

Attempt This Online!
Explanation
Ʋs|  # Implicit input
Ʋ    # Cumulative reduce by:
 s|  #  Swapped logical OR
     # Implicit output

Nekomata, 4 bytes
pZ‼l

Attempt This Online!
Find the last nonzero element in each prefix of the input array.
pZ‼l
p       For each prefix:
 Z‼     Remove zeros
   l    Last element

Arcyóu, 44 bytes
(F(L)(f x(_(_ L))(L((F(i)(?(L i)i($([ i))))x

This is an anonymous function taking one argument.
Explanation:
(F(L)               ; Anonymous function F(L)
  (f x (_ (_ L))    ; For x in range(len(L))
    (L              ; Implicit indexing
      (F(i)         ; Anonymous function F(i)
        (? (L i)    ; If L[i] is not 0:
          i         ; Return i; otherwise:
          ($ ([ i)) ; Recurse ($) with i decremented
        )           ; Then, we call this new function on x
      )             ; And use the return value as the index from line 3
      x             ; No final close-parens

Labyrinth, 21 bytes
The top half seems a bit wasteful, but I'm not sure what to do about it...
""?"
" #"
;  ;
,\!:
@

I/O via linefeed-delimited lists.
Try it online.
The idea is to keep the last printed thing on the stack and discard zeroes whenever we find them.

Mathematica, 28 27 25 bytes
Saved 2 bytes thanks to Martin Büttner.
If[#2==0,##]&~FoldList~#&

If[#2==0,##]&~FoldList~#&?

C 45 Bytes
#define F(a,s) while(s--) *a=*a?*a++:*(a++-1)

Here's my test program
Go easy as it's my first try at code golf.
#include <stdio.h>

#define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0]))
#define F(a,s) while(s--) *a=*a?*a++:*(a++-1)

void printSolutions(int * solutions, int size)
{
  do {
    printf("%d ", *solutions++);
  } while (--size > 0);
  printf("\n");
}

int main(int argc, char * argv[])
{
  static int testCase1[] = {1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9};
  static int testCase2[] = {1, 0, 0, 0, 0, 0};
  static int testCase3[] = {-1, 0, 5, 0, 0, -7};
  static int testCase4[] = {23, 0, 0, -42, 0, 0, 0};
  static int testCase5[] = {1, 2, 3, 4};
  static int testCase6[] = {-1234};
  int * p;
  int s;
  printSolutions(testCase1, ARRAYSIZE(testCase1));
  s = ARRAYSIZE(testCase1);
  p = testCase1;
  F(p, s);
  printSolutions(testCase1, ARRAYSIZE(testCase1));
  printSolutions(testCase2, ARRAYSIZE(testCase2));
  s = ARRAYSIZE(testCase2);
  p = testCase2;
  F(p, s);
  printSolutions(testCase2, ARRAYSIZE(testCase2));
  printSolutions(testCase3, ARRAYSIZE(testCase3));
  s = ARRAYSIZE(testCase3);
  p = testCase3;
  F(p, s);
  printSolutions(testCase3, ARRAYSIZE(testCase3));
  printSolutions(testCase4, ARRAYSIZE(testCase4));
  s = ARRAYSIZE(testCase4);
  p = testCase4;
  F(p, s);
  printSolutions(testCase4, ARRAYSIZE(testCase4));
  printSolutions(testCase5, ARRAYSIZE(testCase5));
  s = ARRAYSIZE(testCase5);
  p = testCase5;
  F(p, s);
  printSolutions(testCase5, ARRAYSIZE(testCase5));
  printSolutions(testCase6, ARRAYSIZE(testCase6));
  s = ARRAYSIZE(testCase6);
  p = testCase6;
  F(p, s);
  printSolutions(testCase6, ARRAYSIZE(testCase6));

  return 0;
}

Running your test program on Ideone.com doesn't seem to work - it just duplicates the first number.

That's strange.  I don't see where I'm relying on undefined behavior.  Maybe some compiler optimization gone wrong?

Yeah, I'm not sure, either (I'm not super-well-versed in C). Both CodingGrounds and codepad have the same behavior.

Also, welcome to Programming Puzzles & Code Golf!

Thanks, slow day in work and I usually just read through these...

Factor, 36 bytes
[ 0 [ dup 0 = -rot ? ] accumulate* ]

(Only works locally in Factor 0.98 or later. TIO is missing accumulate*.) ¯\_(ツ)_/¯
Explanation

0 Push a zero to the data stack for accumulate* to use later. This is a 'starter' element so that a binary operation can be performed on something with the first element of the input sequence.
[ dup 0 = -rot ? ] Push a quotation to the data stack for accumulate* to use later. This is a function that says "Return the non-zero input if possible. Otherwise, return the second input." Shorter but harder to read than [ [ nip ] unless-zero ].
accumulate* Like reduce, except the intermediate results are mapped into a sequence of the same size as the input sequence.

K (ngn/k), 9 bytes
{y+x*~y}\

Try it online!
Take the cumulative sums of the input, resetting to 0 whenever a new non-zero value is encountered in the list.
If the 0's in the input are replaced with nulls (0N), ^\ (fill-scan) suffices for two bytes.

Groovy, 34 25 bytes
f={it.collect{it?n=it:n}}

Try it online!
A more readable solution:
f = { // define new closure
  it.collect { // taking advantage of implicit "it". collect applies the closure
               // on every element in order and returns the new, mapped array
    it ? // Groovy Boolean evaluation: 0 = false, 1+ = true
    n = it // assign value to holding variable (if not 0). assignments are expressions
    :
    n // in Groovy, if no return, last expression evaluated is returned
  } // same as above, returns the mapped array
} // end of closure

Groovy is supposed to be similar to Java (and it is), but the Java answer is more than two times longer. Just something to think about.
EDIT: reduced it by 9 bytes(!) by not declaring the n variable beforehand (saves 6 bytes), and using a ternary operator instead of an if (saves 3 bytes)

Vyxal, 2 bytes
ɖ∨

Try it Online!

rs, 14 bytes
+(\S+) 0/\1 \1

1 byte shorter than Retina!!
Live demo and test cases.

Seriously, 12 bytes
0╗,`╜@;I;╗`M

Try it online
Explanation:
0╗,    initialize first register to 0 and get input
`...`M map the function over the input:
  ╜@;I    push the result of (a if a else <value in register 0>)
  ;╗      dupe result and push to register 0

I was thinking this challenge had no seriously answer...and rather than check, I sat down and wrote this exact solution byte-for-byte.

@quintopia Hush, people are going to think you're my sock :P

Gema, 21 characters
0=$p
<N>=@set{p;$0}$0

Sample run:
bash-4.3$ gema '0=$p;<N>=@set{p;$0}$0' <<< '23 0 0 -42 0 0 0'
23 23 23 -42 -42 -42 -42

JavaScript, 20 Bytes
a=>a.map(b=>c=b?b:c)

Explanation:
a=>           // Define anonymous function which takes argument a
  a.map(      // Loop through input
    b=>       // Looping function
      c=b     // Assign c to the loop value (returns b)
      ?b:c    // Ternary Operator: If b (previous expression) is truthy (Non-zero integers are) return b else return c (last value)
)

b||c saves one byte over b?b:c.

Although then you just end up with @Dendrobium's answer.

His is surperior, I don't want to impersonate him

(I hadn't seen his answer when I wrote my first comment.)

You're fine, but if his is better, than is better so be it.

Perl 5 + -pl, 9 bytes
$;=$_||=$

Try it online!
Explanation
This reads each number in as $_ (-p), then sets $; to $_, after first setting $_ to $; if $_ is falsy (0) and is implicitly printed (-p). Requires -l as otherwise $_ would include \n which would mean 0 isn't falsy. The final ; can be omitted as -p (well, specifically the -n part of -p) adds while(<STDIN>){ ... ;} around your code, resulting in $; at the end.

QBasic, 54 bytes
INPUT n
FOR i=1TO n
INPUT x
IF x=0THEN x=p
?x
p=x
NEXT

Input is the length of the list, followed by the numbers in the list one at a time. (Compare this I/O default, which is the same basic idea even though it refers specifically to passing an array to a function.)
You can try it at Archive.org.
Ungolfed
INPUT arrayLength
FOR i = 1 TO arrayLength
  INPUT number
  IF number = 0 THEN number = previous
  PRINT number
  previous = number
NEXT i

Is there somewhere I can test this? It has been too long since I've written any variant of Basic for me to remember any syntax, etc. I'm sure it is fine, but I always like to check for my own questions!

Sure--you can run it at Archive.org, though you have to type it in by hand.

Batch 147 bytes
@Set A=%* &@Setlocal EnableDelayedExpansion
@Set "L=%A: ="&If .!C!==. Set "C=%"
@Set "A=%A: ="&2>nul Set/AL/L&&Set/AC=L&<nul Set/p=!C! &Set "L=%"

Approach:
Update Value to output only when value is non zero
How:
Line one: Arg asssignment and environment prep. Defines the array from arg to the batch file IE: 4 1 0 2 4 3
Line two: Uses a substring operation for each whitespace present in the string with an if condition to isolate the first substring preceding a space for assignment to Last and CCurrent variables.
Line three: Uses Substring modification to iterate through the array from each space in the substring; divides the Last value by itself and on command success (&&) transfers the Last value to Current. (a 0 value results in divide by zero error, redirected to nul). Current value is output after each step of the substitution.

Example Input / output:
4 3 2 0 3
4 3 2 2 3

TI-Basic, 37 bytes
Prompt A
For(I,2,dim(ʟA
ʟA(I)+ʟA(I-1)not(ʟA(I→ʟA(I
End

Output is stored in ʟA.

Python 3.8 (pre-release), 44 bytes
g=lambda l,s=0:l and[a:=l[0]or s]+g(l[1:],a)

Try it online!

05AB1E, 6 bytes
Å»‚0Kθ

Unfortunately 05AB1E lacks a logical-OR builtin, and a bitwise-OR isn't what we want here.
Try it online or verify all test cases.
Explanation:
Å»      # Cumulative left-reduce the (implicit) input-list by:
  ‚     #  Pair the current and previous integers together
   0K   #  Remove any potential 0
     θ  #  And pop and push the last item of this singleton-list/pair
        # (after which the result is output implicitly)

MathGolf, 7 bytes
êæαç┤o╘

Prints all values on a separated line to STDOUT.
Try it online.
Explanation:
ê       # Push the input as integer-array
 æ      # Foreach over these integers, using four characters as inner code-block:
  α     #  Wrap the top two values on the stack into a list
        #  (the first iteration will pair with an implicit 0)
   ç    #  Remove all 0s (falsey filter)
    ┤   #  Push it's last item to the stack (unfortunately doesn't pop the list)
     o  #  Print it with trailing newline (without popping)
 ╘      # After the foreach: empty the stack (otherwise it would implicitly output the
        # entire stack; feel free to remove it in the TIO-link to see the difference)

Ly, 19 bytes
&nry[p[s!]plu9`oy]p

Try it online!
This works by running through all the numbers on the list and remember the current number if it's non-zero.  Then it unconditionally deleted the current character and what's printed is whatever number is in the backup cell.
&nr                  - read all the nunbers into the stack, reverse them
   y[p          y]   - loop while the stack length is >0
      [  ]           - if/then, true is current number !=0
       s             - save the number to the backup cell
        !            - flip to 0 to exit the loop
                  p  - delete loop boolean so it doesn't print
          p          - delete current number
           lu        - load backup cell and print
             9`o     - print a LF

Clojure, 49 bytes
#(reduce(fn[c i](conj c(if(= i 0)(last c)i)))[]%)

Well this is very boring. TIO

Desmos, 80 bytes
L=l[1...i-1]
A=L[LL>0]
f(l)=[\{l[i]=0:A[A.\length],l[i]\}\for i=[1...l.\length]]

Most likely golfable, though I don't see anything at the moment.
Try It On Desmos!
Try It On Desmos! - Prettified