text:
Bitflip and negate
Given an integer, make an expression that produces it from 0 using unary negation - and bitwise complement ~ (~n = -n-1), with the operators applied right to left.
...
-3  = ~-~-~0
-2  = ~-~0
-1  = ~0
 0  = 0
 1  = -~0
 2  = -~-~0
 3  = -~-~-~0
...

Your expression must be as short as possible, which means no redundant parts of ~~, --, -0, or 00. Output or print the expression as a string or a sequence of characters.

var QUESTION_ID=92598,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/92598/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

So... you want us to put our thing down, flip it and reverse it?

whitespace between ~ and 0 allowed?

No, output the strings exactly.

Obligatory https://xkcd.com/153/

Python, 32 bytes
lambda x:("-~"*abs(x))[x<0:]+"0"

Anonymous lambda function. Given an integer x writes "-~" abs(x) times and  removes the first char if x is negative, then a zero is added to the end.

Aw, beat me to it.

I just wrote the same too - with n in the place of x and ' in the place of " :)

@JonathanAllan Then you can safely consider it a dupe.

JavaScript (ES6), 33 31 bytes
f=x=>x<0?"~"+f(~x):x&&"-"+f(-x)

Recursion < built-ins < loops (at least in this case). Basically unevaluates the input:

if it's less than 0, flip it and add a ~ to the string;
if it's more than 0, negate it and add a - to the string;
if it's exactly 0, return 0.

Takes advantage of this pattern:
 0         = 0
-1 = ~( 0) = ~0
+1 = -(-1) = -~0
-2 = ~(+1) = ~-~0
+2 = -(-2) = -~-~0
-3 = ~(+2) = ~-~-~0
+3 = -(-3) = -~-~-~0
etc.

Pyth, 14 13 12 Bytes
_<>0Q+0sm"~-

-2 Bytes thanks to @StevenH.
test suite
Decided to try out Pyth, so i translated my python answer to it. Any help welcome!
Explanation:
_<>0Q+0sm"~-
        m"~-     # Map "~-" onto the input (= a list of n times "~-").
       s         # Join the list to a string.
     +0          # Add "0" in front.
 <>0Q            # Slice off the last char if the input is negative.
_                # Reverse the whole thing.

Use implicit input at the end to save one byte: >0 instead of <Q0

@StevenH. Thank you! Now we're in a tie with the shortest answer!

Very different solution (that, unfortunately, doesn't save any bytes): tW>0Q_+0sm"~-

@StevenH.   Golfed your solution down to 12: _<>0Q+0sm"~- I hope your okay with me adding this to my solution.

C, 46 bytes
m(x){putchar(x?x<0?126:45:48);x&&m(-x-(x<0));}

Unlike most (all?) other answers, this one outputs the operators ~ and - one by one.

05AB1E, 14 13 bytes
Ä„-~×¹0‹i¦}0J

Explanation
 „-~           # the string "-~"
Ä   ×          # repeated abs(input) times
     ¹0‹i¦}    # if input is negative, remove the first char
           0J  # join with 0

Try it online!

Retina, 19 17 bytes
Replace the number with unary, with a zero on the end. Replace each 1 with -~. Remove double negative if there is one.
\d+
$*10
1
-~
--

Try it online
All test cases at once (slightly modified program to support multiple test cases)

17: http://retina.tryitonline.net/#code=JShHYApcZCsKJCoxMAoxCi1-Ci0tCg&input=LTMKLTIKLTEKMAoxCjIKMw

Perl 38 35 33 (23 + 1 for -p) 24
s/\d+/"-~"x$&.0/e;s;--;

-13 thanks to Dada

You probably meant -p instead of -r.  Also you can get rid of those last parenthesis and semicolon : if$h<0 is enough.

I did, thanks. I've been writing too many answers in sed I guess.

Probably, yea. (Get rid of the last 2 parenthesis too)

You can also save 2 bytes by doing $h<0&&s;.; instead of s/.// if $h<0. (-p adds a ; at the end of the code, so no need for the last ; of s;.;;. And a if b is roughly equivalent to b && a, but in this case it saves you one byte because you can remove the space)

Thanks, I didn't know -p added a ; too.

A 25 bytes version : perl -l60pe 's/\d+/"-~"x$&/e;s;--;'

@Dada got it down to 24 by appending a 0 in the substitution instead of using -l60

Very neat. Have a +1

Haskell, 41 bytes
f n=['-'|n>0]++(tail$[1..abs n]>>"-~")++"0"
f n|n<0=tail$f(-n)|x<-[1..n]>>"-~"=x++"0"

Thanks to nimi for 3 bytes

tail fails for n=0. You can use drop 1 instead.

@nimi Thanks; I have no idea how I missed that..

Don't waste the otherwise guard: f n|n<0=tail.f$abs n|x<-[1..n]>>"-~"=x++"0".

2 bytes to save: ...|n<0=tail$f(-n)|....

Dyalog APL, 18 bytes
'0',⍨0∘>↓'-~'⍴⍨2×|

'0',⍨ character zero appended to
0∘> negativeness (i.e. 1 for numbers under 0; 0 for zero and up)
↓ dropped from
'-~'⍴⍨ the string "~-" cyclically reshaped to length
2× two times
| the absolute value
+ plus
0∘< positiveness (i.e 1 for numbers over 0)
TryAPL online!

V, 21 bytes
/ä
é
D@"ña-~ñá0kgJó--

Try it online!
V has very limited number support, and it actually has no concept of negative numbers. This means in order to support negatives (or even 0), we have to use some hacky workarounds.
Explanation:
/ä                  "Move forward to the first digit
é                   "And enter a newline
D                   "Delete this number, into register '"'
 @"                 "That number times:
   ñ   ñ            "Repeat the following:
    a               "  Append the string:
     -~             "  '-~'
        á0          "Append a 0
          k         "Move up a line
           gJ       "And join these two lines together
             ó--    "Remove the text '--', if it exists

JavaScript (ES6), 39 37 bytes
x=>"-~".repeat(x<0?-x:x).slice(x<0)+0

Saved 2 bytes thanks to @Neil

Ruby, 34 bytes
->x{("-~"*x.abs+?0)[2[0<=>x]..-1]}

Jelly, 10 bytes
A⁾-~ẋḊẋ¡N0

This is a full program. Try it online!
How it works
A⁾-~ẋḊẋ¡N0  Main link. Argument: n

A           Take the absolute value of n.
 ⁾-~ẋ       Repeat the string "-~" that many times. Result: s
       ¡    Conditional application:
     Ḋ        Dequeue; remove the first element of s...
      ẋ N     if s, repeated -n times, is non-empty.
         0  Print the previous return value. Set the return value to 0.
            (implicit) Print the final return value.

Java 7, 95 79 bytes
79 bytes:
String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;}

Ungolfed:
String s(int x) {
    String t = x<0 ? "~" : "";
    while((x<0 ? ++x : x--) != 0)
        t += "-~";
    return t+0;
}

Old version (95 bytes):
String s(int x){return new String(new char[x<0?-x:x]).replace("\0","-~").substring(x<0?1:0)+0;}

Usage:
class A {
    public static void main(String[]a) {
        System.out.println(s(-3));
        System.out.println(s(-2));
        System.out.println(s(-1));
        System.out.println(s(0));
        System.out.println(s(1));
        System.out.println(s(2));
        System.out.println(s(3));
    }
    static String s(int x){String t=x<0?"~":"";while((x<0?++x:x--)!=0)t+="-~";return t+0;}
}

Try it here!
Output:
~-~-~0
~-~0
~0
0
-~0
-~-~0
-~-~-~0

Hi, and welcome to PPCG! Nice first post!

Welcome to PPCG! Hmm, that's a shorter solution than mine, so I will delete my answer and upvote yours instead. :)

EXCEL: 55 33 bytes
=REPT("-~",IF(A1>0,A1,ABS(A1)-1))&"0"

Input is in the form of putting a number in the A1 cell. Formula can go anywhere except A1.

I don't think it works for negative numbers...

CJam, 18 14 bytes
Took some inspiration from Emigna's answer to save 4 bytes.
li_z"-~"*\0<>0

Try it online! (As a linefeed-separated test suite.)
Explanation
li      e# Read input and convert to integer N.
_z      e# Duplicate and get |N|.
"-~"*   e# Repeat this string |N| times.
\0<     e# Use the other copy of N to check if it's negative.
>       e# If so, discard the first '-'.
0       e# Put a 0 at the end.

T-SQL, 87 bytes
select substring(replicate('-~',abs(x)),case when x<0then 2 else 1 end,x*x+1)+'0'from #

The x*x+1 condition in substring is sufficient, since x^2+1>=2*abs(x) for all x.
As usually in SQL, the input is stored in a table:
create table # (x int)

insert into # values (0)
insert into # values (1)
insert into # values (-1)
insert into # values (2)
insert into # values (-2)

Vim - 31 keystrokes
First vim golf, prolly missed a ton of stuff.
`i-~<esc>:s/-\~-/\~-/dwp<left>ii<esc><left>d$@"<esc>a0`

Nice, welcome to the club! :) You could do :s/^- instead of :s/-\~/\~- and D instead of d$

Now that I think about it, I don't think this handles 0. You could get around this by incrementing before deleting with <C-a> and then deleting two characters off the end.

@DJMcMayhem oh, 0i doesn't work?

No, unfortunately not. 0 moves the cursor to the first character on the current row. You can sorta use 0 as a count in V though.

Matlab, 61 bytes
x=input('');A=repmat('-~',1,abs(x));disp([A((x<0)+1:end) 48])

Pyke, 14 13 bytes
X,"-~"*Q0<>0+

Try it here!

Perl 6, 25 bytes
{substr '-~'x.abs~0,0>$_}

Explanation:
{
  substr
    # string repeat ｢-~｣ by the absolute value of the input
    '-~' x .abs

    # concatenate 0 to that
    ~ 0

    ,

    # ignore the first character of the string if it is negative
    0 > $_
}

Jelly, 14 12 bytes
-2 bytes thanks to @Dennis (return 0 rather than concatenate "0", making this a full program only.)
0>‘
A⁾-~ẋṫÇ0

Test it at TryItOnline
How?
0>‘      - link 1 takes an argument, the input
0>       - greater than 0? 1 if true 0 if false
  ‘      - increment

A⁾-~ẋṫÇ0 - main link takes an argument, the input
      Ç  - y = result of previous link as a monad
A        - x = absolute value of input
 ⁾-~     - the string "-~"
    ẋ    - repeat the sting x times
     ṫ   - tail repeatedString[y:] (y will be 1 or 2, Jelly lists are 1-based)
       0 - implicit print then return 0

><>, 18 + 3 = 22 bytes
:?!n0$-:0):1go-
-~

