text:
Molding ASCII art
You are given a single printable ASCII string containing no newlines, and a multiline "mold", containing spaces (), and hashes (#).
You must go character by character in the string, and replace hashes using the characters from the string in left-right, top-bottom order. If the string is too short to fill the mold, you stop outputting, if the string is too long you truncate the string to exactly fill the mold.

Example string/mold (string too long, truncated):
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipitmagnanoneratgravidacondimentum.Vestibulumnecnisllorem.Fuscemolestieviverranibh,eueleifendnislplaceratnon.Namblanditturpislacus,vitaemolestielacusimperdietquis.Nullapulvinar,exquissollicitudinfacilisis,eratnullavolutpatlectus,etluctusenimvelitegetex.Inhachabitasseplateadictumst.Donecinterdumnullalacinia,sodalesloremin,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,quisaliquetquam.Aeneanaugueipsum,imperdietsedaliquetnon,volutpategetsapien.Nullampharetranullaquispretiumornare.Aliquamfermentumvestibulummassavitaevehicula.
###########################################################
##### ##############   ###### ###### ######################
#####  ##   ######   #  ##### ###### ########        ######
###### #  #  ####  #### ##### ###### #######  ######  #####
######   ###  ###       ##### ###### ####### #######  #####
######  ##### ### ########### ###### #######   ###   ######
###### ###### ###  ########## ######      #####   #########
##################       ####    ##########################
###########################################################

Example output:
Loremipsumdolorsitamet,consecteturadipiscingelit.Namsuscipi
tmagn anoneratgravid   acondi mentum .Vestibulumnecnisllore
m.Fus  ce   molest   i  evive rranib h,euelei        fendni
slplac e  r  atno  n.Na mblan dittur pislacu  s,vita  emole
stiela   cus  imp       erdie tquis. Nullapu lvinar,  exqui
ssolli  citud inf acilisis,er atnull avolutp   atl   ectus,
etluct usenim vel  itegetex.I nhacha      bitas   seplatead
ictumst.Donecinter       dumn    ullalacinia,sodalesloremin
,eleifendturpis.Pellentesqueanisimi.Aeneannonlobortisdiam,q

Example string/mold (string too short, output stopped):
This probably won't look good.
### ### ### ###
# # # # #   #
### ### #   # #
#   #   #   # #
#   #   ### ###

Corresponding output:
Thi s p rob abl
y   w o n   '
t l ook     g o
o   d   .

Shortest code in bytes wins.
Credit for the idea to this website.

Can the input line contain hashes? (If so, that could use a test case.)

Can the input line contain spaces?

Can the input have leading/trailing spaces/newlines?

@manatwork In the second test case, it does.

@MartinBüttner Yes, the input case can contain hashes.

@Sp3000 The input can have (leading/trailing) spaces, but not newlines.

Can the output have trailing whitespace if the string is too short?

@Pietu1998 No, the specification is exact. Only the standard single trailing newline is allowed.

CJam, 16 14 bytes
Thanks to Sp3000 for saving 2 bytes.
lq{s'#-\+(\}/;

Terminates with an error if the string is too short, but the error is printed to STDERR.
Try it online!
Alternatively (same byte count):
lq{SN+&\+(\}/;

Explanation
l       e# Read the input line.
q       e# Read the grid.
{       e# For each character in the grid...
  s     e#   Convert to string.
  '#-   e#   Remove "#" from it.
  \+    e#   Prepend it to the input line (this is a no-op for "#"s in the grid).
  (     e#   Pull off the first character from the input line. This will terminate the
        e#   program with an error once the input line is empty.
  \     e#   Swap the character with the input line.
}/
;       e# Discard the remainder of the input line if there is any.

LabVIEW, 37 LabVIEW Primitives
splits the string into text and mold then transforms them into an array. Checks the mold if theres a # and puts a char from text else it does nothing. If either the text or the mold are empty exit the loop

The fact that you did this with LabView blows

AND its fun to look at!

Haskell, 48 bytes
called like "(replace with string)#(hashmark string)":
[]#_=[]
(r:t)#('#':s)=r:t#s
r#(c:s)=c:r#s
_#_=[]

Less golfed:
combine replacements slots | null replacements = []
                           | null slots        = []
                           | head slots == '#' = head replacements : combine (tail replacements) (tail slots)
                           | otherwise         = head slots        : combine       replacements  (tail slots)

Cool, but isn't this invalid unless you add I/O? E.g import Control.Applicative;main=liftA2(#)getLine getContents>>=putStrLn

@Cubic The problem statement does not require IO (or even a full program) and other solutions, including one in Python 3, do not include IO.

Retina, 42 40 bytes
Byte count assumes ISO 8859-1 encoding.
T`#`×`¶.+
+`^(.)([^×]+)×
$2$1
^.*¶|×\D*

The trailing linefeed is significant.
Try it online!
Explanation
T`#`×`¶.+

We first replace # which are part of the grid with the non-ASCII (but extended ASCII) character × so we don't confuse them with any # that might appear on the first line.
+`^(.)([^×]+)×
$2$1

Now we fill as many × as possible from the first line by repeatedly replacing the first × we can find with the first character on the first line (which is removed in the process).
^.*¶|×\D*

Finally, we get rid of anything that's left on the first line as well as anything from the first × to truncate the input in both directions.

JavaScript (ES6), 57 56 55 bytes
(s,m)=>m.replace(x=/[^]/g,c=>c-1?x&&c:x=s[i++]||"",i=0)

Saved 1 byte thanks to @Neil!
Explanation
Works with hashes in the input string and retains trailing white-space after the input string has finished.

var solution =

(s,m)=>
  m.replace(x=/[^]/g,c=> // for each character c of the mold, initialise x to true
    c-1?                 // if c is a space or newline:
      x&&c               // if x is truthy, return c
                         // else if the string has ended, x will equal "" (false), return x
    :                    // else if c is a hash:
      x=                 // set x to the character of the input string
        s[i++]||"",      // return the input string character (or "" if finished)
    i=0                  // initialise i to 0
  )
<input type="text" id="input" value="This probably won't look good." />

<textarea id="mold" rows="6" cols="40">### ### ### ###
# # # # #   #
### ### #   # #
#   #   #   # #
#   #   ### ###</textarea>

<button onclick="result.textContent=solution(input.value,mold.value)">Go</button>

Nice algorithm, but m.replace(/./g,c=>...) is shorter.

@Neil You're right. I was trying too hard for it to be different to your answer haha!

Not any more, since you can use /[^]/ instead of /.|\n/. (Also apologies for wrongly suggesting /./.)

Python 3, 69 68 67 bytes
def f(s,m):s=iter(s);return''.join(n<'#'and n or next(s)for n in m)

Ideone
Thanks to FryAmTheEggman, Chiel ten Brinke for the byte off. Alternatively, I could have used Python 2 for an extra one (print without ()).

You can save one byte by replacing the print with return.

pb, 359 bytes
^w[B!0]{w[B=10]{t[T+1]b[0]}>}<w[T!0]{w[B!0]{<}>^b[T]vw[B!0]{t[B]b[0]^v[B]v<[X]w[B!0]{>}b[T]<[X]^[Y+2]w[B=0]{>}t[B]b[0]>b[T]v}^t[B-1]vw[B=0]{<}}>b[10]t[X]w[X!-2]{w[B!0]{v}<}w[X!T]{b[35]>}^[Y]^<[X]w[B!10]{t[B]b[0]w[T=35]{t[10]}v<[X]w[B!35]{w[B=0]{v<[X]}b[T]^[Y]^<[X]w[B=0]{>}}<[X+2]w[B=0]{v}w[B!0]{b[0]>}w[Y!-1]{<[X]^w[B!0]{w[B=35]{b[0]}w[B=10]{b[35]}>}}

In pb, input is strictly one dimensional. It doesn't understand that you're drawing a shape with your input, it just sees one long line with some bytes with a value of 10 thrown in there. The first thing this program does is copy all but the first "line" of input onto Y=0, Y=1, etc, to create the shape of the mold.
Something I've noticed a lot in code golf, but especially when golfing esoteric languages, is that you often don't want to have two branches to deal with; you just set yourself up that you do the same thing in either case. The naive way to solve this problem would probably check the length of the string against the number of hashes in the rest of the input and do something depending on the result, because it has to behave differently depending on what gets cut off. But that's a lot of bytes.
Instead, after completing the mold, an extra line is added to the bottom. It is simply n hashes in a row, where n is the length of the string. Now the string is guaranteed to fit! After inserting all the characters of the string, that extra line that was added is unconditionally destroyed. Any leftover hashes in the mold proper are erased as well, and that's the necessary output!
Of course, it would violate the spec to simply destroy all hashes. After all, there could be a hash in the input string! To handle this, I refer to another part of the spec:

You are given a single printable ASCII string containing no newlines

(Emphasis mine.) By the time we're dealing with the string, we don't really care if there are newlines in it, but we do know that there aren't any. So, all hashes are replaced with newlines before being put into the mold! After all hashes are destroyed, all newlines are replaced with hashes again. This doesn't turn the entire output into a single hash-delimited line because the nature of pb's 2D output means that it never actually put a newline at the end of each line, it just went on to the next line.
Ungolfed:
# Start by copying down the mold
^
# (B means "the character under the cursor")
w[B!0]{       # While B isn't a null byte:
    w[B=10]{    # While B IS a newline:
            t[T+1]    # Increase T by 1
                      # (`T` is the only variable that can be modified directly)
            b[0]      # Overwrite with 0 to break out of inner loop
    }
    >           # Move to the right
                # (dodge the 0 we wrote and progress towards the end of input)
}

# Brush is now at the end of the input, T contains number of lines

<             # Make sure the brush is actually /on/ the input
w[T!0]{       # While T isn't 0:
    w[B!0]{<}>  # Go to the first character of the last line
    ^b[T]       # Place a flag above current character
                # Also a convenient way to get the value of T back later
    vw[B!0]{    # While the character under the flag isn't 0:
            t[B]b[0]  # Put it in T, overwrite with 0
            ^v[B]v    # Go down by the amount written in the space above
            <[X]      # Go left by the amount right the brush is (i.e. go to X=0)
            w[B!0]{>} # Find first empty space
            b[T]      # Write the value of T
            <[X]      # Go left by the amount right the brush is
            ^[Y+2]    # Go up by the amount down the brush is plus 2 (above input)
            w[B=0]{>} # Find flag
            t[B]b[0]  # Pick it up, overwrite with 0
            >b[T]     # Place it to the right
    v}
    ^t[B-1]v    # Collect flag - 1
    w[B=0]{<}   # Go to end of previous line
}

# Mold is placed, all that's left is placing the string
>b[10]        # Put a newline at the end, guaranteed to not be in the string
t[X]          # Save current X value in T

# Add more hashes, guaranteed to fit the input and findable later
w[X!-2]{       # While X!=-2:
    w[B!0]{v}    # Move down until hitting a null byte
    <            # Move left
}
w[X!T]{        # While not at the X value we saved earlier:
    b[35]>       # Travel right, leaving hashes
}

^[Y]^<[X]     # Go to (0, -1)

w[B!10]{      # Until hitting the newline at the end:
    t[B]b[0]    # Pick up character, overwrite with 0
    w[T=35]{    # If it's a hash...
            t[10]     # Make it a newline so we remember, deal with it later
    }
    v<[X]       # Go to (0, 0)
    w[B!35]{    # While B is not a hash:
            w[B=0]{   # While B IS null:
                    v       # Go down
                    <[X]<   # Go to X=-1
                    b[1]    # Print a 1 to break loop (it won't be rendered anyway)
            }
            >           # Go right, either ignore a non hash or go to X=0
    }
    b[T]        # Overwrite hash with picked up character
    ^[Y]^<[X]   # Go to (0, -1)
    w[B=0]{>}   # Go to first character of it to restart loop
}

<[X+2]        # Go to (-2, -1)
w[B=0]{v}     # Go down until finding the row of added hashes
w[B!0]{b[0]>} # Wipe it out unconditionally
w[Y!-1]{      # For every remaining line on the screen:
    <[X]^       # Go to the beginning
    w[B!0]{     # For each character in it:
            w[B=35]{  # If it's a hash:
                    b[0]    # Destroy it
            }
            w[B=10]{  # If it's a newline:
                    b[35]   # Write a hash (after the check to destroy hashes!)
            }
    >}
}

Nice, that looks like a lot of work.

ES6, 59 bytes
(t,m)=>m.replace(/#/g,h=>t[i++]||h,i=0).replace(/#[^]*/,'')

70 bytes if the text can contain hashes:
(t,m)=>m.replace(/#/g,(_,n)=>t[i]&&(j=++n)&&t[i++],i=0,j=0).slice(0,j)

Do not remove trailing whitespace, exactly replicate the mold, with exactly the input string replacing the hash characters.

@orlp Thanks I'll edit that version back out again.

Perl, 53 51 42 + 2 = 44 bytes
@a=/./g;$/="";$_=<>;s/#/shift@a/ge;s/\s+$//

Requires -p to run. Explanation:
@a=/./g; # Split first line into an array of characters
$/=""; # Enable slurp mode (read the rest of lines in one go)
$_=<>;
s/#/shift@a/ge;
s/\s+$//
# With '-p' auto print is enabled

I get some ugly “1”s at the beginning of the output lines. Try this for a clean output: $a=<>;$/="";say<>=~s/#/substr$a,$i++,1/ger

@manatwork I realized that as well, clever with the use of $/ instead of join

Jelly, 10 8 bytes
¹ƈ<”#$?€

Try it here!

This seems to print too much trailing whitespace when the input line is shorter than the number of # in the input.

Perl 6, 72 bytes
my@a=get.comb;say(S:g/\#/{@a.shift//''}/~~{S/\s+$//}),@a||last for lines

ES6, 47 bytes
Probably the most straightforward solution.
(S,R)=>(i=-1,S.replace(/#/g,_=>R[++i]||R[i=0]))

This code creates an anonymous function that receives 2 parameters and returns the final result.
The first parameter S is the "map" string with your "#", while the second parameter R is the "replacement" for those "#".

Ruby, 52 bytes
->a,b{i=-1
a.gsub(/(#)|./){b[i+1]?$1?b[i+=1]:$&:""}}

Attempt This Online!

@KevinCruijssen Thanks for the heads-up. I've updated my answer.

Looking good now, +1 from me.

Julia 1.0, 98 88 77 bytes
!S=((a,b)=split(S,'
';limit=2);j=0;[b...].|>m->(print(m=='#' ? a[j+=1] : m)))

Try it online!
-22 MarcMush

I think you can save ~10 bytes by using (a,b)=split(S,'\n';limit=2)

-11 bytes by starting j at zero and using a[j+=1] (maybe even more)

K (ngn/k), 39 bytes
{(w@l)#@[y;l#w;:;(l:(#x)&#w:&"#"=y)#x]}

Try it online!
Explanation:
{(w@l)#                                 / up to the final index
       @[y;                             / replace the mold
           l#w;:;                       / at the first l indices of hash characters
                 (l:(#x)&#w:&"#"=y)     / where l is the min of
                                          number of such indices and length of string
                                   #x]} / with the first l characters of string

Uses the fact that one past the last index of a list is null and taking the first null characters defaults to the full list.

Python 3
152 127 bytes
A full program.
from sys import stdin as S
s=list(S.readline())
print(''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()]))

106 bytes
A function that takes the stream as input.
def f(S):s=list(S.readline());return''.join([''if not s else(s.pop(0)if m=='#'else m)for m in S.read()])

We already have a Python answer which is much shorter and uses the same method to construct the output.

I see. I wrote it yesterday though, when that answer wasn't there yet. Sorry for posting so late

You're not posting late, lots of people probably haven't seen this question yet (I certainly didn't until I saw this post)

05AB1E, 12 bytes
`'ÿ«)'#s.;'ÿ¡н

Also complies to the two rules in the comments, unlike some of the other answers:

The input-sentence can contain hashes and (potentially trailing) spaces.
The output does not contain trailing spaces (unless the input contained trailing spaces), only a single trailing newline.

Try it online.
Explanation:
I take advantage of the fact that the input only contains printable ASCII.
`               # Push the characters of the first (implicit) input-sentence separately
                # to the stack
 'ÿ«           '# Append an "ÿ" to the last character
    )           # Wrap the entire stack into a list
     '#        '# Push string "#"
       s        # Swap so the list is at the top again
        .;      # Replace every first "#" in the second (implicit) multi-line string
                # with the items in the list one by one
          'ÿ¡  '# Split the resulting string on "ÿ"
             н  # Only keep the first part
                # (after which the result is output implicitly with trailing newline)

Unfortunately the legacy version of 05AB1E doesn't vectorize with builtin .;, otherwise the second 'ÿ could have been replaced with Z (maximum character - based on codepoint - without popping). In the new 05AB1E version, the min/max builtins doesn't work on characters. But because it doesn't vectorize, it's 15 bytes instead: `'ÿ«)v'#y.;}Z¡н - try it online.

Does this mean the string can’t contain "ÿ"?

@doug Yes, that's indeed correct. As I mentioned in my answer: the question asks to support printable ASCII, so I take advantage of that with my approach of splitting by a unicode character.

Python, 64 bytes
f=lambda s,m:m and(z:=m[0]*(m[0]!='#')+s)and z[0]+f(z[1:],m[1:])

Attempt This Online!


text:
"Fouriest" Transform of An Integer
Challenge
Inspired by this SMBC comic, discussed on reddit, math.stackexchange, and calculus7, the challenge is to return the lowest base such that a number is "fouriest."
Description

[From the comic]
"It's called a Fourier Transform when you take a number and convert it to the base system where it has more fours, thus making it 'fourier.' If you pick the base with the most fours, the number is said to be 'fouriest.'"

The challenge is: given an integer greater than four, return the lowest base in which it is "fouriest."
Rules

The solution may be either a function or a full program, whose input and output are of integral type (Int, Long, etc.)
If your language has a function to convert base systems or solve this challenge for a number other than four, it is disallowed
I will not accept my own solution
Solution with the lowest number of bytes wins!

Test Cases
f(17)      = 13
f(72)      = 17
f(176)     = 43
f(708)     = 176
f(500)     = 124
f(2004)    = 500
f(1004)    = 250
f(4020)    = 1004
f(1004)    = 250
f(4020)    = 1004
f(4076)    = 1018
f(16308)   = 4076
f(8156)    = 2038
f(32628)   = 8156
f(3444443) = 10
f(9440449) = 5

Aside: Except for the final two test cases (which are palindromic primes), each one is a record in this sequence such that its position is an additional record.
You may also note that (the position)/(the record) is around four, and I conjecture that this ratio converges to four.
Test Implementations:
Mathematica:
Maxnum4s[x_] := Block[{thisbest = 0, best = 0, bestpos = 4},
  Do[thisbest = num4s[x, pos];
   If[thisbest > best, best = thisbest; bestpos = pos, 0], {pos, 5, x - 1}]; {bestpos, best}]

Python3:
def foursCount(x0,b):
    count = 0
    x     = x0
    while x > 0:
        if x % b == 4:
            count += 1
        x = x // b
    return count

def fouriest(x):
    bestpos = 4
    best    = 0
    this    = 0
    for pos in range(4,x):
        this = foursCount(x,pos)
        if this > best:
            best    = this
            bestpos = pos
    return bestpos

C:
int foursCount(int x0, int b){
    int count = 0;
    int     x = x0;
    while (x > 0) {
        if (x % b == 4) {
            count++;
        }
        x = x / b;
    }return count;
}
int fouriest(int x){
    int pos     = 5;
    int this    = 0;
    int best    = 0;
    int bestpos = 0;
    while (pos < x) {
        this = foursCount(x, pos);
        if (this > best) {
            bestpos = pos;
            best    = this;
        }
        pos++;
    }
    return bestpos;
}

If you're curious, just for fun:
Mathematica:            77.042 s
Python:                  8.596 s
Haskell (Interpreted): 579.270 s
Haskell (compiled):      4.223 s
C:                       0.129 s

Well, I guess I should search better next time. Good practice anyway.

Haskell, 82 bytes
The function 'f' gives the final result:
_#0=0
b#x=sum[1|4==mod x b]+b#div x b
f x=[b|b<-[5..x],and[b#x>=c#x|c<-[b..x]]]!!0

Less golfed:
countFours 0    _ = 0
countFours base x | x == 0          = 0
                  | mod x base == 4 = 1 + countFours (div x base) base

f x = head [base | base <- [5..x], and smallerBasesNotFouriest]
  where
    smallerBasesNotFouriest = [(countFours base x) >= (countFours base' x) | base' <- [5..base]]

source: Stack Exchange

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

sort: votes


text:
Program touch-tone instructions for my fingers
The keypad on my office phone has the following layout:
[1]  [2]  [3]
/.@  ABC  DEF

[4]  [5]  [6]
GHI  JKL  MNO

[7]  [8]  [9]
PQRS TUV WXYZ

[*]  [0]  [#]
 +    _

Task:
Write a program that, given an input string, returns a list of instructions that my fingers need to follow in order the type/dial the message/number.
Rules:

3 fingers (1,2 & 3) start on keys [4], [5] and [6]. This starting position is 0.
The only instruction a finger receives is its new relative location.
Once a key has been pressed, that is the finger's new starting position. Fingers do not return to their 'home row'.
Moving a finger up the keypad's column is -1, -2 or -3, depending on where it was last used.
Moving a finger down the keypad's column is 1, 2 or 3, depending on where it was last used.
Keeping a finger on the same key means there is no movement (0). It is not included.
Words which require a double letter (like 'OO' in 'BOOK' or 'DE' in CODE) will need a pause (P) between letters.
When using Pause, the finger is not specified.
A finger can only press the keys in its own column (1,4,7,*) (2,5,8,0) (3,6,9,#)
Typing certain letters requires multiple keypresses. To type 'F', 3 needs to be pressed 3 times.
Input is not case sensitive.
Input characters not available on the keypad should be ignored. (Hyphens and parenthesis of a phone number, for example)
Input will either be alpha or numeric - not a mixture - so no need to switch between input methods mid-stream.
When entering numbers, Pauses aren't necessary.
This is code-golf so shortest code in bytes wins.

Update
To slightly simplify matters, [*] and [#] can be ignored. These will not feature in the input. But I'll buy you a beer if you do include them and get lowest byte count! (If you're in London ;-))
Output:
A list of instructions, in the following format:
[direction] [finger_number] [new_relative_location], ...

Whitespace between instructions is optional.
Test cases:
(123)-957 -> -11, -21, -31, 32, 21, 12
555-9273 -> 2,2,2,31,-21,11,-32
CODE GOLF -> -21,2,2, 3,3,3, -31, P, 3,3, 23, 1, 31,3,3, -22,2,2, -31,3,3
Code Golf -> -21,2,2, 3,3,3, -31, P, 3,3, 23, 1, 31,3,3, -22,2,2, -31,3,3

related (but not the same).

@JohnE Ah, good catch - That didn't come up in the list of possible dupes as I was entering the question. I hope this is suitably different.

Python 2, 423 bytes (no */# support)
k='/.@~ABC~DEF~GHI~JKL~MNO~PQRSTUV~WXYZ+~~~ '
d='123456789~0'
g={c:(i/12,i%12/4,i%4)for i,c in enumerate(k)}
g.update(((c,(i/3,i%3,0))for i,c in enumerate(d)))
del g['~']
def f(s):
 s,a=[c for c in s[::-1].upper() if c in g],[]
 q=[1,1,1]
 while s:
  y,x,r=g[s.pop()]
  n,m,_=(9,9,9)if not s else g[s[-1]]
  v=y-q[x]
  q[x]=y
  a+=[(v<0)*'-'+`x+1`+(v!=0)*`abs(v)`]+r*[`x+1`]+(c in k and(y,x)==(n,m))*['P']
 print','.join(a)

Java, 701
static void main(String a[]){int q[]={1,1,1},w[]={0,0,0},f=9,n=0,p=1,x,y,r,l=0,d;String c,i=String.join(" ",a),o="";i=i.replaceAll("[^A-Za-z0-9/.@*#+ ]+", "").toUpperCase();String[]v="1/.@|4GHI|7PQRS&2ABC|5JKL|8TUV|0 &3DEF|6MNO|9WXYZ".split("&");for(;l<i.length();){c=""+i.charAt(l++);for(x=0;x<3;x++)if(v[x].contains(c)){n=x;String[]b=v[x].split("\\|");for(y=0;y<b.length;y++)if(b[y].contains(c)) {w[x]=y;p=b[y].indexOf(c);}}if(f==n&&q[f]==w[f]){if(i.matches("[^0-9]+"))o+="P,";for(r=0;r<p;r++)o+=(f+1)+",";}else{d=w[n]-q[n];if(d!=0)o+=d;for(r=0;r<p;r++){o=new StringBuilder(o).insert(d==0?o.length():o.length()-1,n+1).toString();d=0;o+=",";}}q[n]=w[n];f=n;}System.out.print(o.replaceAll(",$",""));}}

Completely unoptimised and ungolfed
A starting point
public class Keypad {

public static void main(String a[]){

    int fingerRow[] = {1,1,1}, nextFingerRow[]=new int[3], finger=-1, nextFinger=0, repeat=1;
    String input = String.join(" ",a), out="";
    input=input.replaceAll("[^A-Za-z0-9/.@*#+ ]+", "").toUpperCase(); //strip nonsense
    System.out.println(input);
    boolean numbersOnly = input.charAt(0)>47 && input.charAt(0)<58;

    String[] columns = "1/.@|4GHI|7PQRS&2ABC|5JKL|8TUV|0 &3DEF|6MNO|9WXYZ".split("&");

    for (int l=0;l<input.length();l++) {
        // current letter
        String letter = ""+input.charAt(l);

        // find finger
        for (int i=0; i<3; i++) {
            if (columns[i].contains(letter)) {
                nextFinger = i;
                // find row
                String[] buttons = columns[i].split("\\|");
                for (int j=0; j<buttons.length; j++) {
                    if (buttons[j].contains(letter)) {
                        nextFingerRow[i]=j;
                        repeat=buttons[j].indexOf(letter);
                    }
                }
            }
        }

        // both same && letter? Add Pause.
        if (finger==nextFinger && fingerRow[finger]==nextFingerRow[finger]){
            if (!numbersOnly) out += "P,";
            for (int r=0; r<repeat;r++) {
                out += (finger+1)+",";
            }
        }
        else {
            // work out previous to current
            int distance = nextFingerRow[nextFinger] - fingerRow[nextFinger];
            if(distance!=0) out+=distance;
            // add finger
            for (int r=0; r<repeat;r++) {
                out = new StringBuilder(out).insert(distance==0?out.length():out.length()-1, nextFinger+1).toString();
                distance=0;
                out+=",";
            }
        }
        fingerRow[nextFinger] = nextFingerRow[nextFinger];
        finger = nextFinger;
    }
    System.out.println(out.replaceAll(",$",""));
}
}

Sample run
CODE GOLF
-21,2,2,3,3,3,-31,P,3,3,23,1,31,3,3,-22,2,2,-31,3,3

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


text:
The Lucas-nacci Numbers
Background
Most everyone is familiar with the Fibonacci numbers \$F(n)\$:

\$0, 1, 1, 2, 3, 5, 8, 13, 21, ...\$

These are formed by the recursion function \$F(n) = F(n-1) + F(n-2)\$ with \$F(0)=0\$ and \$F(1)=1\$. A000045
A closely related sequence is the Lucas numbers \$L(m)\$:

\$2, 1, 3, 4, 7, 11, 18, 29, ...\$

These are formed by the recursion function \$L(m) = L(m-1) + L(m-2)\$ with \$L(0)=2\$ and \$L(1)=1\$. A000032
We can alternate between the two sequences based on even/odd indices, with the construction
$$A(x) = \begin{cases}
F(x) & x \equiv 0 \pmod 2 \\
L(x) & x \equiv 1 \pmod 2 \\
\end{cases}$$
For example, \$A(4)\$ is equal to \$F(4)\$ since \$4 \bmod 2 \equiv 0\$. We'll call this sequence the Lucas-nacci Numbers, \$A(x)\$:

0, 1, 1, 4, 3, 11, 8, 29, 21, 76 ...

This can be formed by the recursion function \$A(x) = 3A(x-2) - A(x-4)\$ with \$A(0)=0, A(1)=1, A(2)=1\$, and \$A(3)=4\$. A005013
Challenge
Given input \$n\$, output the sequence of \$n+1\$ numbers up to and including \$A(n)\$ as described above. Fewest bytes (or byte-equivalents, such as for LabVIEW, as determined individually on Meta) wins.
Input
A single non-negative integer \$n\$.
Output
A list of numbers that correspond to the subsequence of Lucas-nacci numbers from \$A(0)\$ to \$A(n)\$. The list must be in sequential order as described above.
Rules

Standard code-golf rules and loophole restrictions apply.
Standard input/output rules apply.
Input number can be in any suitable format: unary or decimal, read from STDIN, function or command-line argument, etc. - your choice.
Output can be printed to STDOUT or returned as a result of the function call. If printed, suitable delimiters to differentiate the numbers must be included (space-separated, comma-separated, etc.).
Additionally, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.
If the input is a non-integer or a negative integer, the program can do anything or nothing, as behavior is undefined.

Examples
Input -> Output
0 -> 0
5 -> 0, 1, 1, 4, 3, 11
18 -> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76, 55, 199, 144, 521, 377, 1364, 987, 3571, 2584

Is newline considered an accepted delimiter?

@corsiKa Sure, that's fine.

Jelly, 12 bytes
;2U+¥Ð¡-,1ZḢ

Try it online!
Background
We can extend F and L to -1 by defining F(-1) = 1 and L(-1) = -1. This is consistent with the recursive function.
Our program starts with
-1  1
 0  2

In each step, to form the next pair, we reverse the last pair and add it to the penultimate pair. For example:
[0, 2] U+¥ [-1, 1] -> [2, 0] + [-1, 1] -> [1, 1]

If we continue this process for a few more steps, we get
-1  1
 0  2
 1  1
 1  3
 4  2
 3  7
11  5

The Lucas-nacci sequence is simply the left column.
How it works
;2U+¥Ð¡-,1ZḢ  Niladic link. No implicit input.
              Since the link doesn't start with a nilad, the argument 0 is used.

;2            Concatenate the argument with 2, yielding [0, 2].
       -,1    Yield [-1, 1]. This is [L(-1), F(-1)].
    ¥         Create a dyadic chain of the two atoms to the left:
  U             Reverse the left argument.
   +            Add the reversed left argument and the right one, element-wise.
     Ð¡       For reasons‡, read a number n from STDIN.
              Repeatedly call the dyadic link U+¥, updating the right argument with
              the value of the left one, and the left one with the return value.
              Collect all intermediate results.
          Z   Zip the list of results, grouping the first and seconds coordinates.
           Ḣ  Head; select the list of first coordinates.

‡ Ð¡ peeks at the two links to the left: 2 and U+¥. Since the leftmost one is a nilad, it cannot be the body of the loop. Therefore, U+¥ is used as body and a number is read from input. Since there are no command-line arguments, that number is read from STDIN.

I get the impression that you do this kind of stuff (golfing in Jelly) for a living.  Which makes me terrified.

If anyone sorts out how to golf (code) for a living, please ping me in chat. Asking for a friend...

So basically you're just calculating both sequences, but reversing at each step, which effectively switches between the sequences.

@Neil Yes, exactly. It avoids interleaving the sequences afterwards, which is slightly longer.

Haskell, 59, 57, 56, 52, 51 bytes
l a=2*mod a 2:scanl(+)1(l a)
f n=[l i!!i|i<-[0..n]]

Series definition adapted from this answer.
Less golfed:

fibLike start = start : scanl (+) 1 (fibLike start)
whichStart i = (2*mod i 2)
lucasNacci i = fibLike (whichStart i) !! i
firstN n = [ lucasNacci i | i <- [0..n]]

fibLike start gives an infinite list, defined: f(0)=start, f(1)=1, f(n)=f(n-1) + f(n-2).
whichStart i returns 2 for odd input (Lucas series) or 0 for even (Fibonacci series).
lucasNacci i gives the ith Lucas-nacci number.
firstN n maps over the list.
One byte saved by Boomerang.

I think you can get one more byte by moving 2*mod i 2 into l then you can remove the parenthesis. Like this: l a=2*mod a 2:scanl(+)1(l a) and
f n=[l i!!i|i<-[0..n]]

@Boomerang Yup, that works. Thank you

CJam, 21 20 bytes
Thanks to Sp3000 for saving 1 byte.
TXX4ri{1$3*4$-}*?;]p

Test it here.
Explanation
Simply uses the recurrence given in the challenge spec.
TXX4 e# Push 0 1 1 4 as base cases.
ri   e# Read input and convert to integer N.
{    e# Run this N times...
  1$ e#   Copy a(n-2).
  3* e#   Multiply by 3.
  4$ e#   Copy a(n-4).
  -  e#   Subtract.
}*
?;   e# Discard the last three values, using a ternary operation and popping the result.
]p   e# Wrap the rest in an array and pretty-print it.

Who (or what) is Sp3000 that you thank on every answer?

@CJDennis http://codegolf.stackexchange.com/users/21487/sp3000

@CJDennis Some say he is the greatest Python golfer to ever live. Some say he lives in a secluded cabin on top of a mountain, built out of a minimal number of logs. Some say he is the voice in the back of our heads, which nags us when we post solutions which can be golfed further. But most of us just say he's the user whose profile Martin linked.

Perl 6, 42 bytes
{(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}

usage
> my &f = {(0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[0..$_]}
-> ;; $_? is raw { #`(Block|184122176) ... }
> f(0)
(0)
> f(5)
(0 1 1 4 3 11)
> f(18)
(0 1 1 4 3 11 8 29 21 76 55 199 144 521 377 1364 987 3571 2584)

The clearest lambda that I have come up with is {( (0,1,*+*...*) Z (2,1,*+*...*) ).flat.rotor( 1=>2, 1=>0 )[ 0..$_ ].flat}

Given that the exact wording is "given n", you could save a byte with: (0,1,1,4,{$^b;$^d;3*$^c-$^a}...*)[^(n+1)].

ES6, 65 bytes
n=>[...Array(n)].map(_=>a.shift(a.push(a[2]*3-a[0])),a=[0,1,1,4])

Uses the recurrence relation given in the question.

Oracle SQL 11.2, 218 216 201 bytes
WITH v(a,b,c,d,i)AS(SELECT 0,1,1,4,3 FROM DUAL UNION ALL SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1)SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4UNION ALL SELECT d FROM v WHERE:1>2;

Un-golfed
WITH v(a,b,c,d,i) AS
(
  SELECT 0,1,1,4,3 FROM DUAL
  UNION ALL
  SELECT b,c,d,3*c-a,i+1 FROM v WHERE i<:1
)
SELECT SIGN(LEVEL-1) FROM DUAL WHERE LEVEL-1<=:1 CONNECT BY LEVEL<4
UNION ALL SELECT d FROM v WHERE:1>2;

I managed to gain a few bytes by using (abusing ?) the SIGN function to generate the first 3 elements of the sequence.

Retina, 70 62 59 bytes
1
¶$`1
m`^(11)*1$
$&ff
m`$
 f
+`1(f*) (f*)
$2 $2$1
 f*

f
1

Try it online

Input is in unary base, n 1s.
1? $`¶ - Create a line for each number from 0 to n:  , 1, 11, 111, 1111, ...
m`^(11)*1$ $&ff - Append ff to odd lines. This will seed the function with L(0)=2.
m`$  f - Append  f to all lines (note the space). This seeds the function with 0 and 1 for Fibonacci numbers, and 2 and 1 for Lucas numbers.
+`1(f*) (f*) $2 $2$1 - Loop: calculate F(n+1) = F(n) + F(n-1) while there are still 1s.
 f*      - Remove F(n+1) from the end of each line.
Replace fs back to 1s. If this isn't needed and we can stay with fs, the length is just 55 bytes.

Japt, 25 22 21 bytes
Uò £MgXf2)+X%2*Mg°X)r

Test it online!
Background
It's somewhat difficult to create a Fibonacci sequence in Japt, but we have a built-in Mg to do it for us. However, this only gives us the Fibonacci sequence, not the Lucas sequence. We can accomplish the Lucas sequence fairly easily using this trick:
N    F(N-1)  F(N+1)  F(N-1)+F(N+1)
0    1       1       2
1    0       1       1
2    1       2       3
3    1       3       4
4    2       5       7
5    3       8       11
6    5       13      18
7    8       21      29

As you can see, F(N-1) + F(N+1) is equal to L(N) for all N. However, since we only need Lucas numbers on the odd indices, we can combine the two formulas into one:
N    N-N%2  N+N%2    F(N-N%2)  F(N+N%2)*(N%2)  F(N-N%2)+F(N+N%2)*(N%2)
0    0      0        0         0               0
1    0      2        0         1               1
2    2      2        1         0               1
3    2      4        1         3               4
4    4      4        3         0               3
5    4      6        3         8               11
6    6      6        8         0               8
7    6      8        8         21              29

How it works
Uò £  MgX-1 +X%2*Mg° X)r
Uò mX{MgX-1 +X%2*Mg++X)r

             // Implicit: U = input integer
Uò mX{       // Create the inclusive range [0..U], and map each item X to:
MgXf2)+      //  Floor X to a multiple of 2, calculate this Fibonacci number, and add:
+X%2*Mg++X)  //  Calculate the (X+1)th Fibonacci number and multiply by X%2.
)r           //  Round the result. (The built-in Fibonacci function returns
             //  a decimal number on higher inputs.)

Mathematica, 52 51 bytes
If[#>2,3#0[#-2]-#0[#-4],#-If[#>1,1,0]]&/@0~Range~#&

Very similar idea to Martin's above, I spent some time trying to find a shorter way of defining the "base cases" for the function. Polynomial interpolation was a bust, so I went for this, using the extension into negatives to yield a fairly short definition.

Brachylog, 51 bytes
:0re{:4<:[0:1:1:4]rm!.|-4=:1&I,?-2=:1&*3-I=.}w,@Sw\

This takes a number as input and prints to STDOUT the list, with spaces separating each number.
Explanation
§ Main predicate

:0re{...}               § Enumerate integers between 0 and the Input, pass the integer
                        § as input to sub-predicate 1
         w,@Sw          § Write sub-predicate 1's output, then write a space
              \         § Backtrack (i.e. take the next integer in the enumeration)

§ Sub-predicate 1

:4<                     § If the input is less than 4
   :[0:1:1:4]rm!.       § Then return the integer in the list [0,1,1,4] at index Input

|                       § Else

-4=:1&I,                § I = sub_predicate_1(Input - 4)
        ?-2=:1&*3-I=.   § Output = sub_predicate_1(Input - 2) * 3 - I

The cut ! in the first rule of sub-predicate 1 is necessary so that when we backtrack (\), we don't end up in an infinite loop where the interpreter will try the second rule for an input less than 4.

MATL, 17 18 bytes
0ll4i:"y3*5$y-](x

Almost direct translation of Martin's CJam answer.
Try it online!
0ll4       % push first four numbers: 0,1,1,4
i:         % input n and generate array [1,2,...,n]
"          % for loop. Repeat n times
  y        % copy second-top element from stack
  3*       % multiply by 3
  5$y      % copy fifth-top element from stack
  -        % subtract. This is the next number in the sequence
]          % end loop
(x         % indexing operation and delete. This gets rid of top three numbers

Mathematica, 56 bytes
f@0=0
f@1=f@2=1
f@3=4
f@n_:=3f[n-2]-f[n-4];
f/@0~Range~#&

Very straightforward implementation. Defines a helper-function f and then evaluates to an unnamed function which applies f to a range to get all the results. This feels unnecessarily cumbersome.
A single unnamed function seems to be one byte longer though:
Switch[#,0,0,1,1,2,1,3,4,_,3#0[#-2]-#0[#-4]]&/@0~Range~#&

R, 55 bytes
A=c(0,1,1,4);for(x in 4:scan()+1)A[x]=3*A[x-2]-A[x-4];A

Try it online!

-24 bytes thanks to JayCe

Save 24 bytes!

Mathematica, 41 bytes
LinearRecurrence[{0,3,0,-1},{0,1,1,4},#]&

Groovy, 50 Bytes
x={a,b=0,c=1,d=1,e=4->a<0?:[b,x(a-1,c,d,e,3*d-b)]}

This defines the function x, which takes in n as it's first argument and has the base case of the first four numbers in the Fibocas sequence as default arguments for the rest of the function.
a here is n. b, c, d, and e are the next four elements in the sequence.
It decrements n and recurses until n is less than zero-- when it recurses, it adds on to the ultimate return value the first element in its current sequence. The new values for the next four elements in the sequence are given to the recursive call-- the last three elements are shifted over to be the first three, and a new fourth element is generated from two of the previous elements using 3*d-b.
It delimits new values with list nestings, as groovy can return multiple values by stuffing them into a list-- so each call returns the current first element and the result of recursion, which will be its own list.

C++ Template Meta Programming, 130 bytes
template<int X>struct L{enum{v=3*L<X-2>::v-L<X-4>::v};};
#define D(X,A) template<>struct L<X>{enum{v=A};};
D(0,0)D(1,1)D(2,1)D(3,4)

Recursive definitions somehow cry for C++TMP, usage:
L<x>::v

with x being the A(x) you like.

Pylons, 19
This is a pretty direct translation of Martin's approach.
0114{@-4@-33*-,i}=4

How it works:
0114    # Push 0, 1, 1, 4 to the stack.
{       # Start a for loop.
 @-4    # Get the stack element at index -4
 @-3    # Get the stack element at index -3
 3      # Push 3 to the stack.
 *      # Multiply the top two elements of the stack.
 -      # Subtract the top two elements of the stack.
  ,     # Switch to loop iterations.
 i      # Get command line args.
}       # End for loop.
=4      # Discard the top 4 elements of the stack.

DUP, 32 bytes
[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]

Try it here!
An anonymous lambda that leaves a sequence of numbers on the stack. Usage:
8[a:0 1$4[a;1-$a:][1ø3*4ø-]#%%]!

Explanation
[                              {start lambda}
 a:                            {save input number to a}
   0 1$4                       {base cases to get us started}
        [       ][       ]#    {while loop}
         a;1-$a:               {a--, check if a>0}
                  1ø3*4ø-      {3*stack[n-2]-stack[n-4]}

                           %%  {discard top 2 stack items}
                             ] {end lambda}

Python 2, 71 bytes
def a(n,x=0,y=1,z=2,w=1,p=0):
 if~n:print[x,z][p];a(n-1,y,x+y,w,z+w,~p)

This definitely seems too long.  However, I was pleased that I got to use the bitwise not operator...twice.  Once as kind of a parity flip back and forth, and once to terminate the recursion when n reaches -1.
The variable p will always be either 0 or -1, so it will alternate between entries 0 or -1 of the list. (Choosing entry -1 of a Python list means choosing the last element.)

Jelly, 8 bytes
ŻÆĿÆḞḂ?€

Try it online!
Close to a literal interpretation of the spec
How it works
ŻÆĿÆḞḂ?€ - Main link. Takes N on the left
Ż        - Range from 0 to N
       € - Over each integer k:
      ?  -   If:
     Ḃ   -     Condition: k mod 2
 ÆĿ      -     Truthy: kth Lucas number
   ÆḞ    -     Falsey: kth Fibonacii number

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


text:
Decimal Multiplication of Strings
Given two inputs, a string \$s\$ and a decimal number \$n\$, output the string multiplied by that number.
The catch is that the number can be a float or an integer.
You should output the string \$\lfloor n \rfloor\$ times and then the first \$\lfloor (n - \lfloor n \rfloor) \cdot |\,s\,|)\rfloor\$ characters again.
Other notes:

The input will not always be a float, it may be an integer.
So 1.5, 1, and 1.0 are all possible.
It will always be in base 10 though, and if you wish an exception please comment.
The string input may contain white space except newlines, quotes and other characters.
Control characters are excluded, too, if this helps.
No built-ins for direct string repetition are allowed.
That means for instance Python’s 'a'*5 is forbidden.
Nevertheless string concatenation (frequently denoted by the + sign) is allowed.

Test cases

\$s\$
\$n\$
result

test case
1
test case

case
2.5
casecaseca

(will add more later)
0.3333
(will

cats >= dogs
0.5
cats >

Final Note
I am seeing a lot of answers that use builtin string multiplication or repetition functions.
This is not allowed.
The rule is:
If it directly multiplies the string, you cannot do it.

The wording was modified repeatedly (I did not see the first revision). I suggest to remove direct string repeating (what does this mean?). But all in all you're right

Related quine version

@Sp3000 yeah, I know.  I think the difference is significant enough.

"No built-ins for direct string repeating, even string multiplication like the python 'a'*5 are allowed." You don't explain the difference between these. They sound the same to me.

@edc65 In Perl you can do list repetition then concatenate the elements of that list, which isn't direct string repetition. In Perl 5: join "", ("case") x 2 vs "case" x 2, in Perl 6 [~] "case" xx 2 vs the same "case" x 2

@BradGilbertb2gills yes, that is allowed.  So are stack duplication operators and number*number multiplication.

I'm not voting to close, since I would hammer this and I consider it a bit of a grey area, but I believe this is being voted unclear because of the "no builtins" clause. See this answer.  Although If anyone who actually voted would like to comment I would take their word over mine.

Jelly, 5 bytes
×L}Rị

Doesn't use a repetition built-in. Try it online!
How it works
×L}Rị  Main link. Left input: n (multiplier). Right input: S (string)

 L}    Yield the length of S.
×      Multiply it with n.
   R   Range; turn n×len(S) into [1, ... floor(n×len(S))].
    ị  Retrieve the elements of S at those indices.
       Indices are 1-based and modular in Jelly, so this begins with the first and
       jump back after reaching the last.

Java 7, 89
void g(char[]a,float b){for(int i=0,l=a.length;i<(int)(l*b);)System.out.print(a[i++%l]);}

takes char[] and float and outputs to STDOUT. basic looping.

Good golfing, even for java. :P

this was suggested on my other answer too, but i don't think i will do this. it does not seem right to me.

Eh, fair enough. It is recognized here, but alright. :D

I recommend declaring your language as Java 7. Then no one can tell you to use lambdas.

JavaScript (ES6), 50 bytes
Edit 2 bytes more to include definition of function f. 1 byte less using the tip of @manatwork. Note: using ~ we have more iterations than necessary, but this is code golf and even 1 byte counts
f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l)

TEST

f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l)

//TEST
console.log=x=>O.textContent+=x+'\n'
;[
 ['test case', 1, 'test case'],
 ['case', 3.5, 'casecasecaseca'],
 ['(will add more later)', 0.3333, '(will '],
 ['cats >= dogs', 0.5, 'cats >']]
.forEach(t=>{
  var s=t[0],n=t[1],x=t[2],r=f(s,n);
  console.log("«"+s+"» "+n+' => «'+r+'» '+(x==r?'OK':'FAIL expected '+x));
 })

Okay, thanks.  So far most of the answers have had no problem, and it is really easy to fix.  Thanks for correcting it.

Tiny typo: n>0 in the code vs. n>1 in the test case.

@manatwork thanks. It should work either way

Oh. Indeed. But then why not just ~n? (Really just a question. Tried only the given test cases.)

@edc65 Where is f defined in your solution? Aren't you missing f=?

@dev-null oh oh oh you'r perfectly right, this is recursive. My fault. Thanks for pointing it out

Pyth, 9 8
s@Lz*lzQ

Saved 1 byte thanks to Pietu1998
This takes floor(n * len(string)) letters from the string, using cyclical indexing. I believe this is always equivalent to the given formula.
Test Suite

No plz don't take this from me this soon. xD

@VoteToClose I actually didn't read your answer at all, scouts honour :P I didn't even realise that string repetitions were disallowed, this was just shorter that what I came up with that way...

You don't even need the second s. range is funny like that.

NOO! cries in a corner Ah, oh well.

Vitsy, 9 bytes
Expects the word as an argument, and the number to multiply by through STDIN.
zlW*\[DO{]
z          Grab all string argument input.
 l         Get the length of the stack.
  W        Parse STDIN.
   *       Multiply the top two items (length of string and the number of repetitions)
    \[   ] Do the stuff in the loop.
      DO{  Output one char at a time, making sure to duplicate first.
Try it online!

True to your word, you answered fast.

@RikerW Martin out FGITW'd me.

Why do you Grab all string argument input. and then Parse STDIN. again?

@RikerW Arguments that are doubles are automatically parsed, pushing them to the stack immediately. Handling that takes more bytes than it's worth.

Oh okay. That makes more sense now.

CJam, 10 bytes
l_,l~*,\f=

The string is supplied on the first line of STDIN, the float on the second.
Test it here.
Explanation
l    e# Read string.
_,   e# Duplicate and get its length.
l~   e# Read second line and evaluate.
*    e# Multiply them. If the result, N, was floored it would give us the number of
     e# characters in the required output.
,    e# Get range [0 1 ... ⌊N⌋-1].
\f=  e# For each character in that range, fetch the corresponding character from the
     e# string using cyclic indexing.

Python 2, 71 bytes
lambda s,x:"".join(s for i in range(int(x)))+s[:int(len(s)*(x-int(x)))]

Try it here!
Creates an unnamed lambda which takes the string as first argument and the float as second. Returns the repeated string.
This could be 46 if string repetition builtins were allowed :(

Much sad. Such string multiplication rules. +1 A+ for effurt.

Ruby, 49 48 characters
->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}

Sample run:
2.1.5 :001 > ->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}['case', 2.5]
 => "casecaseca"

Perl 6,  46 41  39 bytes
{([~] $^a xx$^b)~$a.substr(0,$a.chars*($b%1))}    # 46 bytes
{substr ([~] $^a xx$^b+1),0,$a.chars*$^b}         # 41 bytes
{substr ([~] $^a xx$^b+1),0,$a.comb*$b}           # 39 bytes

Perl 6 has both a string repetition operator x and a list repetition operator xx.
Since the rules disallow string repetition, we repeat it as if it was a single element list instead. Then the list gets concatenated together, and a substring of it is returned.
Usage:
# give it a lexical name
my &code = {substr ([~] $^a xx$^b+1),0,$a.chars*$^b}
#          {substr ($^a x$^b+1),0,$a.chars*$^b}

say code('test case', 1).perl;                  # "test case"
say code('case', 2.5).perl;                     # "casecaseca"
say code('(will add more later)', 0.3333).perl; # "(will "
say code('cats >= dogs', 0.5).perl;             # "cats >"

substr ([~] $^a xx$^b+1),0,$a.comb*$b} saves two chars

osascript, 173 bytes
Oh my days, this is worse than I thought.
on run a
set x to a's item 1's characters
set y to a's item 2
set o to""
set i to 1
set z to x's items's number
repeat y*z
set o to o&x's item i
set i to i mod z+1
end
o
end
Returns the value of the string, another answer using cyclical indexing. Expects input as "string" "repetitions".

Oh my days, this is worse than I thought. So true, so true.

Is there a multiple var set at once command? ie set x,y to a's items?

@RikerW I don't think so. If there is, I'm seriously missing out.

Haskell, 44 bytes
c x=x++c x
s#n=take(floor$n*sum[1|a<-s])$c s

Usage example: "(will add more later)" # 0.3333 -> "(will ".
How it works: c concatenates infinite copies of the string x. It behaves like the built-in cycle. sum[1|a<-s] is a custom length function that works with Haskell's strict type system as it returns a Double (the built-in length returns an Int which cannot be multiplied with n). # takes floor (n * length(s)) characters from the cycled string s.

PHP 5, 96 87
9 bytes saved thanks to @manatwork
<?for($i=$z=0;$i++<floor(strlen($a=$argv[1])*$argv[2]);$z++)echo$a[$z]?:$a[$z=0];

Pretty straight forward looping answer.
Ungolfed
<?
$a=$argv[1];
$z=0;
for($i=0; $i < floor(strlen($a)*$argv[2]); $i++) {
    // if the string offset is not set
    // then reset $z back to 0 so we can
    // echo the beginning of ths string again
    @$a[$z] ?: $z=0;
    echo $a[$z];
    $z++;
}

Not sure when should that error suppression help, for me seems to work without @ too: <?for($i=$z=0;$i++<floor(strlen($a=$argv[1])*$argv[2]);$z++)echo$a[$z]?:$a[$z=0];

I was getting a notice on case #2 which caused the output to render incorrectly, which is when I added in the suppression. (running in CLI mode)

“PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED.” – error_reporting So we prefer to base our solutions on default configuration and not to care about notices and other good habits. For example ignoring the initialization of $z and $i.

Oh, cool. Thanks for the info!

Perl, 51 + 3 = 54 bytes
$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]

Requires: -n, -l and -M5.010 | -E:
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'test case\n1'
 test case
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'case\n2.5'
 casecaseca
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'(will add more later)\n0.3333'
 (will
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'cats >= dogs\n0.5'
 cats >

Explanation:
$l=<>*y///c;              # Calculate output length (eg. 2.5 * input length)
for$i(1..$l){push@a,/./g} # Push a lot of chars from input into @a
say@a[0..$l-1]            # Slice @a according to output length

R, 59 bytes
function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l)))

As an unnamed function.  This uses charToRaw to split the string into a vector of raws.  This is filled into an array of length * l, converted back to char and output.
I was going to use strsplit, but it ended up being longer.
Test
> f=
+ function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l)))
> f('test case', 1) # -> test case
test case
> f('case', 2.5) # -> casecaseca
casecaseca
> f('(will add more later)', 0.3333) # -> (will(space)
(will
> f('cats >= dogs', 0.5) # -> cats >
cats >
>

c (preprocessor macro), 71
j,l;
#define f(s,m) l=strlen(s);for(j=0;j<(int)(l*m);)putchar(s[j++%l])

Not much tricky here.  Just need to make sure l*m is cast to an int before comparing to j.
Try it online.

Oracle SQL 11.2, 154 152 bytes
WITH v(s,i)AS(SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL UNION ALL SELECT :1||s,i+1 FROM v WHERE i<=:2)SELECT MAX(s)FROM v;

Un-golfed
WITH v(s,i) AS
(
  SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL
  UNION ALL
  SELECT :1||s,i+1 FROM v WHERE i<=:2
)
SELECT MAX(s) FROM v;

I went the recursive way, with the initialisation select taking care of the decimal part.
Saved 2 bytes thanks to @MickyT

You can save a couple by removing spaces after the ) in the WITH clause and the final select.

Another saving would be to replace FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1))) with MOD(:2,1)*LENGTH(:1)

And one last one :), you can use LPAD rather than SUBSTR

Seriously, 24 bytes
,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ

Try it online!
Explanation:
,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ
,╗                        get first input (string) and push it to register 0
  ,mi@≈                   get input 2 (x), push frac(x) (f), int(x) (n)
       ╜n                 push n copies of the string
         ╜l(*≈            push length of string, multiply by f, floor (substring length) (z)
              r`╜E`MΣ     push s[:z]
                     )kΣ  move fractional part of string to bottom, concat entire stack

Pyth, 9 bytes
V*Elzp@zN

Basically just doing
             z = input()
V*Elz        for N in range(evaluatedInput()*len(z)):    # flooring is automatic
     p@zN        print(z[N], end="")                     # modular indexing

Pascal, 138 B
This full program requires a processor compliant with ISO standard 10206 “Extended Pascal”.
Trivial cases have been excluded:
It is presumed that the input string s is non-empty and n is positive.
NB:
The golfed version caps s at a reasonable length of 999.
program p(input,output);var s:string(999);n:real;begin
read(s,n);while n>1 do begin n:=n-1;write(s)end;write(s[1..trunc(length(s)*n)])end.

Ungolfed:
program decimalMultiplicationOfStrings(input, output);
    var
        { `string` is a schema data type defined by Extended Pascal.
          The `string(maxInt)` discriminates the schema data type.
          Henceforth the specific `string` has a capacity of `maxInt`. }
        s: string(maxInt);
        n: real;
    begin
        { You can specify `real` as well as `integer` literals for `n`.
          An `integer` value is automatically promoted to `real`. }
        read(s, n);
        { The `string` subrange notation used below in the last line
          may not specify an empty range (e. g. `1‥0` is illegal).
          Therefore the `while` loop’s condition is `n > 1`.
          If `n = 1`, the one copy is printed via the final line. }
        while n > 1 do
        begin
            n ≔ n − 1;
            write(s);
        end;
        { The subrange notation is defined by Extended Pascal.
          It cannot be used for strings that are `bindable`. }
        write(s[1‥trunc(length(s) * n)]);
    end.

Input is end-of-line separated.
s can otherwise contain any character from chr(0) to (the implementation-defined) maxChar range.

Nim, 75 bytes
func r[S,F](s:S,n:F):S=
 for i in 0..<int n*s.len.float:result&=s[i%%s.len]

Attempt This Online!

Scala, 68 bytes
Golfed version. Try it online!
(s,n)=>{val l=s.length;(0 to (n*l).toInt-1).map(i=>s(i%l)).mkString}

Ungolfed version. Try it online!
object Main {
  def repeatString(s: String, n: Double): String = {
    val len = s.length
    val repeatLen = (n * len).toInt
    (0 until repeatLen).map(i => s(i % len)).mkString
  }

  def main(args: Array[String]): Unit = {
    println(repeatString("case", 2.5))
  }
}

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


text:
Align function arguments on their own lines
Given an input of a string representing a function definition, output the
string with newlines and spaces inserted so that the function's arguments are
newline-separated and aligned.
The input string will follow the following pattern:

First, it will start with a prefix, which is always at least one character
long and does not contain any of the characters ,().
An open parenthesis (() will then mark the beginning of the argument list.
A list of zero or more arguments will then follow. These are separated by the
string ", " (a comma and then a space). None of the arguments will contain
any of the characters ,().
A close parenthesis ()) will mark the end of the argument list.
Lastly, a postfix may be found, which is zero or more characters long and
may contain the characters ,().

The input string will consist solely of printable ASCII (which means it will never contain a newline).
The output must be:

The prefix, copied down verbatim, and the open parenthesis.
The argument list, this time separated not by ", " but by a comma, newline, and as
many spaces as is needed to vertically align the first character of each
argument.
The close paren and postfix (if it exists) verbatim.

Since this is code-golf, the shortest code in bytes will win.
Test cases (format: single-line input followed by output followed by double
newline):
def foo(bar, baz, quux):
def foo(bar,
        baz,
        quux):

int main() {
int main() {

fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

function g(h) {
function g(h) {

def abc(def, ghi, jkl, mno)
def abc(def,
        ghi,
        jkl,
        mno)

x y z(x, y, z) x, y, z)
x y z(x,
      y,
      z) x, y, z)

Haskell, 115 bytes
import Data.Lists
f x|(a,b:c)<-span(/='(')x,(d,e)<-span(/=')')c=a++b:intercalate(",\n "++(a>>" "))(splitOn", "d)++e

Usage example:
*Main> putStrLn $ f "fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {"
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

How it works:
bind
  a: everything before the first (
  b: the first (
  c: everything after the first (
  d: everything of c before the first )
  e: everything of c from the first ) to the end

construct the output string by concatenating
  a
  b
  splitting d at the argument separator ", " and rejoining it with ",\n " followed by (length a) spaces
  e

a>>" " is really clever...

Japt, 23 bytes
¡Y?X:Xr',",
"+SpUb'(}')

Test it online!
How it works
               // Implicit: U = input string
¡        }')   // Map each item X and index Y in U.split(")") to:
Y?X            //  If Y is non-zero, X. This keeps e.g. "(String, Vec<i32>)" from being parsed.
:Xr',",\n"+    //  Otherwise, X with each comma replaced with ",\n" concatenated with
SpUb'(         //  U.indexOf("(") spaces.
               // Implicit: re-join with ")", output

Perl, 62 52 + 2 = 54 bytes
s/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e

Requires the -p flag:
$ echo "x y z(x, y, z) x, y, z)
fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {" | \
perl -pe's/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e'
x y z(x,
      y,
      z) x, y, z)
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

How it works:
# '-p' reads first line into $_ and will also auto print at the end
s/\(.*?\)/             # Match (...) and replace with the below
  $a=$"x length$`;     # $` contains all the content before the matched string
                       # And $" contains a literal space
  $&=~s|               # Replace in previous match
    (?<=,)[^,]+        # Check for a , before the the string to match
                       # This will match ' b: f64', ' c: String'
  |\n$a$&|gr/e         # Replace with \n, [:spaces:] and all the matched text

Retina, 31 bytes
(?<=^([^(])*\([^)]*,)
¶ $#1$*

Note the spaces at the end of both lines.
We replace every space which has the regex ^([^(])*\([^)]*, before it. The replacing string will be a newline, and the number of the captures with ([^(])* plus one spaces.
A more coherent explanation comes later.
Try it online here.

ES6, 68 67 bytes
s=>s.replace(/\(.*?\)/,(s,n)=>s.replace/, /g, `,
 `+` `.repeat(n)))

This works by extracting the argument list from the original string, and replacing each argument separator with indentation calculated from the position of the argument list within the original string.
Edit: Saved 1 byte thanks to @ETHproductions.

I was wondering why you did .split`, `.join(...) instead of .replace(...). Turns out the other is a byte shorter: s=>s.replace(/\(.*?\)/,(s,n)=>s.replace(/, /g,`,\n `+` `.repeat(n)))

Pyth, 35 30 bytes
+j++\,b*dhxz\(c<zKhxz\)", ">zK

Try it here!
Explanation:
+j++\,b*dhxz\(c<zKhxz\)", ">zK    # z = input()

                 Khxz\)           # Get index of the first ")"
               <z                 # Take the string until there...
              c        ", "       # ...and split it on the arguments
 j                                # Join the splitted string on...
  ++                              # ...the concatenation of...
    \,b                           # ...a comma followed by a newline...
       *dhxz\(                    # ...followed by the right amount of spaces = index of the first "(" + 1
+                         >zK     # Concat the resulting string with the postfix

Groovy, 137 89 95 bytes
Groovy is not the "Right Tool for the Job"™. Edit: It works just fine when you have someone with a brain using it...
f={s=(it+' ').split(/\0/)
s[0].replace(',',',\n'+(' '*it.indexOf('(')))+')'+s[1..-1].join(')')}

Tests:
println f("def foo(bar, baz, quux):")
println f("int main() {")
println f("fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {")
println f("function g(h) {")
println f("def abc(def, ghi, jkl, mno)")
println f("x y z(x, y, z) x, y, z)")

Somewhat ungolfed:
f = {String it ->
    def str = (it + ' ').split(/\)/)
    return (str[0].replace (',', ',\n'+(' ' * it.indexOf('('))) + ')' + str[1])
}

Retina, 47 bytes
Byte count assumes ISO 8859-1 encoding.
m+`^(([^(]+.)[^,)]+,) (.+)
$1¶$2$3
T`p` `¶.+?\(

Try it online!

JavaScript (ES6), 85
s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')

Test

f=s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')

console.log=x=>O.textContent+=x+'\n'

;['def foo(bar, baz, quux):',
  'int main() {',
  'fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {',
  'function g(h) {',
  'def abc(def, ghi, jkl, mno)',
  'x y z(x, y, z) x, y, z)']
.forEach(t=>console.log(t+'\n'+f(t)+'\n'))

I'm sorry, I was mistaking, was running the code in my console and the output was something like this: "x y z(x as you can see the " thats why I was thinking it was one space off. Hence the deletion

@dev-null that happens to me all the time.

Jelly, 39 bytes
ṣ”)Ḣṣ”(Ṫ©œṣ⁾, ji”(⁶ẋƊ⁾,¶;ƊḢ,j®${jʋ@œṣ®$

Try it online!


text:
Implement the Enigma Machine
The Enigma machine is a fairly complex cipher machine used by the Germans and others to encrypt their messages.  It is your job to implement this machine*.
Step 1, Rotation
Our enigma machine has 3 slots for rotors, and 5 available rotors for each of these slots. Each rotor has 26 different possible positions (from A to Z).  Each rotor has a predefined notch position:
Rotor  Notch
------------
1      Q
2      E
3      V
4      J
5      Z

On keypress the following steps occur:

The rotor in Slot 1 rotates
If the rotor in Slot 1 moves past its notch, then it rotates the rotor in Slot 2.
If the rotor in Slot 2 is in its notch (but didn't just move there), both rotor 2 and 3 rotate once.

If we are using rotors 1,3,5 and they are in positions P,U,H then the sequence of positions is: P,U,H > Q,U,H > R,V,H > S,W,I
Step 2, Substitution
Each of the rotors performs a simple character substitution.  The following is a chart of each of the rotors in the A position:
  ABCDEFGHIJKLMNOPQRSTUVWXYZ
  --------------------------
1 EKMFLGDQVZNTOWYHXUSPAIBRCJ
2 AJDKSIRUXBLHWTMCQGZNPYFVOE
3 BDFHJLCPRTXVZNYEIWGAKMUSQO
4 ESOVPZJAYQUIRHXLNFTGKDCMWB
5 VZBRGITYUPSDNHLXAWMJQOFECK
R YRUHQSLDPXNGOKMIEBFZCWVJAT

Rotor 1 in position T is PAIBRCJEKMFLGDQVZNTOWYHXUS, which would substitute the letter C for I.
After the three rotors perform their substitution, the reflector is hit (listed as R above).  It performs its own substitution, and then reflects the signal back through the rotors.  The rotors then perform a reverse substitution in reverse order.
Reverse substitution means that instead of Rotor 1 substituting A with E, it substitutes E with A
Slots are filled with rotors 1,2,3 all in position A.  The letter Q follows the path Q>X>V>M through the rotors.  M reflects to O, which then follows the reverse path of O>Z>S>S.  Therefore, A is substituted with S.
Input/Output
You are passed:

A list of 3 rotors (as integers)
A list of 3 starting rotor positions (as letters)
A string that needs to be encrypted.

You can assume that your input will be well formed, and all characters will be uppercase letters, no spaces.
You must return the encrypted string.
You can optionally accept the rotors, notches, and reflectors as input.  For those that don't can take off 95 bytes from their score, as 95 = ceil(log2(26 letters ^(26*6 rotors +5 notches))/8 bytes)
Test cases
Rotor Position Input              Output
4,1,5 H,P,G    AAAAAAAAA          PXSHJMMHR
1,2,3 A,A,A    PROGRAMMINGPUZZLES RTFKHDOCCDAHRJJDFC
1,2,3 A,A,A    RTFKHDOVZSXTRMVPFC PROGRAMRXGVGUVFCES
2,5,3 U,L,I    GIBDZNJLGXZ        UNCRAUPSCTK

My implementation can be found on Github.  I've tested it, but I may have bugs in my implementation (which would mean that my test cases are likely wrong).
*I've tried to make this as accurate as possible, but due to the variations between machines, I may have some details wrong.  However, your task is to implement what I've described, even if I'm inaccurate.  I'm not including the plugboard for simplicity

This is a correct implementation for the encryption algorithm used in the Enigma I, M3 & M4. All the settings are present, the plugboard and the Uhr switch work as well: https://github.com/arduinoenigma/ArduinoEnigmaEngineAndUhr This is the same encryption engine used in the Arduino Enigma Machine Simulator

I think I understand, but it doesn't seem to work right. Here is a gist explaining it https://gist.github.com/JJ-Atkinson/ddd3896fe10d85b3b584.

In the first example you said "if we are using rotors 1, 3 and 5" but I think this would be rotors 1, 2 and 5 (or whatever for the last).

@coredump Fixed

Is my understanding of how rotors work still incorrect?

@JAtkin I believe I found a bug, and updated one of my examples.  Do you match now?

Not quite, this is what I think should be happening https://gist.github.com/JJ-Atkinson/ddd3896fe10d85b3b584, But I may still be wrong about how the substitution part works.

Do the reflectors rotate when the letter is sent back through them from the reflector?

No.  Rotation happens before substitution.

My solution agrees with @JAtkin's outputs for the test cases (and I worked the AAAAAAAAA example by hand to double check), so I've updated the test cases to reflect that. I believe your implementation contains a bug when finding the notches. For some reason, running your implementation with the last test case (making it show the notches it's rotating on) shows the notches as S,K,M not E,Z,V which is what they should be. I'd include a TIO link, but it's too long, try adding print(*rotors, notches) as the last line of rotate_all

@cairdcoinheringaahing sounds good.  Thanks for updating the test cases.  I don't care to update my reference implementation, as there are plenty of other implementations here :)

Jelly, 42 38 37 bytes
="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ḷ⁹©Ç€

Try it online!
Verify each test case
This is extremely liberal with the input format. It takes input in the following way:

The three rotors (the strings, not the numbers) as the first command line argument, each rotated so that the starting points are the first characters
The message as the second command line argument
The 3 specific notches as the third command line argument
The reflector as the fourth command line argument

In the above TIO link, the Footer converts a triple of numbers (the rotors) into the rotor strings, then rotates them to the correct order, so that you don't have to do it yourself.
However, for 45 bytes we can have a program which takes input in the following way:

The message, on STDIN
The three rotors (as the strings) as the first command line argument
The 3 specific notches as the second command line argument
The reflector as the third command line argument
The three starting points for the rotors as the fourth command line argument

Again, the Footer converts the rotors from integers to the corresponding strings.
Finally, if we want to go all the way and just accept 3 inputs (the rotors, as integers, the starting positions and the message (thus have -95 to our score)), we get a score of 44

How it works
As they all use the same underlying algorithm, I'll just explain the 38 byte version in full, and I'll cover how the other two versions adapt the inputs to match the shortest version. For this explanation: M is the message, R are the three rotor strings, N are the notches, F is the reflector and C is the value in the register (initially 0).
ḷ⁹©Ç€ - Main link. Takes M on the left and R on the right
 ⁹    - Yield R
  ©   - And copy it into the register. C = R
ḷ     - Discard R and yield M
    € - Over each character in M:
   Ç  -   Call the helper link
        Implicitly output the final result

="⁵Ḣ€Ṗ1;ṙ@"µɼ⁶ṭØAiịɗƒµ®Ṛi@ịØAɗƒ - Helper link. Takes a character X on the left

="⁵Ḣ€Ṗ1;ṙ@"µɼ                   - Rotate the rotors
            ɼ                   - Yield C, run the following on it, save the result to C:
           µ                    -   Initially, C = R, the list of rotors
  ⁵                             -   Yield the notches, N
 "                              -   Pair each notch with each rotor, then:
=                               -     Vectorised equality
   Ḣ€                           -   Take the head of each
                                      This yields a triple of bits [a, b, c]
                                      which indicate which rotor hits its notch
     Ṗ                          -   Remove c as rotor 3 has no affect
      1;                        -   Prepend 1 as rotor 1 always moves; [1, a, b]
          "                     -   Pair 1 with rotor 1, a with rotor 2 and b with rotor 3,
                                        then for each pair:
        ṙ@                      -     Rotate the rotor if the bit is 1

             ⁶ṭØAiịɗƒ           - Send the character through the rotors
             ⁶                  - Yield the reflector F
              ṭ                 - Tack it to the end of the rotors, call this C'
                   ɗ            - Group the previous 3 links into a dyad f(U, L):
                                   where U is a character and L a list of characters
               ØA               -   "ABC...XYZ"
                 i              -   Index of U in the alphabet
                  ị             -   Index into L
                    ƒ           - Starting with X, reduce C' by the dyad f(U, L)
                                  As C is a triple of lists of characters, this returns
                                  A = f(f(f(f(X, C[1]), C[2]), C[3]), F), a single character

                     µ®Ṛi@ịØAɗƒ - Send A back through the rotors
                     µ          - Begin a new link with A as the argument
                             ɗ  - Group the previous 3 links into a dyad g(U, L)
                        i@      -   Index of U in L, i
                          ịØA   -   i'th letter of the alphabet
                      ®         - Yield C
                       Ṛ        - Reverse C
                              ƒ - Starting with A, reduce rev(C) by the dyad g(U, L)
                                      This yields g(g(g(A, C[3]), C[2]), C[1]),
                                      which is our intended result

How the other 2 work
The 45 byte version
Taking a look at the code, we notice that the only thing that's changed is that the last line is now
ṙ"©⁶O_65¤ṛɠÇ€

The difference between this version and the 37 byte version is how the rotors are taken as input:

The three rotors (the strings, not the numbers) as the first command line argument, each rotated so that the starting points are the first characters

The three rotors (as the strings) as the first command line argument

The new bits here just rotate the rotors for us and take M from STDIN:
ṙ"©⁶O_65¤ṛɠÇ€ - Main link. Takes R on the left
        ¤     - Create a nilad:
   ⁶          -   The 3 starting points of the rotors
    O         -   Converted to char points
     _65      -   Minus 65
 "            - Zip with each rotor:
ṙ             -   Rotate the rotor that many steps
  ©           - Save this to the register
          ɠ   - Read M from STDIN
         ṛ    - Discard the rotors and yield M
           Ç€ - Call the helper link on each character of M

The 139 byte version
Let's take a look at the full code:
="³ị“QEVJZ”¤Ḣ€Ṗ1;ṙ@"µɼ“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤ṭØAiịɗƒµ®Ṛi@ịØAɗƒ
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØAṙ"©⁴O_65¤ṛɠÇ€

Try it online!
This is very similar to our 45 byte version. In fact, here's what's different in the first lines, with everything that is unchanged, replaced with .
..³ị“QEVJZ”¤..........“¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤.................

Furthermore, you'll note that the end of the first line is ṙ"©⁴O_65¤ṛɠÇ€, which is the first line of the 45 byte version, meaning that there are really only three changes. In this case, those changes are because of the changes to the input system. Here's the first 2:

⁴ \$\to\$ ³ị“QEVJZ”¤. Rather than take the notches as input, we use the rotor list (³) to ịndex into the string of notches “QEVJZ”. The ¤ is simply a precedence marker, telling the program to treat this as a constant

⁵ \$\to\$ “¡ƝḋœṚṗḶw⁸Aß`’œ?ØA¤. Again, this is changing an input into program data, the reflector in this case. ¤ Once again acts as a precedence marker. However, we have 3 new commands here:

œ? is a dyad which takes 2 arguments - on the left, an integer x, and on the right a string, s - and returns the x'th permutation of s
ØA we've already encountered, and is the uppercase alphabet. In this context, it acts as the right argument to œ?
“¡ƝḋœṚṗḶw⁸Aß`’ is the compressed integer \$383316524290458478707255597\$, which is the left argument to œ?

Together, this returns the \$383316524290458478707255597\$th permutation of the uppercase alphabet, or the string "YRUHQSLDPXNGOKMIEBFZCWVJAT"

The final change is the entire start of the last line:
ị“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’œ?ØA

Here, we have a list of massive compressed numbers:
“F.⁻wṣḊ£tọḅɱ“¥AṡḌỴịk⁼UH9“Ñɱ½#Ẋʋẹ¹⁼UṢ“KzBpñÇḅẊẎḳḣ“¡j5ɼ}ṡỴb\£BṆ’

Each “ marks the beginning of a new compressed number, and the entire list is
[67892310845892591685803413, 5023890671354916271018308, 16834429128340685633834184, 72949485053238139997554738, 340670280577577536609579431]

We then take the three integers which correspond to the three rotor inputs with ị, and then use œ?ØA to generate the alphabet permutations we want for each rotor. Finally, these permutations are fed into the rest of the program, already covered above.

Has something gone wrong with the TIO links?  The test cases don't seem to work correctly (they seem to break-down halfway through...)

@DominicvanEssen They're all working for me. If you mean that they're different from the test cases in the question, see the comments below; there was/is a bug in the OP's initial implementation. The correct encoding of UNCRACKABLE for instance should be GIBDZTRRMAA

Yes, that's what I meant.  Unfortunately the links in the comments below the question don't seem to work (I get error 404 not found): so it might be worth including the correct encodings directly into the post.  Anyway, congratulations (a few months late) on a great answer!

Python 3, 403 bytes
I think this is working correctly. The rotors passed to it:
def z(p,o,m,f,g,h):
 O=ord;b=lambda a:a[1:]+a[:1];d=lambda a:chr(a+O('A'));e=lambda a:O(a)-O('A');i=[list(g[i-1])for i in p];j=[f[i-1]for i in p];i=[x[e(y):]+x[:e(y)]for x,y in zip(i,o)];k=[]
 for l in m:
  if i[0][0]==j[0]:i[1]=b(i[1])
  elif i[1][0]==j[1]:i[1]=b(i[1]);i[2]=b(i[2])
  i[0]=b(i[0]);c=l
  for n in i:c=n[e(c)]
  c=h[e(c)]
  for n in reversed(i):c=d(n.index(c))
  k+=[c]
 return''.join(k)

f is the notch, g is the rotors and h is the reflector.
Ungolfed:
shift = lambda rotor: rotor[1:] + rotor[:1]
letter = lambda num: chr(num + ord('A'))
number = lambda chr: ord(chr) - ord('A')

def encode(rotors, rotorStart, message, defaultRotors, reflector, rotorNotchPositions):
    usedRotors = [list(defaultRotors[i - 1]) for i in rotors]
    notches = [rotorNotchPositions[i - 1] for i in rotors]
    usedRotors = [rotor[number(offset):] + rotor[:number(offset)] for rotor, offset in zip(usedRotors, rotorStart)]

    sub = []

    for char in message:
        # print([''.join(rotor) for rotor in usedRotors])
        if usedRotors[0][0] == notches[0]:
            usedRotors[1] = shift(usedRotors[1])
        elif usedRotors[1][0] == notches[1]:
            usedRotors[1] = shift(usedRotors[1])
            usedRotors[2] = shift(usedRotors[2])

        usedRotors[0] = shift(usedRotors[0])

        c = char
        for rotor in usedRotors:
            c = rotor[number(c)]
        c = reflector[number(c)]
        for rotor in reversed(usedRotors):
            c = letter(rotor.index(c))
        sub += [c]
        print([''.join(rotor) for rotor in usedRotors], char, c, message)

    return ''.join(sub)

rotorNotchPositions = 'QEVJZ'
*defaultRotors, reflector = [
    #ABCDEFGHIJKLMNOPQRSTUVWXYZ#
    "EKMFLGDQVZNTOWYHXUSPAIBRCJ",  # 1
    "AJDKSIRUXBLHWTMCQGZNPYFVOE",  # 2
    "BDFHJLCPRTXVZNYEIWGAKMUSQO",  # 3
    "ESOVPZJAYQUIRHXLNFTGKDCMWB",  # 4
    "VZBRGITYUPSDNHLXAWMJQOFECK",  # 5
    "YRUHQSLDPXNGOKMIEBFZCWVJAT"   # R
]

#             Rotor       Position        Input                 Output
assert encode((4, 1, 5), ('H', 'R', 'G'), 'AAAAAAAAA',
              defaultRotors, reflector, rotorNotchPositions) == 'PXSHJMMHR'
assert encode((1, 2, 3), ('A', 'A', 'A'), 'PROGRAMMINGPUZZLES',
              defaultRotors, reflector, rotorNotchPositions) == 'RTFKHDOCCDAHRJJDFC'
assert encode((1, 2, 3), ('A', 'A', 'A'), 'RTFKHDOVZSXTRMVPFC',
              defaultRotors, reflector, rotorNotchPositions) == 'PROGRAMRXGVGUVFCES'
assert encode((2, 5, 3), ('U', 'L', 'I'), 'GIBDZNJLGXZ',
              defaultRotors, reflector, rotorNotchPositions) == 'UNCRAUPSCTK'

I think this is working, but it produces a different output, due to what (I think) is a bug in the reference impl.

Replace both instances of O('A') with 65 to save 8 bytes. Then you don't need the O=ord alias, so replace O=ord;...O(a) with ord(a) saving another 4 bytes. Total 12 bytes.


text:
Print cos(2π/17) exactly
One way to construct a regular heptadecagon starts with drawing a horizontal line of length 1 from the center to a vertex. Then the distance along that line from the center to the second vertex is cos(2π/17). All other vertices are easy to get.
The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations +, -, *, /, sqrt() and the natural numbers, which gives cos(2π/17) when evaluated. The power operator is not allowed: e.g. sqrt(17) cannot be written as 17^(1/2).
For example (formula taken from Wikipedia):
1/16*(
    -1+
    sqrt(17)+
    sqrt(34-2*sqrt(17))+
    2*sqrt(
        17+
        3*sqrt(17)-
        sqrt(34-2*sqrt(17))-
        2*sqrt(34+2*sqrt(17))
    )
)

Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to cos(2π/17).
Built-in functions are allowed.

What degree of precision do we need? Why can't I just hard code the formula if it's always a constant number? Why would I have to calculate any numbers at all?

Infinite precision - it's a symbolic expression, not a number. You can hard-code it, though I think you can do better.

I think this question has been misunderstood. It's fairly clear to me. It's a Kolmogorov complexity requiring An ASCII Math expression evaluating to cos(2pi/17) That is, either a straight text compression of the example expression given, or (as an interesting twist) a significant rearrangement of that expression provided it evaluates to the exact same quantity. Is that correct? Minor nitpick: in addition to natural numbers +,-,*,/ and sqrt() you have also used individual parentheses in other ways so I assume they are allowed. Question: no power operator?  No decimals?

Oops: I missed calculating e.g. cos(π/16) would be OK... That is unclear. We need to know exactly what operators and functions are allowed and what aren't. This question can't be reopened until it's absolutely clear what operators are allowed. I suggest you delete that bit and stick with the square roots.

I removed the confusing part about built-in functions. It's actually interesting to see how one could use dedicated functions to solve this. Wolfram-alpha doesn't try to solve this.

CJam (60 bytes)
1-4{"(- +sqrt( * -4*
))/2"S/@a*N/\a*}:F~'-\+WF'-\+W-4FWFF'/2

Online demo
Output (with added newlines to avoid wrapping):
(--(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/2-4*-1)
)/2+sqrt(-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4))/
2-4*-1))/2*-(--(-1+sqrt(1*1-4*-4))/2+sqrt(-(-1+sqrt(1*1-4*-4))/2*-(-1+sqrt(1*1-4*-4)
)/2-4*-1))/2-4*(-(--1+sqrt(-1*-1-4*-4))/2+sqrt((--1+sqrt(-1*-1-4*-4))/2*(--1+sqrt(-1
*-1-4*-4))/2-4*-1))/2))/2/2

I suspect this is the kind of answer OP was secretly hoping for. Rather than apply general-purpose compression to a string, it uses the field structure which Gauss first exploited to present this value in surds, in his Disquisitiones Arithmeticae.
I worked from this presentation (pages 18 and 19) but adapted it slightly in order to only ever require the positive root of a quadratic. Unrolled and in pseudo-code, the expression breaks down as
# Positive root of x^2 + bx + c = 0
F(b, c) = (-b + sqrt(b*b - 4*c))/2
# (8,1)
p = F(1, -4)
# (4,1)
q = F(-p, -1)
# -(8,3)
r = F(-1, -4)
# (4,3)
s = F(r, -1)
# Result
F(-q, s)/2

Yes, this is an awesome solution!

JavaScript (ES6), 93
Edit 1 byte saved thx @ETHproductions
An anonymous function.
x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])

Output:
(1*sqrt(17)+sqrt(34-2*sqrt(17))+2*sqrt(17+3*sqrt(17)-sqrt(34-2*sqrt(17))-2*sqrt(34+2*sqrt(17)))-1)/16

TEST

F=x=>"(19)+8-29))+29+39)-8-29))-2*8+29)))-1)/16".replace(/8|9/g,n=>["sqrt(34","*sqrt(17"][n-8])

// Math check

k=Math.cos(Math.PI*2/17)
x=F()

v=eval(x.replace(/sqrt/g,"Math.sqrt"))

O.textContent=k+' (Math.cos(Math.PI*2/17))\n'+v+' ('+x+')\n'+(v==k)

Mathematica, 26 bytes
FunctionExpand@Cos[2Pi/17]

Output
1/(4 Sqrt[2/(15+Sqrt[17]-Sqrt[2 (17-Sqrt[17])]+Sqrt[2 (34+6 Sqrt[17]+Sqrt[2 (17-Sqrt[17])]-Sqrt[34 (17-Sqrt[17])]+8 Sqrt[2 (17+Sqrt[17])])])])

Alternative form
CForm@FunctionExpand@Cos[2Pi/17]

gives
1/(4.*Sqrt(2/(15 + Sqrt(17) - Sqrt(2*(17 - Sqrt(17))) + Sqrt(2*(34 + 6*Sqrt(17) + Sqrt(2*(17 - Sqrt(17))) - Sqrt(34*(17 - Sqrt(17))) + 8*Sqrt(2*(17 + Sqrt(17))))))))

I think you should replace each space by the multiplication sign * to make the syntax valid

@anatolyg It is conventional in Mathematica to use space as multiplication. I will add a different form of the same expression soon.

I'm trying to find something similar in Sage, but I can't. :(

Bubblegum, 50 bytes
Hex dump:
78 DA D3 28 2E 2C 2A D1 30 34
D7 D4 06 33 8C 4D 74 61 02 5A
46 50 31 43 73 6D B8 98 B1 2E
16 65 30 31 6D 24 31 30 D2 35
D4 D4 37 34 03 00 AC BC 1B 67

Contains a pesky null byte, so you can’t try it online, but it prints this string:
(sqrt(17)+sqrt(34-sqrt(17)*2)+sqrt(17+sqrt(17)*3-sqrt(34-sqrt(17)*2)-sqrt(34+sqrt(17)*2)*2)*2-1)/16

Is it possible to remove the null byte?

There's not issue with null bytes. The problem is that this file has zlib headers, which Bubblegum expects raw DEFLATE. If you remove the first two bytes (and optionally the last one), it works.

Bubblegum, 39 bytes
0000000: d3 35 d4 37 34 d3 2e 2e 2c 2a d1 30 34 d7 84 b3  .5.74...,*.04...
0000010: 75 8d b4 60 62 da c6 26 98 e2 a8 d2 ba 58 f4 00  u..`b..&.....X..
0000020: 31 82 0b 32 da 02 00                             1..2...

Try it online!
Verification
$ base64 -d > exact-cos.bg <<< 0zXUNzTTLi4sKtEwNNeEs3WNtGBi2sYmmOKo0rpY9AAxggsy2gIA
$ wc -c exact-cos.bg
39 exact-cos.bg
$ bubblegum exact-cos.bg; echo
-1/16+sqrt(17)/16+sqrt(-2*sqrt(17)+34)/16+sqrt(-2*sqrt(2*sqrt(17)+34)-sqrt(-2*sqrt(17)+34)+3*sqrt(17)+17)/8
$ cat verify-cos
#!/usr/bin/python3

from sympy import *

print(Eq(S(input()), cos(2*pi/17)))
$ bubblegum exact-cos.bg | ./verify-cos
True

Vyxal, 37 bytes
17√:£‹34¥d-√:→+¥T17+←-34¥d+√d-√d+16/S

Try it Online!
So... Vyxal uses sympy for numbers, and sympy represents complex equations, such as sqrt(17) + 1, as expressions  that resolve to that.
So, all we  have to do is calculate the number (using the question's formula for convenience) and stringify it.
17√                                   # Push √17
   :£‹                                # Store a copy to the register and push √17 - 1
      34¥d-√                          # Push √(34 - 2√17)
            :→                        # Store a copy to the ghost variable
              +                       # Add to previous
[             ]                       # √17 - 1 + √(34 - 2√17)
               ¥T17+                  # 3√17 + 17
                    ←-                # Subtract ghost variable
                                      # 3√17 + 17 - √(34 - 2√17)
                      34¥d+√d-        # √(34 + 2√17) subtracted from above
               [             ]        # Results in 3√17 + 17 - √(34 - 2√17) - 2√(34 + 2√17)
                              √d      # Take the square root of that doubled
                                +16/S # Add to previous, divide by 16 and format.

golflua, 122 chars
Adapted from this Math.se post.
f='sqrt('y='(1-'..f..'17))'x='('..y..'/2+'..f..y..'*'..y..'/4+4))'w('(2/'..x..'+'..f..x..'/2*'..f..'17+4*'..f..'17))))/4')

which is pretty damn long :( (mostly because of the wasteful .. for concatenating strings).
Output
(2/((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))+sqrt(((1-sqrt(17))/2+sqrt((1-sqrt(17))*(1-sqrt(17))/4+4))/2*sqrt(17+4*sqrt(17))))/4

Which, when evaluated, returns 0.93247222940436

Ruby, 71
I think this could be shorter in another language.
'(s/2)+s-s*2))+s*2+s*72)-4*s-s*2))-8*s+s*2)))-1)/16'.gsub(?s,'sqrt(34')

The above string expression evaluates to the below string. The idea was to rearrange the expression so that a single substitution of s -> sqrt(34 would be the only operation needed to decompress it.
(sqrt(34/2)+sqrt(34-sqrt(34*2))+sqrt(34*2+sqrt(34*72)-4*sqrt(34-sqrt(34*2))-8*sqrt(34+sqrt(34*2)))-1)/16

I assume "produce in any other conventional way" means an expression is enough. If this is not the case: Printing the string in quotation marks would need 2 extra bytes at the beginning of the source code: p . For 5 bytes it can be printed without quotation marks by adding puts. Enclosing it in ->{} yields an anonymous function for 4 extra bytes.

CJam, 68
"2* 17 sqrt( 23) 243-41) (1+0+423+1+41-0-4243+41))"S/~5{s/\*}/W")/"G

Try it online

R 68 bytes
s=sqrt;x=s(17);y=s(34-2*x);cat((x+y+2*s(17+3*x-y-2*s(34+2*x))-1)/16)

Vim, 70 keystrokes
:im a *sqrt(<CR>
:im b a17)<CR>
i(1b-1+1a34-2b)+2b<bsp>+3b-1a34-2b)-2a34+2b)))/16<esc>

Perl 5, 78 bytes
A subroutine:
{'(1S)+T-2S))+2S+3S)-T-2S))-2*T+2S)))-1)/16'=~s/S/*sqrt(17/gr=~s/T/sqrt(34/gr}

View the returned value by means of print sub{...}->() or the like.
Hat tip.


text:
Write a Semiquine
Suppose you have 2 languages, A and B. A string s is a semiquine in A and B if it satisfies the following conditions:

s is a quine in language A.
s is a polyglot in A and B.
The output of running s as a B program is a different string s', which is a quine in B.

The goal of this challenge is to write a semiquine in two distinct languages. This is code-golf, so shortest code wins, with earliest answer used as a tiebreaker.
Rules for Quines
Only true quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, without:

reading your source code, directly or indirectly.
relying on a REPL environment which just simply evaluates and prints every expression you feed it.
relying on language features which just print out the source in certain cases.
using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)

Furthermore, your source code must not consist purely of literals (whether they be string literals, numeric literals, etc.) and/or NOPs. For example, `12 is a polyglot in Jelly and Pyth, but in Jelly it is a NOP and a numeric literal, so it is not valid.
Any non-suppressible output (such as copyright notices, startup/shutdown messages, or a trailing line feed) may be ignored in the output for the sake of the validity of the quine.
Rules for Polyglots
The two languages used must be distinctly different. In particular:

They must not be different versions of the same language (e.g. Python 2 vs. Python 3).
They must not be different dialects of the same language (e.g. Pascal vs. Delphi).
One language may not be a subset of the other one (e.g. C vs. C++1).
One language may not be a trivial derivative of the other (e.g. Matlab vs. Octave2, brainfuck vs boolfuck vs TinyBF vs ShadyAsFuck vs all the other trivial brainfuck derivatives).

Miscellaneous Rules

You may not accept input from STDIN (or any other source). If your chosen language must take input, then either the input must be empty (empty string, piped from /dev/null, etc.), or the output of the program must not depend on the input.
For this challenge, you must write a complete program. Requiring additional code to run the solution is not allowed (such as assigning and calling a lambda function defined in the solution).

1: Yes I know that C is not really a subset of C++. It's close enough to be considered one for the purpose of polyglots, though, so I'm counting it for this challenge.
2: Like point 1 above, though Octave is technically not 100% compatible with Matlab, it was designed to be compatible, and is close enough that allowing a Matlab/Octave polyglot would trivialize the challenge.

Are ESMin's copy blocks allowed?

@ThomasKwa I'm not familiar with ESMin, so could you give me a quick rundown?

There's a command to start a copy block, which gets the source code of everything past it. I think other JS golfing languages might have one too.

@ThomasKwa That would not be allowed under the first rule in the quine rules (no reading the source code, directly or indirectly).

Can we abuse interpreter quirks which aid in making a quine?

@Downgoat So long as it doesn't break any other rules, absolutely. Abusing quirks is kind of the goal of this site :)

@ThomasKwa ESMin can't do this one anyway :P

GolfScript + Fission, 19 18 bytes
{".~
'!+OR"
2<}.~

The trailing linefeed is necessary.
This is a true quine in GolfScript. Try it online!
In Fission it prints
'!+OR"

which is a true quine in Fission. Try it online!
Explanation
In GolfScript, anything of the form
{...}.~

is a quine as long as ... leaves a string with ".~" on the stack. The . duplicates the block, such that there's one copy that gets printed at the end, and the ~ executes it, so we can use its contents to print the .~ itself. In this case, the block pushes the string
".~
'!+OR"

and then truncates it to the first two characters with 2<.
The Fission program really works exactly the same as the quine itself, since the first and third line are entirely ignored by the program.

Ruby + (JavaScript or Python 3), 76 bytes
This is another challenge that can be solved using my new favourite language, the almost-common subset of Ruby, JavaScript, and Python 3; and given that we don't have any answers in exoteric languages yet, and many people like to see non-golfing-language solutions, I thought I'd contribute one. Even better, the same answer solves the challenge in a variety of ways at the same time.
Here's s:
s="'";d='"';n='print("s="+d+s+d+";d="+s+d+s+";n="+s+n+s+";eval(n)")';eval(n)

This is a quine in Ruby. It isn't a quine in JavaScript or Python 3; if you run it in either of those languages, its output s' has a trailing newline, and thus is different:

s="'";d='"';n='print("s="+d+s+d+";d="+s+d+s+";n="+s+n+s+";eval(n)")';eval(n)

However, s' is a polyglot quine in JavaScript and Python 3! (As usual for me, I'm using the Rhino implementation of JavaScript, both for convenience (as it runs from the command line rather than needing a browser), and because it has a weird standard library in which print writes to standard output.) Both languages produce s' as a result of running either program.
As a bonus, this program also solves the problem in reverse. If you decide to run s' in Ruby, it'll print the original program s again. As such, s' is a valid (but slightly longer, at 77 bytes) answer to the question.
At this point, I'm almost starting to think "differences in whether or not the output ends with a newline being sufficient to count two programs as different" should be considered a standard loophole, given that this seems to be a second set of languages (beyond the well known GolfScript/CJam) in which it's possible to pull the trick off.

Vitsy (safe mode) and Y, 9 bytes, noncompeting.
' Ugrd3*Z

In Vitsy, this is a quine. In Y, this prints Ugrd3*Z'; when run, this prints Ugrd3*Z', which is a quine in Y. Y postdates the question, however.
What Vitsy sees:
 ' Ugrd3*Z
 '         Heyyyy a string! Let's do this!
  ........ Capturing a string! Oh, not done? Hm, let's go back to the start.
 '         There we go.
           (space) ...
   U       (no op)
    g      use count, disabled in safe mode
     r     reverse stack
      d3*  push a '
         Z print it all!

What Y sees:
' Ugrd3*Z
'         Push a space.
  U       Wrap around and capture.
   g      Print that. (Nothing else is printed.)

Note that this only works in Safe mode, or, rather, it has some... unintended side effects in non-safe mode.

CJam + GolfScript, 9 bytes
"0$p"
0$p

This is a quine in CJam. In GolfScript, it outputs itself with a trailing newline, which is a quine in GolfScript.
I'm not sure whether CJam should be considered a trivial derivative of GolfScript. But I think they are quite different and at least not trivial.