Try it online! +3 bytes for the  -v flag to initialise the stack with the input. If assuming that STDIN is empty is okay, then the following is a byte shorter:
:?!ni*:0):1go-
-~

The program keeps flipping the input n as necessary until it reaches 0, after which it errors out.
[Loop]
:?!n      If n is 0, output it as a num. If this happens then the stack is now
          empty, and the next subtraction fails
0$-       Subtract n from 0
:0)       Push (n > 0)
:1go      Output the char at (n>0, 1) which is a char from the second line
-         Subtract, overall updating n -> -n-(n>0)

PseudoD, 688 579 521 bytes
utilizar mate.pseudo
utilizar entsal.pseudo
adquirir n
adquirir a
adquirir r
adquirir i
fijar n a llamar LeerPalabra finargs
si son iguales n y CERO
escribir {0}
salir
fin
fijar a a llamar ValorAbsoluto n finargs
fijar i a CERO
si comparar Importar.Ent.Comparar n < CERO
fijar r a {~}
sino
fijar r a {-}
fin
mientras comparar Importar.Ent.Comparar i < a
escribir r finargs
si son iguales r y {~}
fijar r a {-}
Importar.Ent.Sumar i UNO i
sino
fijar r a {~}
fin
finbucle
si son iguales r y {~}
escribir {~}
fin
escribir {0}

Explain:
Read a number from STDIN;
If the number is zero (0); Then:
    Writes 0 to STDOUT and exits;
End If;
If the number is less than zero (0); Then:
    Set the fill character to "~";
Else:
    Set the fill character to "-";
End If;
For i = 0; While i is less than abs(number); do:
    Write the fill character to STDOUT;
    If the fill character is "~":
        Set the fill character to "-"
        Increment i by one
    Else:
        Set the fill character to "~"
    End if;
End for;
If the fill character is "~"; Then:
    Write "~" to STDOUT;
End If;
Write "0" to STDOUT

Welcome to PPCG! Is that as small as it gets? I see some long identifiers you could probably shorten ("relleno" to "r", menos relleno :P). I think you can drop the imports for standard lib if it's only a function or code snippet too. It doesn't ask for trailing newline on output, so maybe you can change the last EscribirLinea to Escribir. Can you assign functions to shorter names(adquirir e``fijar p a Escribir)?

Octave, 51 bytes
x=input('');[("-~"'*[1:abs(x)>0])((x<0)+1:end),'0']

At first blatantly copying the Matlab approach by @pajonk and then modifying some details, rewriting as an "outer product" between a vector of ones and the characters "-~" and abusing on-the-fly-indexing (or what it could be called) lets us save some bytes. It still pains me slightly that I can't get the index expression to take fewer bytes.
Octave allows a(i1)(i2) or even (...)(i1)(i2) for indexing where Matlab would want us to store variables in between the indexings.
((x<0)+1:end)

is far too long to describe "skip first if". There must be a better way.

PHP, 61 bytes
if(0>$n=$argv[1]){echo"~";$n=~$n;}echo str_repeat("-~",$n),0;

PHP, 58 bytes
<?=((0<$a=$argv[1])?'-':'').str_pad('0',2*abs($a),'~-',0);

Labyrinth, 25 bytes
`?+#~.
.  ; 6
54_"#2
  @!

Try it online!
Explanation
I really like the control flow in this one. The IP runs in a figure 8 (or actually a ∞, I guess) through the code to reduce the input slowly to 0 while printing the corresponding characters.
The code starts in the upper left corner going right. The ` doesn't do anything right now. ? reads the input and + adds it to the implicit zero below. Of course that doesn't do anything either, but when we run over this code again, ? will push a zero (because we're at EOF), and + will then get rid of that zero.
Next the # pushes the stack depth, simply to ensure that there's a positive value on the stack to make the IP turn south, and ; discards it again.
The " is a no-op and acts as the main branch of the code. There are three cases to distinguish:

If the current value is positive, the IP turns right (west) and completes one round of the left loop:
_45.`?+
_45      Push 45.
   .     Print as character '-'.
    `    Negate the current value (thereby applying the unary minus).
     ?+  Does nothing.

If the current value is negative, the IP turns left (east) and the following code is run:
#26.~
#        Push stack depth, 1.
 26      Turn it into a 126.
   .     Print as character '~'.
    ~    Bitwise NOT of the current value (applying the ~).

Note that these two will alternate (since both change the sign of the input) until the input value is reduced to zero. At that point...
When the current value is zero, the IP simply keeps moving south, and executes the ! and then turns west onto the @. ! prints the 0 and @ terminates the program.

GolfScript, 30 24 20 bytes

Saved 6 bytes thanks to xnor.
Saved 4 bytes thanks to Dennis.

~."-~"\abs*\0<{(;}*0
Input: -5
Output: -5 = ~-~-~-~-~0
Explanation
~.     # Input to integer and duplicate
"-~"   # We shall output a repetition of this string
\abs   # Move the input onto the stack and computes abs
*      # Multiply "-~" for abs(input) times
\      # Copy onto the stack the input
0<     # Is it less than 0?
{(;}*  # Yes: remove first '-' from the output
0      # Push 0

Try it online!

You don't have to print the 2 = , just the -~-~0.

You can use {(;}*0 instead of {(;}{}if 0.


text:
Constructible n-gons
A constructible \$n\$-gon is a regular polygon with n sides that you can construct with only a compass and an unmarked ruler.
As stated by Gauss, the only \$n\$ for which a \$n\$-gon is constructible is a product of any number of distinct Fermat primes and a power of \$2\$ (ie. \$n = 2^k \times p_1 \times p_2 \times ...\$ with \$k\$ being an integer and every \$p_i\$ some distinct Fermat prime).
A Fermat prime is a prime which can be expressed as \$2^{2^n}+1\$ with \$n\$ a positive integer. The only known Fermat primes are for \$n = 0, 1, 2, 3 \text{ and } 4\$
The challenge
Given an integer \$n>2\$, say if the \$n\$-gon is constructible or not.
Specification
Your program or function should take an integer or a string representing said integer (either in unary, binary, decimal or any other base) and return or print a truthy or falsy value.
This is code-golf, so shortest answer wins, standard loopholes apply.
Relevant OEIS
Examples
3 -> True
9 -> False
17 -> True
1024 -> True
65537 -> True
67109888 -> True
67109889 -> False

Jelly, 7 5 bytes
Thanks to Sp3000 for saving 2 bytes.
ÆṪBSỊ

Uses the following classification:

These are also the numbers for which phi(n) is a power of 2.

Where phi is Euler's totient function.
ÆṪ        # Compute φ(n).
  B       # Convert to binary.
   S      # Sum bits.
    Ị     # Check whether it's less than or equal to 1. This can only be the
          # case if the binary representation was of the form [1 0 0 ... 0], i.e.
          e# a power of 2.

Try it online!
Alternatively (credits to xnor):
ÆṪ’BP
ÆṪ        # Compute φ(n).
  ’       # Decrement.
   B      # Convert to binary.
    P     # Product. This is 1 iff all bits in the binary representation are
          # 1, which means that φ(n) is a power of 2.

A direct port of my Mathematica answer is two bytes longer:
ÆṪ        # Compute φ(n).
  µ       # Start a new monadic chain, to apply to φ(n).
   ÆṪ     # Compute φ(φ(n)).
      H   # Compute φ(n)/2.
     =    # Check for equality.

I don't know Jelly, but could you perhaps check power of 2 by factoring and checking if the maximum is 2? You can also check if the bitwise AND of it and its predecessor is 0.

@xnor Hm, good idea but my attempts at that are the same length. If there's a way to check if a list is of length 1 in less than 3 bytes, it would be shorter though (by using the factorisation function that just gives a list of exponents). I can't find a way to do that though.

I see there's E to check if all element of a list are equal. What if you double the number, factor it, and check if all factors are equal?

@xnor That's also a nice idea. :) That would probably be 6 bytes then, but Sp3000 pointed out that there's B and Ị which let me test it in 5.

Ah, nice. Any chance that decrement, then binary, then product is shorter?

@xnor That would also be 5: ÆṪ’BP

Mathematica, 24 bytes
e=EulerPhi
e@e@#==e@#/2&

Uses the following classification from OEIS:

Computable as numbers such that cototient-of-totient equals the totient-of-totient.

The totient φ(x) of an integer x is the number of positive integers below x that are coprime to x. The cototient is the number of positive integers that aren't, i.e. x-φ(x). If the totient is equal to the cototient, that means that the totient of φ(x) == x/2.
The more straightforward classification

These are also the numbers for which phi(n) is a power of 2.

ends up being a byte longer:
IntegerQ@Log2@EulerPhi@#&

What are cototients and totients? And are cototient-of-totients and totient-of-totients ratios?

@Qwerp-Derp The totient of n is the number of integers below n that are coprime to n, and the cototient is the number of integers below n that aren't. I'll edit in a link.

Mathematica's built-in will never stop to amaze me

@Qwerp-Derp As for your second question it just means that you compute the (co)totient of the totient of n.

Retina, 51 50 bytes
0+$

+`^(.*)(?=(.{16}|.{8}|....|..?)$)0*\1$
$1
^1$

Input is in binary. The first two lines divide by a power of two, the next two divide by all known Fermat primes (if in fact the number is a product of Fermat primes). Edit: Saved 1 byte thanks to @Martin Ender♦.

binary input is fine, as well as the assumption about Fermat primes

JavaScript (ES7), 61 bytes
n=>[...Array(5)].map((_,i)=>n%(i=2**2**i+1)?0:n/=i)&&!(n&n-1)

Actually, 6 bytes
This answer is based on xnor's algorithm in Martin Ender's Jelly answer. Golfing suggestions welcome. Try it online!
▒D├♂≈π

How it works
         Implicit input n.
▒        totient(n)
 D       Decrement.
  ├      Convert to binary (as string).
   ♂≈    Convert each char into an int.
     π   Take the product of those binary digits.
         If the result is 1,
           then bin(totient(n) - 1) is a string of 1s, and totient(n) is power of two.

Batch, 97 bytes
@set/pn=
@for /l %%a in (4,-1,0)do @set/a"p=1<<(1<<%%a),n/=p*!(n%%-~p)+1"
@cmd/cset/a"!(n-1&n)"

Input is on stdin in decimal. This is actually 1 byte shorter than calculating the powers of powers of 2 iteratively. I saved 1 byte by using @xnor's power of 2 check.

source: Stack Exchange

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

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

sort: votes


text:
UNIX Uniq Uknow?
Challenge
You must write a program which takes a string and a flag as input and performs one of the following functions.
Input
If your language does not support command line arguments, you may take the arguments as input via STDIN.
The flag will be two characters: a dash and an ASCII character such as -d or -c.
Functions
The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.
Counting: -c
This counts the number of duplicate lines in the input file. For example, if the input is:
aa
aa
bb
bb
bb
xx

The output will be:
2 aa
3 bb
1 xx

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.
Duplication: -d
This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx), the output would be:
aa
bb

Because these are lines which have been duplicated. You should only output each line once.
Duplication: -D
This is almost the same as -d except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:
aa
aa
bb
bb
bb

Because aa occurs twice and bb occurs three times.
Unique: -u
Similar to above except it only prints unique lines. For example, using the example file, the output will be:
xx

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.
Example
Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie

The output for each of the flags would be:
-c
4 apple pie
1 dog
2 hello world
1 zebra

-d
apple pie
hello world

-D
apple pie
apple pie
apple pie
apple pie
hello world
hello world

-u
dog
zebra

Rules
Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.
All output should be to STDOUT.
The file will only ever contain lowercase, alphabetical characters, newlines and spaces:
abcdefghijklmnopqrstuvwxyz

The output should be sorted alphabetically.
In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.
As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.
Winning
As this is code-golf, the shortest code in bytes wins.

Would ["foo", "bar"], "-c" be considered a valid input? (array of strings + flag as separated string)

@Arnauld Yes, it would

Perl, 92 + 4 (-sn flags) = 96 bytes
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h

This code needs to be in a file to run. And it needs -sn flags, as well as -M5.010 (free).
For instance :
$ cat input.txt
hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
$ cat prog.pl
$h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h
$ perl -M5.010 -sn prog.pl -c < input.txt
4 apple pie
1 dog
2 hello world
1 zebra

GNU sed, 496 485 + 2(rn flags) = 487 bytes
1h;1b;$bb;2{:r;$!N;$!br;s/.*/echo "&"|sort/e};:b;x;/[dD]/bd;/c/bc;/u/!b;x;s/^/\n/
s/(\n.*)\1+//g;s/\n//p;b;:d;x;/^(.*)\n\1/!D;:l;x;/D/{x;P;x};x;s/^[^\n]*\n//
/^(.*)\n\1/bl;P;D;:c;s/$/#/;G;x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;:i;s/9(@*:)/@\1/;ti;s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/;s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/@+:/1&/;y/@/0/;bc};s/:/ /;s/[^\n]*$/1:&/;bc;:p;x;s/...//;s/..$//;s/:/ /gp

The code size is not going to compete, but it was fun emulating the uniq command. I wanted to add a simple selection sort to get rid of the sort call, thus solving it in pure sed only, but the code got too long already. The input is read entirely from STDIN, with the flag expected on the first line.
Run:
(echo "-c";cat input_file)|sed -rnf uniq_emulator.sed

Output:
4 apple pie
1 dog
2 hello world
1 zebra

Initially submitted code and explanation: (sections are separated by an extra newline)
# The main
    # store the flag in hold space and start next cycle
1h;1b
    # usually a cycle starts with each line read, but I also start it manually,
    #so I need to skip some lines that should run only once
$bb
2{
        # read the entire input into pattern space
    :r;$!N;$!br
        # executes a shell call to sort the pattern space
    s/.*/echo "&"|sort/e
}
    # based on the flag, the appropriate jumps to "functions" are made
:b;x;/[dD]/bd;/c/bc;/u/!b

# Unique: -u
    # all duplicate lines are deleted and what remains is printed
x;s/^/\n/;s/(\n.*)\1+//g
s/\n//p;b

# Duplication: -d and -D
    # if the first 2 lines are different, delete the first and start new cycle
:d;x;/^(.*)\n\1/!D
:l
        # if -D, print the first duplicate line
    x;/D/{x;P;x};x
        # otherwise (-d), delete the first duplicate line
    s/^[^\n]*\n//
        # loop condition, go back to :l if the first 2 lines are duplicate
/^(.*)\n\1/bl
    # print only the first line and start a new cycle
P;D

# Counting: -c
    # in order to count line occurrences, I simulate reading the input again
    # In a loop I append all pattern space to hold space, delete first line of
    #pattern space and from hold space all lines except the first one appended.
:c;s/$/#/;G
x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/
    # if the new line "read" is the same as the previous one, increment the
    #counter of that line (format is "counter:line"), delete and go back to :c
/([^:\n]*)\n\1$/{s/\n[^\n]*$//;bi;:I;bc}
    # otherwise, stop the counter for the previous line, add a counter for the
    #current one and go back to :c
s/:/ /;s/[^\n]*$/1:&/;bc
    # when the loop ends, the hold space with all counts is printed
:p;x;s/...//;s/..$//;s/:/ /gp

# Increment function that works by manually updating the changing digit(s)
:i;s/9(@*:)/@\1/;ti
s/8(@*:)/9\1/;s/7(@*:)/8\1/;s/6(@*:)/7\1/
s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/;s/0(@*:)/1\1/
s/@+:/1&/;y/@/0/;tI

Can you save a few bytes by putting your increment function inline, instead of breaking it out? I only see it being used once, so you could delete the call (bi;:I) and return (tI) for 7 bytes.

@Riley Yes, you're right. I pasted that increment f. from another program of mine and thought to leave it separate for easier explanation. I'll apply the change soon. Good catch and thanks for taking the time to read all that.

I definitely didn't understand all of it, there is still a lot for me to learn.

@Riley Yesterday I had no more edits available, today I changed it. Bytes count dropped by 8 (;tI), plus 1 I spotted during the edit.

R, 128 bytes
Using a different method than @Billywob and implemented as a unnamed function
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}

Ungolfed
function(s,o){
   R=rle(sort(s));               # do the run length encoding for the sorted input
   cat(                          # output to STDOUT
      switch(o                   # switch on option to provide output lines
        ,'-d'=R$v[R$l>1]         # RLE values with length > 1
        ,'-D'=s[s%in%R$v[R$l>1]] # string values in RLE values with length > 1
        ,'-c'=paste(R$l,R$v)     # RLE length and values pasted together
        ,'-u'=R$v[R$l<2]         # RLE values with length < 2, eg 1
       )
      ,sep='
'                                # set separator to carriage return
   )
}

Test Run
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}
> s = c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")
> f =
function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep='
')}
> f(s, "-c")
4 apple pie
1 dog
2 hello world
1 zebra
> f(s, "-d")
apple pie
hello world
> f(s, "-D")
hello world
apple pie
hello world
apple pie
apple pie
apple pie
> f(s, "-u")
dog
zebra
>

Clever use of rle and switch, +1!

JavaScript (V8),  170 164  140 bytes
Expects (array_of_strings)(flag_string). Prints the output.
a=>c=>[...new Set(a)].sort().map(k=>(a.map(v=>n+=v==k,n=0),o={c:n+' '+k,d:n>1&&k,D:n>1&&Array(n).fill(k).join`
`,u:n<2&&k}[c[1]])&&print(o))

Try it online!

R, 179 bytes
f=function(s,o){s=sort(s);n="\n";z=cat;for(i in unique(s)){v=sum(s%in%i);if(v>1&o=="-d")z(i,n);if(o=="-c")z(v, i,n);if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="");if(o=="-u"&v<2)z(i,n)}}

Input
Input is assumed to be an "R-vector" of strings (inspired by @Arnauld's JS array input, see below) and a string containing the type of function e.g. -d.
Example
An example of how to execute the function where I pre-define the vector of strings (not necessary).
strings <- c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie")

f(strings,"-c")
f(strings, "-d")
f(strings,"-D")
f(strings, "-u")

Ungolfed
f=function(s,o){
    s=sort(s)                   # sort vector alphabetically
    n="\n"                      # generate string for newline (used 5x times)
    z=cat                       # generate alias for cat (used 4x times)
    for(i in unique(s)){        # for each unique string of vector
        v=sum(s%in%i)           # count number of occurences
        if(o=="-d"&v>1)z(i,n)   # if occurences >1 & "-d": print each unique string
        if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="") # repeat string #occurences and then print
        if(o=="-u"&v<2)z(i,n)   # if occurences <2 & "-u": print each uniquely occuring string
        if(o=="-c")z(v,i,n)     # if "-c": print number of occurence and each unique string
   }
}

I'm sure this can be golfed further by shortening the control flow statements but couldn't figure out a smart way to do it yet.

It is generally acceptable to have the functions as unnamed, so you can save yourself a couple.

Bash(coreutils, grep), 265 bytes
IFS=$'\n'
for l in `sort -u $1`;do r=$r$(grep -c "$l" $1)" $l\n"
done
case $2 in -c)printf $r;;-d)printf $r|grep -v "1.*"|cut -d' ' -f2-;;-D)s=$(sort $1)
for l in `sh $0 $1 -u`;do s=$(grep -v "$l"<<<"$s")
done
echo "$s";;-u)printf $r|grep "1.*"|cut -d' ' -f2-;;esac

Usage
$ sh unique.bash input -D
apple pie
apple pie
apple pie
apple pie
hello world
hello world
$ sh unique.bash input -c
4 apple pie
1 dog
2 hello world
1 zebra
$ sh unique.bash input -u
dog
zebra
$ sh unique.bash input -d
apple pie
hello world

Explanation

Constructs $r which is the output of -c. To construct it, it uses sort -u which sorts the input file and returns only unique results (I know, somewhat cheat but it wasn't specified in the rules. Feel free to ignore the answer if you don't like it :-). Also, it uses grep -c to count the occurrences of each word.
For -d it gets the output of -c and with grep it prints everything that does not start with 1. With cut it ignores the first column (number of occurrences).
For -u it does exactly the same as -d except from grep, where it selects everything that starts with 1.
For -D it get the sorted input and remove all the words that are printed with -u in a for loop by using grep -v again.

jq -r, 115 bytes
Takes an array of strings and the flag as separate string.
group_by(.)|map(select(has(1)))as$m|{c:map("\(length) \(.[0])"),d:[$m[][0]],D:[$m[][]],u:[.-$m|.[][]]}[input[1:]][]

Example and explanation:
echo '["aa", "aa", "bb", "bb", "bb", "xx"] "-c"' | jq -r '
  group_by(.) |                  # sort and group by item
  map(select(has(1))) as $m |    # store the slice of non-uniques
  {                              # create a lookup object
    c: map("\(length) \(.[0])"), # map to length and one item
    d: [    $m    [][0]],        # take one of each from the slice
    D: [    $m    [][ ]],        # take all of them from the slice
    u: [. - $m | .[][ ]]         # subtract the slice from the input
  }                              #     and take all of them
  [input[1:]]                    # lookup by the 2nd char of flag
  []                             # iterate and output
'

2 aa
3 bb
1 xx

Try it online!

J, 84 bytes
('cDdu'i.1{[)>@{[:(~.@]((],' ',[)&":"p.;D;~.@D;[-.D=.#~]*1<])1#.=@])@/:~];._1@(LF,])

Try it online!
A bit cumbersome, but I've progressively golfed it down from about 100b. I expect more golfing opportunities may be had, but I'm not quite sure where at this point.
Explanation
This answer can be divided into a bunch of components. Here's an easier to read version of the above (Try it online!) (technically functions slightly differently since we're not actually doing answer_list@sort, but rather, (answer_list@/:)~, which is happens to be the same thing.)
get_index =: 'cDdu' i. 1 { [
lines =: ];._1@(LF , ])
sort =: /:~
multi_dup =: #~ ] * 1 < ]
only_once =: [ -. multi_dup
single_dup =: ~.@multi_dup
count_list =: (] , ' ' , [)&":"1 0
counts =: 1 #. =@]
unique =: ~.@]
answer_list =: unique (count_list ; multi_dup ; single_dup ; only_once) counts
uniq_ans =: get_index pick answer_list@sort@lines

Python 2, 115 bytes
f,a=input()
f=ord(f[1])%5
for w in sorted(set(a)):C=a.count(w);exec"print'%d '%C*(f>3)+w;"*[C>1,0,C<2,(C>1)*C,1][f]

Example:
golf % python2.7 uniq.py <<<'["-c",["hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"]]'
4 apple pie
1 dog
2 hello world
1 zebra

Lua, 270 Bytes
Well, that ended being way longer than I though it would, but I'm happy with it.
Takes in a filename via command-line and forms two array while reading it's content (t={line, repetitions} and T={index, line}). Sorts T then outputs via STDOUT depending on the flag.
f,m=...io.input(f)t={}T={}for l in io.lines()do
l=l.."\n"t[l]=t[l]and t[l]+1or 1T[#T+1]=t[l]<2 and l or nil
end
table.sort(T)o=""for i=1,#T
do
k=T[i]v=t[k]o=o..(m=="-c"and v.." "..k
or m=="-D"and k:rep(v)or
m=="-d"and v>1 and k
or m=="-u" and v<2 and k or'')end
print(o)

Explanation
f,m=...                        -- shorthands for the inputs
io.input(f)                    -- set the file f as the current input stream
t={}                           -- set the array linking a line to its number of occurrence
T={}                           -- set the array containing each line once for sorting purpose
for l in io.lines()            -- iterate over each line in the file
do
    l=l.."\n"                  -- add a newline at the end of it
    t[l]=t[l]                  -- if it's not the first time we see this line
           and t[l]+1          -- increment its number of occurence
         or 1                  -- else set it to 1 occurence
    T[#T+1]=t[l]<2 and l or nil-- and set it in our listing
end
table.sort(T)                  -- sort the list of line
o=""                           -- initialise the output to an empty string
for i=1,#T                     -- iterate over each entry in T
do
    k=T[i]                     -- shorthand for the line's string
    v=t[k]                     -- shorthand for its number of occurence

    -- the following nested ternaries are basically a chained if/elseif
    o=o..                      -- at the end of our current output string
      (m=="-c"                 -- if the flag is -c(ount)
          and v.." "..k        -- add the number of occurrence and the corresponding string
        or m=="-D"             -- if the flag is -D(uplicates)
          and k:rep(v)         -- add v times the line
      or m=="-d" and v>1       -- if the flag is -d(uplicates) and it has appeared >2 times
          and k                -- add this line
      or m=="-u" and v<2       -- if the flag is -u(niq) and it has appeared only once
          and k                -- add this line
        or '')                 -- if neither of these cases are true, had an empty string
end
print(o)                       -- output what we formatted previously :)

Java, 19(import java.util.*;) + 315 = 334 bytes
String f(String[]r,String q){TreeMap<String,Integer>m=new TreeMap();for(String s:r)m.put(s,m.get(s)==null?1:m.get(s)+1);int a=q.charAt(1),v;String o="",k;for(Map.Entry<String,Integer>e:m.entrySet()){v=e.getValue();k=e.getKey()+"\n";while(68==a&&v-->1)o+=k;o+='u'==a&&v<2||'d'==a&&v>1?k:99==a?v+" "+k:"";}return o;}}

Usage
String[] input = {"hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"};
System.out.println("-c");
System.out.println(f(input,"-c"));
System.out.println("-d");
System.out.println(f(input,"-d"));
System.out.println("-D");
System.out.println(f(input,"-D"));
System.out.println("-u");
System.out.println(f(input,"-u"));

Output
-c
4 apple pie
1 dog
2 hello world
1 zebra

-d
apple pie
hello world

-D
apple pie
apple pie
apple pie
hello world

-u
dog
zebra

Explanation
A TreeMap<String, Integer> is used to store pairs of words and how many times they were repeated. The TreeMap is sorted so no extra call to sort it is required. Ternary operator is used to construct the output string regarding the input argument.

Vyxal, 44 bytes
⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋

Try it Online!
A fun little answer that gets to use a list of lambdas. Takes input as flag, list of lines.
Explained
⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋
                             W               # Wrap the stack into a single list:
⁽R                                           # A function that reverses each item in a list
  ‡'tċ;vh                                    # A function that keeps only non-unique items
         ‡'tċ¬;vh                            # A function that keeps only unique items
                 ≬'tċ;ƛ÷$wẋ;f                # A function that repeats non-unique items by their count
                              ‛Ǎ⟇?tḟi        # Get the function at index "cdu".find(input[-1])
                                     $sĊ$†   # Call that function on a list of the counts of each item in the input, sorted alphabetically
                                          W⁋ # Wrap into a single list (needed because of a bug) and join on newlines.

05AB1E, 25 24 bytes
C|ÅγøíIÅγ2@ÏIDÅγÏDŠK)ćè»

05AB1E doesn't support custom system arguments, so it takes the inputs through STDIN.
The first input-line is the flag, and every other input-line is the input-file.
Try it online or verify all four flags.
Explanation:
C         # Convert the first (implicit) input-flag from a binary-string to an integer†
|         # Get all other input-lines as a list of strings
 Åγ       # Run-length encode it, and push the list of values and counts separated to
          # the stack
   ø      # Pair the values and lengths together
    í     # Reverse each from [value,count] to [count,value]
I         # Push the list of input-lines again
 Åγ       # Run-length encode it again
   2@     # Check for each count if it's >=2
     Ï    # Only leave the values at the truthy indices
I         # Push the list of input-lines yet again
 D        # Duplicate it
  Åγ      # Run-length encode it a third time
    Ï     # Only leave the values at the truthy (==1) indices
     D    # Duplicate this list of unique items
      Š   # Triple-swap the input,unique,unique lines to unique,input,unique lines
       K  # Remove the unique lines from the input
)         # Wrap the entire stack into a list
 ć        # Extract head; pop list and push remainder-list and first item separately to
          # the stack
  è       # Use that C(input-flag) to 0-based modular index it into the list
   »      # Join each inner list by spaces first (for the list of [count,value] pairs),
          # and then join each string by newlines
          # (after which the result is output implicitly)

† C on strings basically gets the index of each character in the string 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт ΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³\nµ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ•, and then converts this list of indices to a base-2 integer:

Flag
C
0-based modular index

"-c"
252
0

"-d"
253
1

"-D"
270
2

"-u"
227
3

Groovy (185 Bytes)
Golf'd:
x={m,l->u=[];u.addAll(l);u.unique();c=u.collect{v->[v,l.count{it==v}]};D=c.collect{a,b->if (b>1){(1..b).collect{a}}};D.remove(null);m=='d'?D.collect{it.unique()}:['D':D,'c':c,'u':u][m]}

https://groovyconsole.appspot.com/edit/5173563388592128
Ungolf'd (Kinda):
x = {
    m,l->
        u=[];
        u.addAll(l);
        u.unique();
        c = u.collect {
            v->
                [v, l.count {it==v}]
        }
        D = c.collect {
            a,b->
                if (b>1) {
                    (1..b).collect{a}
                }
        }
        D.remove(null)
        m == 'd' ? D.collect{it.unique()} : ['D':D,'c':c,'u':u][m]
}

Output

u Results aa bb xx

c Results [aa, 3] [bb, 2] [xx, 1]

D Results [aa, aa, aa] [bb, bb]

d Results [aa] [bb]

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

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


text:
The Path to the Result
Input:
A grid of varying size only containing numbers in the range 00-99, the following four characters: ^; >; v; <, and spaces to fill (and new-lines of course).
Output:
The result of the sum (integer) when you follow the path.
How does this work?
You start at the arrow with the highest number, and follow the path the arrows point to.
For each of the four arrows we'll do a different arithmetic calculation:

> = Addition (+);
< = Subtraction (−);
^ = Multiplication (* or × or ·);
v = Real / Calculator Division (/ or ÷);

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the arithmetic operation than the examples, then that is of course completely acceptable.)
Challenge rules:

You can choose the input (to some extent). A string-array would be most logical I think, but a symbol/newline-separated single string is also fine. (Full functions as input that are simply executed in the actual code snippet aren't allowed!)
Trailing spaces for the input are optional.
Numbers 0-9 will have a leading 0 so all numbers plus arrow are of an equal three-character length.
The number & arrow will always have the following format: DDA (D being a digit; A being one of the four arrows).
You use the current value with the previous arithmetic operation (the example below explains this better).
The final arithmetic operation can be ignored because of the rule above.
It is possible to have DDA's in the input-grid that aren't being used in the path to the resulting sum.
There won't be any test-cases for arrows that form a loop.
There won't be any test-cases for dividing by 0.
There won't be any test-cases where dividing creates a decimal sum-result. You only have to worry about integers.
EDIT: Since there weren't any answer yet, I decided to change the grids slightly to perhaps make it easier. I know this is usually not recommended to do with challenges, but since no answers were given yet, I think this will make it slightly easier, giving more (/any) answers:
The spaces between de DDA's are random. There could even be no spaces in between at all. All DDA's and spaces are grouped per three. Also, it is possible to have no spaces between DDA's at all.

Example:
Input:
94>      66v
   05v   08<
         43>
   03>   00^

Path it follows:
Path it follows   |   Current sum value
________________________________________
94>               |   94  (highest value)
66v               |   160 (+)
08<               |   20  (/)
05v               |   15  (-)
03>               |   5   (/)
00^               |   5   (+)
43>               |   215 (*)
                          '>' after 43 is ignored because it's the last number

Output: 215
General Rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:
94>      66v           ->     215
   05v   08<
         43>
   03>   00^

77>   80v55^02<        ->     -19
      20>   14^

22>11>15>80>14v        ->     -16
18^17>      10v
00^   90v43^02v
07^11<15<22v01<

99>98>97>96>95>94v     ->     102
93>92>   91v   03<

I keep finding -12 for the third test case...

@PaulPicard Ah, I'm so sorry, there was a mistake in the grid.. 07< has been changed to 07^ to fix this.

Could somebody please tell me what I'm misunderstanding with the second one? As I see it, it is: 77+80/20+14*2-55=-11.3 without order of operations.

@Dopapp You start at the highest value, so it's 80/20+14*2-55=-19

Python 2, 409 390 377 bytes
def f(p):
 p=map(lambda s:map(lambda d:d==3*(' ',)and(0,-1)or(int(d[0]+d[1]),'><^v'.index(d[2])),zip(s[::3],s[1::3],s[2::3])),p);x,y=max([(x,y)for x in range(len(p[0]))for y in range(len(p))],key=lambda(x,y):p[y][x][0]);r=o=0
 try:
  while 1:
   1/(y*x>=0);d=p[y][x]
   if-1<d[1]:r=eval('r%sd[0]'%'+-*/'[o]);o=d[1];a=(-(o==1),1)[o<1];b=(-(o==2),1)[o>2]
   x+=a;y+=b
 except:print r

The second and third indent levels are a raw tab and a raw tab plus a space, respectively. Markdown mangles the raw tabs, so they've been replaced by two spaces.
Ungolfed:
def follow(path):
  # Split path's strs into DDAs ((0, -1) for blank, else (int, int))
  path = map(
    lambda s: map(
      lambda dda: (0, -1) if dda == (' ', ' ', ' ') else (int(dda[0] + dda[1]), '><^v'.index(dda[2])),
      zip(s[::3], s[1::3], s[2::3])
    ),
    path
  )

  # Find highest DDA
  x, y = max([(x, y) for x in range(len(path[0])) for y in range(len(path))], key=lambda (x, y): path[y][x][0])

  result = 0
  op = 0  # addition
  try:
    # Keep following the path until we get an IndexError
    while True:
      if y < 0 or x < 0: raise IndexError

      dda = path[y][x]
      if dda[1] != -1:
        # It's not empty - do the operation & change direction
        const = dda[0]

        result = eval('result %s const' % '+-*/'[op])

        op = dda[1]

        dx = 1 if op == 0 else -1 if op == 1 else 0
        dy = 1 if op == 3 else -1 if op == 2 else 0

      # Move to the next thing
      x += dx
      y += dy
  except IndexError:
    # We've exited the path - return
    print result

Ideone it! (all test cases)

Python 2, 449 bytes
i=input();p,d,a,o,l=[-1,0],">",0,"+",0
for y in range(len(i)):
 for x in range(len(i[0])):
  if i[y][x]in"><^v":
   v=int(i[y][x-2]+i[y][x-1])
   if v>l:l=v;p=[x-2,y]
while 1:
 if d==">":p[0]+=1
 if d=="<":p[0]-=1
 if d=="^":p[1]-=1
 if d=="v":p[1]+=1
 try:
  c=i[p[1]][p[0]]
  if c in"><^v":
   d=c
   if p[0]<0 or p[1]<0:1/0
   a=eval(str(a)+o+str(int(i[p[1]][p[0]-2]+i[p[1]][p[0]-1])));o={">":"+","<":"-","^":"*","v":"/"}[c]
 except:print a;break

This takes an array of strings as input
Ungolfed:
pointer = [-1,0]
dir = ">"
output=0
operation="+"

largest = 0
for y in range(len(input)):
    for x in range(len(input[0])):
        if input[y][x] in "><^v":
            value = int(input[y][x-2]+input[y][x-1])
            if value > largest: largest = value; pointer = [x-2, y]

while 1:
    if dir==">":pointer[0]+=1
    if dir=="<":pointer[0]-=1
    if dir=="^":pointer[1]-=1
    if dir=="v":pointer[1]+=1
    try:
        current = input[pointer[1]][pointer[0]]
        if current in "><^v":
            dir = current
            value = int(input[pointer[1]][pointer[0]-2]+input[pointer[1]][pointer[0]-1])

            if pointer[0]<0 or pointer[1]<0:1/0
            output=eval(str(output)+operation+str(value))

            if current==">":operation="+"
            if current=="<":operation="-"
            if current=="^":operation="*"
            if current=="v":operation="/"

    except:
        print output;break


text:
HexaGolf: Wordagons
See also: Rotatagons
Challenge
Given a string as input, output its wordagon.
Wordagons
A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:
Firstly, you start with the first character in the string a place it in the centre:
h

Then, you take the next character in the string and add a hexagonal layer:
 e e
e h e
 e e

Then, add the next layer:
  x x x
 x e e x
x e h e x
 x e e x
  x x x

Finally, add the last layer:
   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a

And you now have the wordagon for the string hexa.
Examples
Here's some I prepared earlier:
hello
    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o

PPcg
   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g

o *
  * * *
 *     *
*   o   *
 *     *
  * * *

(T_T)
    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )

Note that trailing and/or leading newlines are allowed.
Winning
The shortest code in bytes wins.

Bonus points if someone does this in Hexagony? ;)

Can the input string contain linefeeds? I don't think it would pose any implementation problem, just produce invalid wordagons

@Aaron No, the input string will never include newlines

is it ok if the output is a string with newlines returned from a function?

@Dopapp Yes, that's fine

@KevinCruijssen You could always start a bounty ;)

Aww. I'm disappointed because I read the title as "word-dragons"...

Pyth - 29 bytes
j+_K.e+*kdjdjF+*bhk*L2>zhkztK

Test Suite.

Python 2, 83 bytes
s=input()
l=len(s)
while 1:l-=1;y=abs(l);print' '*y+' '.join(s[:y:-1]+s[y]*y+s[y:])

Prints the wordagon and then crashes (which only prints to STDERR).
Example:
% python2.7 wordagon.py <<<'"abcde"' 2&>/dev/null
    e e e e e
   e d d d d e
  e d c c c d e
 e d c b b c d e
e d c b a b c d e
 e d c b b c d e
  e d c c c d e
   e d d d d e
    e e e e e

xnor saved 5 bytes. Thanks!

Elegant solution.

You can loop through the y's by doing n=len(s)\nwhile 1:n-=1;y=abs(n);... and terminating with error.

Vim, 92 bytes
:se ri|s/./ &/g
ⓋCⓇ"Ⓓ␛$vpmlmrqqYpi ␛`ljxxhmlylv`rjlmr:s/\%V\(.\)./Ⓡ" /g
@qq@qVdy2G:g/^/m0
Gp

Circled letters represent Control + letter; ␛ is escape.

Wouldn't this be counted as keystrokes?

@moo_we_all_do No. This is [tag:code-golf] (as opposed to editor golf), so all answers should be scored in bytes.

The second @q causes an infinite loop for me.  It works perfectly if it's removed.

Mathematica 100 219 bytes
If ASCII-Art need not be Terminal-Art this should be valid.
My earlier submission mistakenly drew a star rather than a hexagon.
I can't see how I was so off!
c = CirclePoints@6;
f@s_:=Graphics[{Text[s~StringPart~1,{0,0}],Flatten@Table[Text[StringPart[s,n+1],#]&/@Subdivide[Sequence@@#,n]&/@Partition[Riffle[(n)CirclePoints@6,RotateLeft[n CirclePoints@6]],2],{n,1,StringLength@s-1}]},BaseStyle->20]

CirclePoints@6 returns the vertices of a unit hexagon, assuming that the center is at the origin.
Subdivideing the coordinates for neighboring vertices finds equally spaced positions along the respective edge.
A counter from 1 through the StringLength -1 of the input string allows each layer of the wordagon to be handled separately.
As n increases, so does the respective distance of each vertex from the origin.
Text[s~StringPart~1,{0,0}] prints the first letter of the input at the origin.

f@"Wordagon"

For the curious, this is what the star version looked like.
I know, it was way off the mark. It only showed the letters at the hexagon's vertices.
Graphics@Table[Text[Style[StringPart[#, r + 1], 54], r {Cos@t, Sin@t}], {t, 0, 2π, π/3}, {r, 0, StringLength@# - 1}] &["Hexa"]

Can you post what the star looked like? :D

Sure.  It's now posted.

Wow, that is a nice star

Ruby, 82 bytes
->s{n=s.size-1
(r=-n..n).map{|i|(" "*k=i.abs)+r.map{|j|s[[k+j,k,-j].max]}*" "}*$/}

iterates through 1-n..n-1 in both i=y and j=x directions. Without the leading spaces on each line, the output looks like the below, as a result of picking a character from s  with the index  [[i.abs+j,i.abs,-j].max]. Adding leading spaces forms the required hexagon.
f f f f
f l l l f
f l o o l f
f l o G o l f
f l o o l f
f l l l f
f f f f

Ungolfed in test program
f=->s{
  n=s.size-1             n=string length - 1
  (r=-n..n).map{|i|      iterate from -n to n, build an array of lines
    (" "*k=i.abs)+       k=i.abs. Start each line with k spaces.
    r.map{|j|            iterate from -n to n, build an array of characters.
      s[[k+j,k,-j].max]  select character from s (store null string in array if index past end of string)
    }*" "                concatenate the array of characters into a line, separated by spaces
  }*$/                   concatenate the array of lines into a single string, separate by newlines
}

puts f[gets.chomp]

Typical output
   f f f f
  f l l l f
 f l o o l f
f l o G o l f
 f l o o l f
  f l l l f
   f f f f

JavaScript (ES6), 118 bytes
s=>[...Array((l=s.length-1)*2+1)].map((_,i,a)=>a.map((_,j)=>s[Math.max(i-l,l-i,j-l,i-j,l+l-i-j)]||``).join` `).join`\n`

Where \n represents the literal newline character. Based on my answer to Hexplosive ASCII-art challenge although parts of the solution resemble @LevelRiverSt's Ruby answer. The various components of the Math.max produce the following output for l=3:
    i - l           l - i           j - l            i - j        l + l - i - j
- - - - - - -   3 3 3 3 3 3 3   - - - 0 1 2 3    0 - - - - - -    6 5 4 3 2 1 0
- - - - - - -   2 2 2 2 2 2 2   - - - 0 1 2 3    1 0 - - - - -    5 4 3 2 1 0 -
- - - - - - -   1 1 1 1 1 1 1   - - - 0 1 2 3    2 1 0 - - - -    4 3 2 1 0 - -
0 0 0 0 0 0 0   0 0 0 0 0 0 0   - - - 0 1 2 3    3 2 1 0 - - -    3 2 1 0 - - -
1 1 1 1 1 1 1   - - - - - - -   - - - 0 1 2 3    4 3 2 1 0 - -    2 1 0 - - - -
2 2 2 2 2 2 2   - - - - - - -   - - - 0 1 2 3    5 4 3 2 1 0 -    1 0 - - - - -
3 3 3 3 3 3 3   - - - - - - -   - - - 0 1 2 3    6 5 4 3 2 1 0    0 - - - - - -

The maximum value is taken, and the values greater than l are removed, thus producing the hexagon shape, while the remaining values map to characters from the string:
6 5 4 3 3 3 3      3 3 3 3          a a a a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
3 2 1 0 1 2 3   3 2 1 0 1 2 3    a x e h e x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
6 5 4 3 3 3 3      3 3 3 3          a a a a

05AB1E, 31 bytes
R.pvy`¹gN-©×NFs.ø}Sðý®ð×ì})Â¦«»

Explanation
Utilizing symmetry to only generate the top part of the hexagon, then mirroring that to form the lower part.
R.pv                     }       # for each prefix of the reversed string
                                 # ['f', 'fl', 'flo', 'floG']
    y`                           # split into chars, ex: 'f', 'l', 'o'
      ¹gN-©×                     # repeat the last char len(input)-N times,
                                 # where N is the 0-based list index of the current prefix
                                 # ex: 'oo'
            NF   }               # N times do
              s.ø                # surround current char with the next char on stack
                                 # ex: 'floolf'
                  Sðý            # insert spaces between each letter, ex: 'f l o o l f'
                     ®ð×ì        # prefix string with len(input)-N spaces
                                 # ex: '  f l o o l f'
                          )      # wrap all strings in a list
                           Â¦    # create a reversed copy of the list and
                                 # remove the first item (as we only need the middle once)
                             «»  # concatenate the lists and merge with newlines

Try it online!

Python 2, 104 bytes
def f(s):
 for n in range(len(s)*2-1):x=abs(n-len(s)+1);print' '*x+' '.join(s[x+1:][::-1]+s[x]*x+s[x:])

PHP - 202 bytes
$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(" ",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad("",$a).strrev($s).($a%2?" ":" {$w[$a]} ")."$s
";$a=abs(--$i);}

Usage from command line:
php.exe -r "put the escaped code here" "put your desired word here"

for example:
php.exe -r "$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(\" \",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad(\"\",$a).strrev($s).($a%2?\" \":\" {$w[$a]} \").\"$s\n\";$a=abs(--$i);}" "example"

Test Suite.


text:
Double rotation
Challenge Description
Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.
Examples
1: Hello world
Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution

2: codegolf
codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl

3.: empty string
(empty string) //Input
(empty string) //Output

Input
String you need to rotate. May be empty. Does not contain newlines.
Output
Rotated input string, trailing newline allowed
May be written to the screen or returned by a function.
Rules

No loopholes allowed
This is code-golf, so shortest code in bytes solving the problem wins
Program must return the correct solution

Remind me, what letters are from the first half of the alphabet, what letters are from the second?

But still, good challenge.

First half: ABCDEFGHIJKLMabcdefghijklm Second half: NOPQRSTUVWXYZnopqrstuvwxyz

Funny that codegolf becomes an anagram of itself

MATL, 29 bytes
FT"ttk2Y213:lM@*+)m)1_@^YS9M(

Try it online!
Explanation
FT        % Push arrray [0 1]
"         % For each
  t       %   Duplicate. Takes input string implicitly in the first iteration
  tk      %   Duplicate and convert to lower case
  2Y2     %   Predefined string: 'ab...yz'
  13:     %   Generate vector [1 2 ... 13]
  lM      %   Push 13 again
  @*      %   Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
  +       %   Add: this leaves [1 2 ... 13] as is in the first iteration and
          %   transforms it into [14 15 ... 26] in the second
  )       %   Index: get those letters from the string 'ab...yz'
  m       %   Ismember: logical index of elements of the input that are in
          %   that half of the alphabet
  )       %   Apply index to obtain those elements from the input
  1_@^    %   -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
  YS      %   Circular shift by 1 or -1 respectively
  9M      %   Push the logical index of affected input elements again
  (       %   Assign: put the shifted chars in their original positions
          % End for each. Implicitly display

Retina, 55 bytes
O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1

Try it online!
Uses two sorting stages to rotate the first- and second-half letters separately.

05AB1E, 44 43 42 bytes
Ðžn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?

Explanation
Generate a list of the letters of the alphabet of both cases. ['Aa','Bb', ..., 'Zz']
Ðžn2äø€J

Split into 2 parts and store a copy in the register.
2ä©

Extract the letters from the input that are a part of the 1st half of the alphabet, rotate it and store in X.
`ŠÃÁU

Extract the letters from the input that are a part of the 2nd half of the alphabet, rotate it and store in Y.
ÃÀV

Main loop
v                         # for each char in input
 ®`                       # push the lists of first and second half of the alphabet
   yåi                    # if current char is part of the 2nd half of the alphabet
      Y¬?                 # push the first char of the rotated letters in Y
         ¦V               # and remove that char from Y
           ëyåi           # else if current char is part of the 1st half of the alphabet
               X¬?        # push the first char of the rotated letters in X
                  ¦U      # and remove that char from X
                    ëy?   # else print the current char

Try it online!
Note: The leading Ð can be omitted in 2sable for a 41 byte solution.

<s>44</s> still looks like 44.

of course http://meta.codegolf.stackexchange.com/a/7427/21348 @KarlKastor

Javascript (ES6), 155 142 138 bytes
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

Edit: saved 3 4 bytes by using unshift() (inspired by edc65's answer)
How it works
The R function takes an array method as its parameter m:
R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))

It is first used with the push method to store extracted characters in a[] (first half of alphabet) and b[] (second half of alphabet). Once these arrays have been rotated, R() is called a second time with the shift method to inject the new characters in the final string.
Hence the slightly unusual syntax: R`push`  and R`shift` .
Demo

let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)

console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));

Save 1 more byte avoiding a comma a.unshift(a.pop(b.push(b.shift())))

CJam, 41 bytes
lee_{'N,_el^:A&},_1m>er_{ADf+&},_1m<erWf=

Try it online!
Uses a similar approach to my vowel shuffling answer.

Python, 211 Bytes
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
 if y(i):r+=u[-1];u=[i]
 else:r+=i
for i in r[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
print l

Best i could do. Takes the string from STDIN and prints the result to STDOUT.
alternative with 204 Bytes, but unfortunatly prints a newline after each char:
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
 if z(i):l=d[0]+l;d=[i]
 else:l=i+l
for i in l:
 a=i
 if y(i):a=u[-1];u=[i]
 print a

Python 2, 149 bytes
s=input();g=lambda(a,b):lambda c:a<c.lower()<b
for f in g('`n'),g('m{'):
 t='';u=filter(f,s)[-1:]
 for c in s:
  if f(c):c,u=u,c
  t=c+t
 s=t
print s

Not sure who downvoted you, but I made it 0 again by upvoting. Welcome to PPCG! Perhaps you could add an explanation or ideone of your code? I'm assuming here that the downvote was done automatically after the edit by Beta Decay by the Community user, based on @Dennis' comment in this answer.

JavaScript (ES6), 144
Using parseInt base 36 to separate first half, second half and other. For any character c, I evaluate y=parseInt(c,36) so that

c '0'..'9' -> y 0..9
c 'a'..'m' or 'A'..'M' -> y 10..22
c 'n'..'z' or 'N'..'Z' -> y 23..35
c any other -> y NaN

So y=parseInt(c,36), x=(y>22)+(y>9) gives x==1 for first half, x==2 for second half and x==0 for any other (as NaN > any number is false)
First step: the input string is mapped to an array of 0,1 or 2. Meanwhile all the string characters ar added to 3 arrays. At the end of this first step the array 1 and 2 are rotated in opposite directions.
Second step: the mapped array is scanned, rebuilding an output string taking each character from the 3 temporary arrays.
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop(q.push(q.shift())))).join``

Less golfed
s=>[...s].map(
  c => a[ y = parseInt(c, 36), x=(y > 22) + (y > 9)].push(c)
       && x,
  a = [ [], p=[], q=[] ]
).map(
  x => a[x].shift(),  // get the output char from the right temp array
  p.unshift(p.pop()), // rotate p
  q.push(q.shift())   // rotate q opposite direction
).join``

Test

f=
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop()),q.push(q.shift())).join``

function update() {
  O.textContent=f(I.value);
}

update()
<input id=I oninput='update()' value='Hello, world'>

Perl. 53 bytes
Includes +1 for -p
Run with the input on STDIN:
drotate.pl <<< "Hello_world"

drotate.pl:
#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g

Python, 142 133 bytes
A better variation on the theme:
import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')

ungolfed:
import re
def u(s,p):
    x = re.split('(?i)([%s])'%p,s)  # split returns a list with matches at the odd indices
    x[1::2] = x[3::2]+x[1:2]
    return ''.join(x)

def v(s):
  w = u(s[::-1],'A-M')
  return u(w[::-1],'N-Z')

prior solution:
import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')

ungolfed:
import re
def h(s,p):                              # moves matched letters toward front
    t=re.findall(p,s)                    # find all letters in s that match p
    t=t[1:]+t[:1]                        # shift the matched letters
    return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter

def f(s):
    t = h(s[::-1],'[A-Ma-m]')            # move first half letters toward end
    u = h(t[::-1],'[N-Zn-z]')            # move 2nd half letters toward front
    return u

Ruby, 89 bytes
f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]

PHP, 189 bytes
Quite hard to golf... Here is my proposal:
for($p=preg_replace,$b=$p('#[^a-m]#i','',$a=$argv[1]),$i=strlen($b)-1,$b.=$b,$c=$p('#[^n-z]#i','',$a),$c.=$c;($d=$a[$k++])!=='';)echo strpos(z.$b,$d)?$b[$i++]:(strpos(a.$c,$d)?$c[++$j]:$d);


text:
Numeric to Alphabetic Organization
I have a list of images grouped numerically (YI0.png, YI1.png...YI20479.png). I want them sorted alphabetically, like so:
YI0.png -> YIA.png
YI1.png -> YIAA.png

without my last image having 20479 As in it.
Input
A directory name.
Output
All files in that directory will be alphabetically renamed.
Constraints

The pattern is always Prefix Number.Extension
There are no subdirectories
All files in the directory adhere to the pattern
Number starts at 0
Prefix doesn't contain numbers

Example
Directory consisting of Pie0.txt, Pie1.txt, all the way to Pie11.txt would be renamed to PieA.txt, PieB.txt, all the way to PieL.txt.
If it goes to Pie28.txt, they would be renamed like so:
Pie0.txt -> PieA.txt
Pie1.txt -> PieAA.txt
Pie2.txt -> PieAB.txt
Pie3.txt -> PieB.txt
Pie28.txt -> PieZ.txt

Remember, this is code-golf, so the answer in the shortest bytes wins.

will all files in the dir be of the form "some_letters_that_are_always_the_sameNumber.txt"?

Yes, it will have a pattern of PrefixNumber.Extension @Maltysen

will be ever have three length codes?

Will the directory only have plain files or can it e.g. have subdirectories which need to be ignored or recursed into ?

Anyways, I'm not sure I like a challenge that needs to do system commands and especially filename parsing (e.g. is \\ or / the separator, can files start with . etc.) . An input that is a list of simple filenames with an output that are the corresponding translated names seems nicer to me

Can there be holes in the sequence of numbers ? Can numbers have extra leading zeros ? Can the prefix contain digits ? Does the sequence always start with 0 ?

Yes, there will be varied length codes (remember, I have 20479 files). The prefix and extension will only contain alphabetical characters. There are no subdirectories or different patterned files.

Will the numeric suffix have leading zeroes? If you sort the numbers between 1 and 100 alphabetically you get [1, 10, 100, 11, 12 ..], but if they have leading zeroes you get [001, 002, 003 ..]

@BlackCap they do not

Since there are different OS in the world, can we not write a program or function which takes a list of strings in the format you defined and outputs a list of new names in the same order as the input list such that the output list is in alphabetic order? Also can we use digits and lowercase letters in our new names (since standard alphabetic sorting would be 0<9<A<Z<a<z)?

@Jonathan Allan only letters, not numbers. Lowercase and uppercase are allowed though.

This needs a spec. At present we have to guess what it might be from two examples.

Imagine a hyperdictionary but culled to only have the amount of "words" as the numbers. Once I run the perl example I will have more examples

Perl, 65 bytes
Assumes the number sequence starts with 0 and has no holes (or duplicates if there are extra leading zeros). No error checking.
Assumes only plain files, filenames do not start with . and the user can enter the directory.
Run with the directory as argument
alphaorg.pl directory

alphaorg.pl:
#!/usr/bin/perl
chdir pop;$a=A;@F=sort map$a++,<*>;rename$_,s/\d+/$F[$&]/r for<*>

If the directory name can't contain digits and your sytem will accept / as directory separator (unix and windows do), this 61 byte version is shorter (give directory name on STDIN here):
#!/usr/bin/perl -ln
$a=A;@F=sort map$a++,@;=<$_/*>;rename$_,s/\d+/$F[$&]/r for@

Haskell - 97 bytes
I probably picked the wrong language; Haskell has painfully long names for IO operations
r p=do f<-getDirectoryContents p;sequence_.zipWith renameFile(sort f).sort$permutations['A'..'Z']

(this program has O(26^26) in run-time unless you're on a quantum computer)

Maybe I am on a Quantum Computer :^) no lol I wish though

@moo_we_all_do You could be- IBM is handing out access to a 6 qubit quantum computer at the moment (I got it, so it can't be that hard).
Unfortunately you're gonna need about 123 qubits to run this program in real time ..

I also now have access to it. If I had $100 dollars, I would pay you $100 to write this program in QASM. That would astound me!

@moo_we_all_do R x|-Zip(Sort x).Sort$Permutations['A'..'Z']. This is QML, a haskell inspired quantum language with a compiler written in haskell: sneezy.cs.nott.ac.uk/qml Obviusly you can't read files or anything yet, so you have to pass it the file names as a list of strings. It is in my opinion by far the best effort at a high level quantum language as of now. Don't ask me why he chose to have uppercase names for functions


text:
Segmented numbers
The sequence of segmented numbers or prime numbers of measurement (OEIS A002048) is the sequence of numbers such that each member is the smallest positive (greater than zero) number that can't be made of a sum of earlier consecutive numbers, with a(0) = 1.
Example
To calculate a(7) we first calculate a(0->6) = [1, 2, 4, 5, 8, 10, 14]. we then start from zero and go through numbers until we find one that is not the sum of one or more consecutive numbers in the sequence.
1  = 1
2  = 2
3  = 1 + 2
4  = 4
5  = 5
6  = 2 + 4
7  = 1 + 2 + 4
8  = 8
9  = 4 + 5
10 = 10
11 = 2 + 4 + 5
12 = 1 + 2 + 4 + 5
13 = 5 + 8
14 = 14
15 = ????

Since fifteen cannot be made by summing any consecutive subsequence and every number smaller can be fifteen is the next number in the sequence. a(7) = 15
Task
Your task is to take a number (via standard methods) and output the nth term in this sequence (via standard output methods).  This is code-golf and you will be scored as such.
Test Cases
0 -> 1
1 -> 2
2 -> 4
3 -> 5
4 -> 8
5 -> 10
6 -> 14
7 -> 15
8 -> 16
9 -> 21

Haskell, 62 58 bytes
-4 bytes thanks to @xnor!
(x:y)#z=x:filter(`notElem`scanl(+)x z)y#(x:z)
([1..]#[]!!)

Sequence is 0-indexed.

I think you need two more bytes and surround the last line with () to make it a proper function.  The partial applied !! is an operator section and must be enclosed in () to make it a function. Without it's just a snippet that only becomes a function (or "value" to use strict Haskell terms) with the missing argument.

Beautiful method! The import seems like overkill though; filter(`notElem`scanl(+)x z)y should do.

Perl, 50 49 bytes
Includes +1 for -p
Run with input on STDIN:
segmented.pl <<< 7

segmented.pl:
#!/usr/bin/perl -p
${$_-=$\}++for@F;1while${-++$\};++$#F<$_&&redo}{

Explanation
@F contains the list of (negative) sums of consecutive numbers that end with the current last number. When a new number is discovered the list is extended with 0 and then all values are decreased by the new number maintaining the invariant.
Global %:: is used as a hash mapping all (negative) numbers that have been seen (through @F) to a non-zero value.
$\ is the current number and gets increased until it reaches a value not yet in %::.
By being a bit careful about the order in which everything happens no initialization is needed, 1 will automatically become the first number.
Since the size of @F is how many numbers have been generated it can be used as a halting condition

Jelly, 14 13 11 bytes
Ḷß€Ẇ;ḅ1‘ḟ$Ṃ

Try it online!
How it works
Ḷß€Ẇ;ḅ1‘ḟ$Ṃ  Main link. Argument: n

Ḷ            Unlength; yield [0, ..., n - 1].
 ß€          Recursively map the main link over the range.
   Ẇ         Window; yield all subarrays of consecutive elements of the result.
    ;        Append n to the array of subarrays.
     ḅ1      Convert all subarrays from base 1 to integer.
             This is equivalent to S€ (sum each), but it allows ; to hook.
         $   Combine the previous two links into a monadic chain.
       ‘       Increment all sums.
        ḟ      Filter; remove the original sums from the incremented ones.
          Ṃ  Compute the minimum.

05AB1E, 17 16 bytes
Xˆ$µ>D¯ŒOså_i¼Dˆ

Explanation
Xˆ                # initialize global array to [1]
  $               # push 1 and input to stack
   µ              # while counter != input
    >             # increase variable on stack
      ¯ŒO         # list of all sums of consecutive number in global array
     D   så_i     # if current stack value is not in the list
             ¼    # increase counter
              Dˆ  # add current stack value to global array

Try it online!
Saved 1 byte thanks to Adnan

Does $ instead of Xs work?

@Adnan: Yes of course. Silly of me. Thanks!

Pyth - 19 17 bytes
Damn off-by one ruining all my implicits. (Same bytes count, literaly incrementing Q: =hQesmaYf!}TsM.:Y)
esmaYf!}TsM.:Y)1h

Test Suite.

Using reduce saves (only) one byte. Expected more... eu+Gf!}TsM.:G))hQY

@Jakube map is usually shorter for self referential sequences like these

Javascript, 125 112 110 bytes
Saved 2 bytes thanks to @Neil
f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)a.some(b=>b.includes(i))||(a[z+1]=[0,...a[z++]||[]].map(v=>i+v));alert(i-1)}

Previous answers
112 bytes thanks to @Neil:
f=n=>{a=[[]];for(i=1,z=0;z<=n;i++)if(!a.some(b=>b.includes(i))){a[z+1]=[0,...a[z++]||[]].map(v=>i+v)}alert(i-1)}

125 bytes:
f=n=>{a=[[]];for(i=1,k=z=0;z<=n;i++)if(a.every(b=>b.every(c=>c-i))){a[i]=[i].concat((a[k]||[]).map(v=>i+v));k=i,z++}alert(k)}

For b.every(c=>c-i),  I'd try !b.includes(i) or possibly !a.some(b=>b.includes(i)) works, while [0,...a[k]||[]].map(v=>i+v) might replace [i].concat((a[k]||[]).map(v=>i+v)). Also do you really need k?

Now that your if(!...){...} is only one statement, you could probably replace it with ...||(...) or ...?0:....

Husk, 12 11 bytes
!¡ö←`-NmΣQø

Try it online!
returns nth term, 1-indexed.
-1 byte from Dominic Van Essen, using empty list.
Explanation
!¡ö←`-NmΣQø
          ø start with the empty list:
 ¡ö         apply the following infinitely:
         Q  get all subsequences
       mΣ   sum each of them
    `-N     remove the sums from natural numbers
   ←        take the first one
!           get the nth element from this list

You can start with the empty list, instead of 1, for 11 bytes

Python, 113 105 92 80 bytes
s=F={1}
x=1
exec"while{x}<=s:x+=1\nF={x+j for j in{0}|F};s|=F\n"*input()
print x

The final bytes I saved were inspired by Ton’s Perl answer: my F does the same thing as his @F; my s does essentially the same thing as his %::.

JavaScript (ES6), 77 bytes
(n,a=[],s=a,i=1)=>s[i]?f(n,a,s,i+1):--n?f(n,[0,...a].map(j=>s[j+=i]=j),s,i):i

Basically a recursive port of the algorithm of @TonHospel's Perl answer.

Scala, 97 bytes
n=>{var(r,i)=Seq(1)->1;while(r.size<n+1){i+=1;r++=Set(i)--r.tails.flatMap(_.inits).map(_.sum)};i}

Try it online


text:
When is their birthday?
Donald Knuth was born in 1938, on the 20th day of Capricorn.
The first day of Capricorn is the 22nd December.
Donald Knuth was born on the 10th of January (1938).

The challenge
Write a program or function which takes three inputs about a person (any other specified order is fine):

Their (calendar) year of birth (an integer)
Their sign of the zodiac (a string)
- may be whichever you choose from the following, so long as it is consistent:

all lower case except the first character;
all lower case; or
all upper case.

The (1-based) day of the zodiac period on which they were born (an integer)

...and provides two outputs (the other order is fine if specified):

The day of the month on which they were born (an integer)
Their month of birth (an integer)

More details
If your answer were a function, F, then for Donald Knuth we would run F(1938, 'Capricorn', 20) and receive the output (10, 1)
For the purposes of this challenge you do not need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years.
February has 29 days rather than 28 on leap years.
A year is usually a leap year if it is divisible by 4 - the exceptions are when it is divisible by 100 but not 400 (so, 1600 and 2000 were, whereas 1700, 1800, and 1900 were not).
For reference the names of the signs of the zodiac and their inclusive ranges are:
Aries       21 March     – 20 April
Taurus      21 April     – 21 May
Gemini      22 May       – 21 June
Cancer      22 June      – 22 July
Leo         23 July      – 22 August
Virgo       23 August    – 23 September
Libra       24 September – 23 October
Scorpio     24 October   – 22 November
Sagittarius 23 November  – 21 December
Capricorn   22 December  – 20 January
Aquarius    21 January   – 19 February
Pisces      20 February  – 20 March

This is code-golf, so the shortest code in bytes is the aim.
No loopholes, yada yada; you know the drill.

Test cases
Charles Babbage   F(1791, 'Capricorn',  5) -->  (26, 12)
George Boole      F(1815, 'Scorpio',   10) -->  ( 2, 11)
Herman Hollerith  F(1860, 'Pisces',    10) -->  (29,  2)
Vannevar Bush     F(1890, 'Pisces',    20) -->  (11,  3)
Howard H. Aiken   F(1900, 'Pisces',    17) -->  ( 8,  3)  - note 1900 was not a leap year
Donald Knuth      F(1938, 'Capricorn', 20) -->  (10,  1)
<Future Famed>    F(2000, 'Pisces',    17) -->  ( 7,  3)  - note 2000 was a leap year

Would it be OK to output the birth date as a string (such as "1791-12-26") rather than the birthday? Or the birthday as a string (such as "12-26")?

@Arnauld The output is strictly specified as two integers, so if you utilise any date utilities you'll have to pull them out. (I just saw the deleted comment, so just to clarify: the input is the calendar year of birth)

Javascript (ES6), 121 120 119 bytes
(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

Format for the sign of the zodiac is either:

all lower case except the first character
all lower case

Test cases

let f =
(y,s,d)=>[(d=new Date(y,m=s[2]=='s'?1:'r.sune0oapti'.search(s[4]||0),23+d-'343322110012'[m])).getDate(),d.getMonth()+1]

console.log(f(1791, 'Capricorn',  5)); // -->  (26, 12)
console.log(f(1815, 'Scorpio',   10)); // -->  ( 2, 11)
console.log(f(1860, 'Pisces',    10)); // -->  (29,  2)
console.log(f(1890, 'Pisces',    20)); // -->  (11,  3)
console.log(f(1900, 'Pisces',    17)); // -->  ( 8,  3)
console.log(f(1938, 'Capricorn', 20)); // -->  (10,  1)
console.log(f(2000, 'Pisces',    17)); // -->  ( 7,  3)

TSQL, 147 bytes
Golfed:
DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,@=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@)

Ungolfed:
DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT
  @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,
  @=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d
SELECT day(@),month(@)

Fiddle

Python 3 - 333 309 299 240 238 bytes
from datetime import*
def f(y,s,d):y=datetime(y,1,1)+timedelta((([[[21,80,111,142,173,235,267,297,327,356]['rsuneoapti'.index(s[4])],51][s[2]=='s'],204][len(s)<4])+d)%(365+[[[0,1][y%4==0],0][y%100==0],1][y%400==0])-2);return y.day,y.month

Saved 24 26 bytes thanks to @Jonathan Allan

You can shave off 20 bytes by moving the contents of the lambda into the only place you call it and replacing it's n with y and  shortening mod.

You could also save another 4 by moving S into place and then another 3 by putting the first three lines of the function on one line using ; to separate.

Running on Python 3.3 gives me a syntax error for len(s)<4else with no space after the 4, but you could still save by switching the statements around and using if s[3:]; i.e. [[21,...=='s']if s[3:]else 204. Edit: in fact you could do s[3:]and[[21,...=='s']or 204


text:
A Fragile Quine
A Fragile Quine
A fragile quine is a quine that satisfies the property of having each substring made by removing a single character, when evaluated, produces an error.
For example. If your program asdf is a quine, then for it to be fragile, the following programs must error:
sdf
adf
asf
asd

Your program (and all of its substrings) must be fully deterministic, and must be in the same language. A program falling into an infinite loop (that is, failing to terminate), even if not eventually producing an error is considered to "produce an error" for the purposes of this challenge.
Standard loopholes apply, including the usual quine restrictions (e.g. not able to read own source code).
For example, print("foo") is not fragile. All these substrings must error:
rint("foo")
pint("foo")
prnt("foo")
prit("foo")
prin("foo")
print"foo")
print(foo")
print("oo")
print("fo")
print("fo")
print("foo)
print("foo"

The ones that don't error are:
print("oo")
print("fo")
print("fo")

So it is not fragile.
An important note on quines
By consensus, any possible quine must satisfy this:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
Furthermore, a quine must not access its own source, directly or indirectly.

Example
Since I consider JavaScript's function#toString to be "reading it's own source code", I am disallowing it. However, if I weren't to bar it, here is a fragile quine in JavaScript:
f=(n=b=`f=${f}`)=>(a=(n)==`f=${f}`,n=0,a)&(n!=b)?b:q

Tester
Here is a program that, given the source code of your program, generates all programs that must error.

let f = (s) =>
  [...Array(s.length).keys()].map(i =>
    s.slice(0, i) + s.slice(i + 1)).join("\n");

let update = () => {
  output.innerHTML = "";
  output.appendChild(document.createTextNode(f(input.value)));
};

input.addEventListener("change", update);

update();
#output {
  white-space: pre;
}

#input, #output {
  font-family: Consolas, monospace;
}
<input id="input" value="print('foo')">

Am I allowed HQ9+?

@OliverNi No

Is infinite output considered a valid error?

Also, is it valid to print the correct output and then crash?

This is making assumptions about language features - not all languages have "errors".

+1 for disallowing Function.prototype.toString.

@Mego Most languages have errors. I am not terribly worried about making this possible in all languages.

@Pietu1998 infinite output implies infinite looping, so yes; if it crashes, then that constitutes an error.

@Mego Infinite loops are also allowed instead of errors. Every Turing-complete language has infinite loops.

@feersum Not true. Lambda calculus has recursion, not loops. It's not clear whether or not infinite recursion would count as an infinite loop.

@Mego how about running infinitely -.-

@ConorO'Brien I have a million dollars for you if you can prove that an arbitrary program doesn't terminate.

@Mego that is irrelevant. Why even bother bringing up the general case if only a finite subset applies per problem?

Burlesque, 32 28 25 bytes
{3SHWD{Je!}.+{Sh}\msh}Je!

Try it here.
So most instructions in Burlesque are 2 characters. And it is much easier to write a quine in Burlesque than in Marbelous. Je! or ^^e! means _~ in CJam.

Wait...if this is not golfed (and is by far the shortest here), then I can't imagine what golfed is! +1

@Dopapp The problem is Burlesque has too many instructions, so it is very likely I missed something.

Python 3, 45 bytes
c='print(end="c=%r;exec(c"%c+c[8*4])';exec(c)

Switching to Python 3 so that the trailing newline can be easily removed.
I started out with a stupid structure that had 2 variables instead of 1, but switching to 1 variable only made it 4 bytes shorter.
-(4 + 3) bytes by Dennis.

didn't know about assert. Good work

Would be great if you add an explanation.

Combining your exec structure with my % trick, there's c='print(end=len(c)%5*"c=%r;exec(c)"%c)';exec(c) for 48 bytes.

c='print(end="c=%r;exec(c"%c+c[8*4])';exec(c) saves 3 more bytes.

Python, 91/92 67 bytes
This was fun!
Now I know about assert:
s='s=%r;assert len(s)==34;print(s%%s)';assert len(s)==34;print(s%s)

If a char from string is removed, assert error. I would have done this sooner had I known of this feature, assert.

I forgot about the trailing newline question... if you do count it, then our answers are invalid since it can be safely removed.

Python 2, 51 50 46 bytes
lambda s='lambda s=%r:s[22:]%%s%%s':s[22:]%s%s

Verify it on Ideone.

Function quines are indeed allowed.

Huh? I've never heard of functions being allowed as quines...are there any examples for this?

@feersum The query javascript quine yields a few results.

@feersum the standard Mathematica quine is also function based (using #0).

I just had another look and most JS or Mathematica quines actually also call the function. So it would be more correct to call them REPL quines. That said, the example provided by Conor in the spec of this challenge is just a function, so I guess at least it's valid here.

Let us continue this discussion in chat.

JavaScript, 90 bytes
a="a=%s;a[44]!=')'?x:console.log(a,uneval(''+a))";a[44]!=')'?x:console.log(a,uneval(''+a))

Works in the console of Firefox 48, and should work in any other environment with uneval and console.log. Breakdown of errors:
a="                                             "; [  ]!=' '?x:           (a       (''+a))   // SyntaxError
   a=%s;a[44]!=')'?x:console.log(a,uneval(''+a))  a 44    )                                  // ReferenceError from calling `x`
                                                               console.     ,uneval          // ReferenceError from calling `onsole.log`, `auneval`, etc.
                                                                       log                   // TypeError from calling `console.og`, etc.

Wow, didn't know about uneval. Also, nice to see you at least somewhat back! :D

@ConorO'Brien Nice to be (at least somewhat) back! I've posted a couple more quine-y answers using this technique.

C#, 145 bytes
_=>{var@s="_=>{{var@s={1}{0}{1};for(;79!=s.Length;){{}}System.Console.Write(s,s,'{1}');}};";for(;79!=s.Length;){}System.Console.Write(s,s,'"');};

I've not written a quine in C# before, but higher scores are better in golf, right? :)
Infinite loop if a char is removed from the string or a digit from the magic const 79. Removing any other char results in a compile error.
Ungolfed:
/* Action<object> Quine = */ _ => // unused parameter
{
    // String of the function (well, mostly).
    // {0} placeholder for s, so the output contains the function and string.
    // {1} placeholder for " since it requires escaping.
    var@s = "_=>{{var@s={1}{0}{1};for(;79!=s.Length;){{}}System.Console.Write(s,s,'{1}');}};";

    // Infinite loop if a char is removed from the above string or if the 7 or 9 is removed.
    for(;79!=s.Length;){}

    // Print the quine.
    System.Console.Write(s,s,'"');
};

Python 2, 59 bytes
x='x=%r;1/(len(x)==30);print x%%x';1/(len(x)==30);print x%x

This throws a ZeroDivisionError if a 0, a 3, or a character is removed from the string. Removing a different character results in a NameError or a SyntaxError.

A Pear Tree, 50 bytes
a="print('a='.repr(a).';eval(a)');#f+QF>";eval(a)

Try it online!
Not the shortest answer, but a fairly comprehensive one; any character deletion from this program causes it to fail to checksum, thus the A Pear Tree interpreter won't even attempt to run it. (For example, you get an error if you delete the trailing newline.) The ;#f+QF> is used to ensure that the program as a whole has a CRC-32 of 0 (and f+QF> is one of three possible 5-byte strings that could be placed in the comment to achieve that while staying in ASCII; using ASCII is important here because repr would fail to round-trip it correctly otherwise).