text:
Parse and Process the Key-Language Input
Let's parse and process Key-Language! Given the input of a sequence of keyboard keypresses and/or special keys, write a program, function, etc. that outputs the product when all the actions are processed based on the following keyboard:
+-------------------------------------------------------+
| ~ | ! | @ | # | $ | % | ^ | & | * | ( | ) | - | + |   |
| ` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | _ | = |Del|
+-------------------------------------------------------+
|TAB| q | w | e | r | t | y | u | i | o | p | [ | ] | \ |
|   | Q | W | E | R | T | Y | U | I | O | P | { | } | | |
+-------------------------------------------------------+
|CAPS | a | s | d | f | g | h | j | k | l | ; | ' | RET |
|     | A | S | D | F | G | H | J | K | L | : | " |     |
+-------------------------------------------------------+
| SHIFT | z | x | c | v | b | n | m | , | . | / | SHIFT |
|       | Z | X | C | V | B | N | M | < | > | ? |       |
+-------------------------------------------------------+
|                                                       |
|                      SPACEBAR                         |
+-------------------------------------------------------+

The keys that output actual characters not consisting of whitespace and are able to be modified by other keys will be known as "character keys", and those that modify the output of other keys or output whitespace will be known as "special keys". The alphabet character keys, which will be shown in the input with uppercase letters, can be modified with either Shift or Caps Lock to produce uppercase letters, and the rest of the character keys can only be modified with Shift to produce their alternate characters. Therefore A in the input corresponds to the a A character key, whose normal output is a and whose modified output, obtainable with either the Shift or Caps Lock key, is A. On the other hand, /, which corresponds to the / ? character key, has a normal  output of / and a modified output of ? obtainable with only with Shift this time.
Rules

The input will always be a string consisting of a sequence of the character keys and special keys. The full special key to string mapping for the input (i.e. the format they are guaranteed to be in the input) and their corresponding actions/outputs are as follows:

 -> Delete the previous character (including whitespace). If called when string is empty, nothing happens. If called 2 or more times in a row, 2 consecutive deletes happen. For instance, "RE" should return an empty string ("") and also "R<RET>E" should return just "E".
<CAPS> -> Enable Caps Lock until <CAPS> appears again, upon which it is disabled, although it is not guaranteed to be disabled by the end of the input. Enabling this only modifies the upcoming alphabet keys resulting in them outputting only uppercase letters. For instance, "<CAPS>RE<CAPS>" results in the output "RE", but <CAPS>.<CAPS> would still result in a ".".
<RET> -> Add a new line.
<SPC> -> Add a single blank space.
<TAB> -> Add 4 spaces.
<SHFT> -> Shift is held down resulting in the alternate character of the upcoming keypress to be output, after which the key is released. For instance, "<SHFT>A" results in the output "A", "<SHFT>1" results in the output "!", and "<SHFT>1234" results in the output "!234" as only the first upcoming keypress is modified and nothing else. It is guaranteed that a character key will succeed a <SHFT>. Therefore, <SHFT><SPC> is not a possible input.

An empty string is also possible as input, for which the output should be nothing.
The use of any built-in that solves this problem directly is disallowed.
The use of standard loopholes is disallowed.

Test Cases
Presented in the format Actual String Input -> Actual String Output followed by an explanation for a few.

1<SHFT>2<TAB><CAPS>R.KAP.<SPC><SHFT>123 -> 1@    R.KAP. !23
Output 1 as the 1 key is pressed without a toggle, then Shift is held down and the 2 key is pressed resulting in the @ output. Then the Shift key is released and Tab is pressed, resulting in a 4 spaced indentation. Following up, the Caps Lock key is pressed, after which the R,.,K,A,P, and . keys are pressed, resulting in the output R.KAP.. Finally, a single space is output followed by shift resulting in !23 being output when the 1,2, and 3 keys are pressed at the end.
<SHFT>ABCDEFG<SHFT>HIJK<SHFT>1<SHFT>2<SHFT>3<SHFT>4567890 -> AbcdefgHijk!@#$567890
The Shift key is held down followed by the A key, resulting in the output A followed by the output bcdefg when the B-G keys are pressed. Then, the Shift key is held down again succeeded by the H key, after which the output is H, followed by ijk when the I-K keys are pressed. Finally, the 1-4 keys are all modified as shift is held down before each keypress resulting in the output !@#$ finished off by 567890 when the 5-0 keys re pressed.
<CAPS>THIS<SPC>IS<SPC>IN<SPC>ALL<SPC>CAPS<CAPS><SPC>NOW<SPC>THIS<SPC>IS<SPC>IN<SPC>ALL<SPC>LOWERCASE -> THIS IS IN ALL CAPS now this is in all lowercase
<TAB><SPC><TAB><SHFT>1 ->          !
<CAPS>WWW<CAPS>.CODEGOLF.STACKEXCHANGE<SHFT>.COM -> WWW.codegolf.stackexchange>com
PROGRAMMING<CAPS><SPC>IS<SPC><CAPS>AWESOME -> programming IS awesome
<RET><RET> -> "" (Empty String)
The delete key is pressed in the beginning after which nothing happens. Then, the Return key is pressed resulting in a new line, which is deleted after the backspace key is pressed again. Finally, the same sequence (new line followed by backspace) is repeated. After all this, the output is an empty string.
<SHFT>HI<SPC>HOW<SPC>ARE<SPC>YOU<SHFT>/<RET><SHFT>I<SPC><SHFT>AM<SPC>O<SHFT>GOOD<SHFT>1 -> Hi how are you?\nI Am Good!
<SHFT>,<CAPS>RET<CAPS><SHFT>. -> <RET>
The string <RET> should be the actual string output. Thus, this should not output a new line.
<CAPS>67890,.;'[]<CAPS> -> 67890,.;'[]
<CAPS><SHFT>A -> A
RE -> "" (Empty String)
U<RET>I -> i
5 -> "" (Empty string)
"" (Empty String) -> "" (Empty String)

This is codegolf so the shortest code in bytes wins!

That's a weird Delete key you have there...

@Dennis Well, I'm describing keys based on my MacBook Pro's keyboard, where the delete key deletes the previous character. I still agree with you though. It's a pretty weird layout.

Ah, that explains it. It's called Backspace on literally every keyboard I've ever owned. mumbles something about normal keyboard keypresses

In test #2, should the output be AbcdefgHijk!@#$567890? Also, in test #8, <SHFT> is at the end of the string, but the rules state: "It is guaranteed that a character key will succeed a ."

@atlasologist Yes, you are right, and nice catch! I forgot to update those.

What does <CAPS><SHFT>A produce?

@LeakyNun That produces A.

Can you have a low position character in input like ? : "

@edc65 Low position characters will be used to signify alphabet character keys, whereas the high position characters will be used to signify all other character keys. For instance, A will be used to signify the A a key, whereas ; will be used to signify the ; : key.

16-bit x86 machine code, 140 139 bytes
Saved 1 byte by replacing DL with DX in the second-to-last opcode. Also corrected jump offsets in disassembly to match hex dump.
Since the nature of the task requires some pre-initialized data, and the answer is not a full program but a function, I assume that there's a data section in the program and the linker promptly updates the address of the data. The address placeholder is denoted by '????'.
This is a hex representation of the code. The parameters are pointer to input string in SI and pointer to the output buffer in DI. Strings are assumed to be NULL-terminated.
8D1E????89F931D231C0FCAC84C07419D0EA72173C3C74263C41720A3C5A770684F675020C20AAEBE2AAC33C41720B3C5A76F324170402D7EBEC2C27EBF94646AC46240F74154848741748741948741A4848741A39F973B34FEBB04680F601EBAAB020AAAAAAB020EBBCB00AEBB84642EB99

Content of the mapping table (25 bytes):
"   =<_>?)!@#$%^&*( :{}|`

The byte count accounts for both code and data.
Disassembly:
8d 1e ?? ??        lea    bx,ds:???? ;Load address of mapping table to BX
89 f9              mov    cx,di      ;Save pointer to output buffer in CX
31 d2              xor    dx,dx      ;DX is the status register, bit 0 - shift status
31 c0              xor    ax,ax      ;bit 8 - caps lock status
fc                 cld               ;Clear DF

_loop:
ac                 lodsb             ;Fetch next char
84 c0              test   al,al      ;If end of string found
74 19              je     _end       ;break
d0 ea              shr    dl,1       ;Copy shift flag to CF and clear it
72 17              jc     _shift     ;Branch to input procssing with shift set
3c 3c              cmp    al,0x3c    ;If AL == '<'
74 26              je     _special   ;branch to special character processing
3c 41              cmp    al,0x41    ;At this point anything
72 0a              jb     _out       ;not in 'A'..'Z' range
3c 5a              cmp    al,0x5a    ;should be printed unmodified
77 06              ja     _out
84 f6              test   dh,dh      ;If caps lock status flag is set
75 02              jne    _out       ;go to printing right away
0c 20              or     al,0x20    ;otherwise convert to lower case
_out:
aa                 stosb             ;Store AL into output buffer
eb e2              jmp    _loop      ;Continue
_end:
aa                 stosb             ;NULL-terminate the output string
c3                 ret               ;and return

_shift:
3c 41              cmp    al,0x41    ;AL in the range [0x27..0x3b] with
72 0b              jb     _xlat0     ;a couple of holes in it

3c 5a              cmp    al,0x5a    ;AL in the range 'A'..'Z'
76 f3              jbe    _out       ;Since shift is active, go print it

24 17              and    al,0x17    ;AL is 0x5b, 0x5c, 0x5d or 0x7e,
04 02              add    al,0x2     ;convert to the [0x15..0x18] range
_xlat:
d7                 xlatb             ;Lookup mapping table (AL=[BX+AL])
eb ec              jmp    _out
_xlat0:
2c 27              sub    al,0x27    ;Convert AL to be a zero-based index
eb f9              jmp    _xlat      ;Reuse lookup code

_special:                            ;The next 4 or 5 chars are special character opcode
46                 inc    si         ;Since correct input format is guaranteed
46                 inc    si         ;don't bother reading & checking all of them,
ac                 lodsb             ;just load the third one and skip the rest
46                 inc    si         ;The lower 4 bits of the 3rd char
24 0f              and    al,0xf     ;allow to differentiate opcodes

74 15              jz     _sc_caps   ;0x0
48                 dec    ax
48                 dec    ax
74 17              jz     _sc_tab    ;0x2
48                 dec    ax
74 19              jz     _sc_spc    ;0x3
48                 dec    ax
74 1a              jz     _sc_ret    ;0x4
48                 dec    ax
48                 dec    ax
74 1a              jz     _sc_shft   ;0x6

_sc_del:                             ;0xC,  opcode
39 f9              cmp    cx,di      ;Check the length of the current output
73 b3              jae    _loop      ;DI <= CX ==> NOOP
4f                 dec    di         ;Remove the last char
eb b0              jmp    _loop
_sc_caps:                            ;<CAPS> opcode
46                 inc    si         ;Consume leftover '>' from the input
80 f6 01           xor    dh,0x1     ;Flip caps lock status bit
eb aa              jmp    _loop
_sc_tab:                             ;<TAB> opcode
b0 20              mov    al,0x20    ;Space char
aa                 stosb             ;Print it three times
aa                 stosb             ;and let the <SPC> handler
aa                 stosb             ;do the last one
_sc_spc:                             ;<SPC> opcode
b0 20              mov    al,0x20    ;Space char
eb bc              jmp    _out       ;Go print it
_sc_ret:                             ;<RET> opcode
b0 0a              mov    al,0xa     ;Newline char
eb b8              jmp    _out       ;Go print it
_sc_shft:                            ;<SHFT> opcode
46                 inc    si         ;Consume leftover '>' from the input
42                 inc    dx         ;Set shift status bit (DL is guaranteed to be zero)
eb 99              jmp    _loop

For 32-bit instruction set the code is absolutely the same except for the first instruction which is 2 bytes longer due to 32-bit addressing (8d1d????????   lea  ebx,ds:????????)

Nice work! :) If it's not too much trouble, can you please check if your program returns and output of i for the test caseU<RET>I and an empty string for the input RE? I clarified the rules a little bit regarding the delete key, so if those 2 test cases don't work, could you please also update your code so that it produces the correct output for those test cases? Thank you!

All test cases succeeded. Why would  work incorrectly? It's just a register decrement with boundary check

All right. I just wanted to make sure that your program worked as it should. Great answer.

We need more special cases. It'd be more interesting if  could not delete the . I can implement it in just 3 bytes.

How would that be more interesting? In reality, the delete key can remove any previously typed in character, so for the purposes of this challenge, it should too. I'm not just going to change the rules so that you can implement it in just 3 bytes while both the other answers are invalidated.

It would also make no sense that  cannot delete <RET> but can still delete both <SPC> , <TAB>, and anything else.

When typing in a shell's command line that perfectly makes sense. But, mind you, I'm not asking for the rule change. Thanks for the challenge.

JavaScript (ES6), 207
Updated to fix the bug with repeated deletes, even some bytes shorter.
s=>s.replace(/<\w+>|./g,x=>(k=x[3])=='L'?o=o.slice(0,-1):k=='P'?l=!l:k=='F'?s=0:o+=k?k<'C'?'    ':k<'D'?' ':`
`:s?l?x.toLowerCase():x:s=")!@#$%^&*("[x]||'_={}|:"<>?'["-+[]\\;',./".indexOf(x)]||x,l=s,o='')&&o

less golfed
s=>s.replace( /<\w+>|./g, x =>
  (k=x[3]) == 'L' ? o = o.slice(0,-1)
  : k == 'P' ? l = !l
  : k == 'F' ? s = 0
  : o+= k ? k < 'C' ? '    ' : k < 'D' ? ' ' : '\n'
  : s ? l ? x.toLowerCase() : x
  : s = ")!@#$%^&*("[x] || '_={}|:"<>?' ["-+[]\\;',./".indexOf(x)] || x,
  l = s, o = ''
) && o

Test

F=
s=>s.replace(/<\w+>|./g,x=>(k=x[3])=='L'?o=o.slice(0,-1):k=='P'?l=!l:k=='F'?s=0:o+=k?k<'C'?'    ':k<'D'?' ':`
`:s?l?x.toLowerCase():x:s=")!@#$%^&*("[x]||'_={}|:"<>?'["-+[]\\;',./".indexOf(x)]||x,l=s,o='')&&o

console.log=(...x)=>O.textContent+=x.join` `+'\n'

;[["1<SHFT>2<TAB><CAPS>R.KAP.<SPC><SHFT>123", "1@    R.KAP. !23"]
,["<SHFT>ABCDEFG<SHFT>HIJK<SHFT>1<SHFT>2<SHFT>3<SHFT>4567890", "AbcdefgHijk!@#$567890"]
,["<CAPS>THIS<SPC>IS<SPC>IN<SPC>ALL<SPC>CAPS<CAPS><SPC>NOW<SPC>THIS<SPC>IS<SPC>IN<SPC>ALL<SPC>LOWERCASE", "THIS IS IN ALL CAPS now this is in all lowercase"]
,["<TAB><SPC><TAB><SHFT>1", "         !"]
,["<CAPS>WWW<CAPS>.CODEGOLF.STACKEXCHANGE<SHFT>.COM", "WWW.codegolf.stackexchange>com"]
,["PROGRAMMING<CAPS><SPC>IS<SPC><CAPS>AWESOME", "programming IS awesome"]
,["<RET><RET>", ""]
,["<SHFT>HI<SPC>HOW<SPC>ARE<SPC>YOU<SHFT>/<RET><SHFT>I<SPC><SHFT>AM<SPC>O<SHFT>GOOD<SHFT>1", "Hi how are you?\nI Am Good!"]
,["<SHFT>,<CAPS>RET<CAPS><SHFT>.", "<RET>"]
,["<CAPS>67890,.;'[]<CAPS>", "67890,.;'[]"]
,["<CAPS><SHFT>A", "A"]
,["U<RET>I", "i"]
,["RE", ""]
,["", ""]].forEach(t=>{
  var i=t[0],k=t[1],r=F(i)
  console.log(
    k==r?'OK':'KO',i,'\n->',r,k==r?'\n':'(should be ->'+k+')\n'
  )
})

Nice job! :) If it's not too much trouble, can you please check if your program returns and output of I for the test case U<RET>I and an empty string for the input RE? I clarified the rules a little bit regarding the delete key, so if those 2 test cases don't work, could you please also update your code so that it produces the correct output for those test cases? Thank you!

Wrong for these test cases. I have to take another approach. Meanwhile, i presume U<RET>I should give i not I

Yes, you are correct about that. Updated.

Retina, 136 bytes
Probably can be golfed further.

<SHFT>
§
<SPC>

<TAB>

<CAPS>
¶
<RET>
þ

÷
T`L`l`(?<=^(.*¶.*¶)*).+
T`-=;'[]/\\,.w`\_+:"{}?|<>_)!@#$%^&*(lL`§.
§|¶

i(`þ
¶
[^§]?÷

Verify all testcases. (Slightly modified to run all testcases at once.)

Caps + Shift + A = a on my keyboard.

@Neil Well, for the purposes of this challenge (and according to my Macbook Pro's keyboard) Caps+Shift+A = A. Man my keyboard is weird...

CAPS + SHIFT + A = A. Why on earth would caps invert shift??

@cat in millions on Windows system CAPS invert shift, no matter how many question marks you write. Because it's convenient and users are used to it

@edc65 So does that mean that CAPS+SHIFT+/ = / on Windows systems?

@R.Kap No, CAPS+SHIFT+/ is ?, but CAPS+SHIFT+A is a. Or else, how can you type a when you pressed caps-lock?

Also, fixing that does not change my byte-count at all (and it's only 1 byte that needs to be changed).

@LeakyNun ...Maybe you could, I don't know, turn off Caps Lock when you don't need it? Otherwise, what is the point of having Caps Lock on when you don't need to type several uppercase letters in succession?

Then what would be the use of SHIFT when you are in caps-lock mode? Windows system is designed so that you can access all characters in caps-lock mode

@LeakyNun In Caps-Lock mode, SHIFT could be used to access the special characters of other keys, such as the / key to get ? from it, or the , key to get the < from it.

But I don't want to turn this into some pointless argument, so let's just agree to disagree.

Now this works perfectly. +1

123: http://retina.tryitonline.net/#code=JShgPFNIRlQ-CsKnCjxTUEM-CiAKPFRBQj4KCQo8Q0FQUz4KwrYKPFJFVD4Kw74KPERFTD4Kw7cKVGBMYGxgKF58wrYpLirCtj8KVGA9OydbXVxcLC0vd2ArOiJ7fXw8XF8-P18pIUAjJCVeJioobExgwqcuCsKnfMK2CgpTYMO-CnNgLj_Dtwo&input= (including the inputs made the link too long for a comment)

Actually, here's 110: http://retina.tryitonline.net/#code=JShHYApUYEZDQlBUXExgwqcgCcK2w77Dt2A8Li4uCjwuXEQoXEQpLj8-CiQxClRgTGBsYChefMK2KS4qwrY_ClRgPTsnW11cXCwtL3dgKzoie318PFxfPj9fKSFAIyQlXiYqKGxMYMKnLgrCp3zCtgoKU2DDvgpzYC4_w7cK&input=

@MartinEnder Thanks for the commented answer! :) However, this does not produce the correct output for test case # 12 (input RE), which should be an empty string.

@R.Kap Actually, the current solution doesn't correctly handle that either, but here's a 2-byte fix for the 110-byte solution: http://retina.tryitonline.net/#code=JShHYApUYEZDQlBUXExgwqcgCcK2w77Dt2A8Li4uCjwuXEQoXEQpLj8-CiQxClRgTGBsYChefMK2KS4qwrY_ClRgPTsnW11cXCwtL3dgKzoie318PFxfPj9fKSFAIyQlXiYqKGxMYMKnLgrCp3zCtgoKU2DDvgorMXNgLj_Dtwo&input=

@MartinEnder Nice! Good Job! :) Can you make that an actual answer? It seems to be the only program here that produces the correct output for all test cases.

@LeakyNun Your answer does not seem to produce the correct output for test case 12 (input RE).

Another 112-byte solution, which I think is a bit neater: http://retina.tryitonline.net/#code=JShHYApUMDN-YExgYDxcdys-ClRgRkNCUFRcTHBgwqcgCcK2w77Dt19gPC4-ClRgTGBsYChefMK2KS4qwrY_ClRgPTsnW11cXCwtL3dgKzoie318PFxfPj9fKSFAIyQlXiYqKGxMYMKnLgrCp3zCtgoKU2DDvgorMXNgLj_Dtwo&input= ... @R.Kap, if Leaky Nun wants to, they can use it to edit their own answer, since it's heavily based on theirs.

@MartinEnder All right, cool.

Aaaand, two 110 byte solutions: http://retina.tryitonline.net/#code=JShHYApUMDR-YHBgYDxcdysKVGBGQ0JQVFxMPmDCpyAJwrbDvsO3X2AuPgpUYExgbGAoXnzCtikuKsK2PwpUYD07J1tdXFwsLS93YCs6Int9fDxcXz4_XykhQCMkJV4mKihsTGDCpy4Kwqd8wrYKClNgw74KKzFzYC4_w7cK&input=, http://retina.tryitonline.net/#code=JShHYAo8Li4oLilcdz8KJDEKVGBGQ0JQVFxMPmDCpyAJwrbDvsO3X2AuPgpUYExgbGAoXnzCtikuKsK2PwpUYD07J1tdXFwsLS93YCs6Int9fDxcXz4_XykhQCMkJV4mKihsTGDCpy4Kwqd8wrYKClNgw74KKzFzYC4_w7cK&input= ... I think I'm done for now. ;)

source: Stack Exchange

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

sort: votes


text:
Make an integer adder with the C preprocessor
The C preprocessor is not turing-complete, but you can do some pretty cool stuff with it.
The challenge is to make an integer adder with it. You can use any representation you like: base 2, base 10, unary, separate each digit with a comma, etc. Whatever you do, you may only use the C preprocessor.
The rules are simple:

You can only use the C preprocessor.
You must support both positive and negative integers.
You can use any integer representation you like, both for input and output. You must clearly state what representation(s) you're using. The input representation doesn't have to match the output representation.
CRLF counts as 2 bytes, LF counts as 1. Convert your files to LF line endings.
You must actually calculate the values, that is, they should neither be hardcoded nor output as a+b. This is a C preprocessor challenge, not a C challenge.
You must have an ADD macro that takes two numbers and outputs one. The numbers must be comma-separated. (for example ADD(a1,a2,a3,...,a32,b1,b2,b3,...,b32) for 32-bit fixed-width binary input.)

Possible inputs and their outputs, in decimal:

133, 57 (= 190)
123, 321 (= 444)
111, 289 (= 400)
9, 9 (= 18)
18, 18 (= 36)
9, -9 (= 0)
-9, -9 (= -18)
0, 9 (= 9)
-9, 0 (= -9)
399, -400 (= -1)

Was is the MAX_INT and MIN_INT we have to support?

@Mego That challenge is not a good dupe target since it's very restrictive in input format.

@DrGreenEggsandIronMan The input format is actually very relaxed from its original incarnation. It's still a bit stricter than usual for challenges, but not by much. This is a dupe because it's the exact same challenge, but with a very tight language restriction. Answers here could be posted in that challenge and be competitive.

@PatrickRoberts The C preprocessor can't do a+b.

@Mego This one is about creating an integer adder with the C preprocessor. That one is just about summing two integers.

I'd say that this isn't a dupe. The C pre-processor is harder to program in than BF!

@wizzwizz4 That doesn't matter. Addition is addition. We don't need integer adder in C preprocessor, integer adder in Malbolge, integer adder in Seed, etc. as different challenges.

@Dennis That challenge isn't about implementing your own integer adder in a language without an integer adder.

Sure it is. Just solve it in a language without an addition built-in.

No, I mean this is more specific.

The C pre-processor is hard to program in because it isn't a programming language. It is a tool that people use to aid them in their C compiling, but it definitely isn't a programming language; it's not even Turing complete! sigh But I suppose we could just put C pre-processor answers on that question...

This is not a dupe. The C preprpoceessor is really a language based on our definition it can do primality checking. @wizzwizz4 making it work for multiple integers also does seem to be a fair challenge, but its no tup to me to deem this a dupe or not

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


text:
Distinct Sieves
Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values.
The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list.
In my examples below, I define 1 to be truthy and 0 to be falsy.
[5, 4, 7, 1]  Input
[1, 1, 1, 1]  Output
              Select only the values with with true indicies in the sieve
[5  4  7  1]  Contains zero duplicate values

[5, 9, 7, 5, 6, 0, 5]
[0, 1, 1, 1, 1, 1, 0]
[   9, 7, 5, 6, 0   ]

Test Cases
When there is an or, it means that there are multiple valid outputs. If there is a trailing ellipsis ... after the or, it means that not all of the possible outputs were listed.
[0] = [1]

[55] = [1]

[32, 44] = [1, 1]

[0, 0] = [1, 0] or [0, 1]

[9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1]

[5, 4, 7, 1] = [1, 1, 1, 1]

[1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or
                     [1, 1, 0, 1, 1, 1]

[5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or
                        [0, 1, 1, 1, 1, 1, 0] or
                        [0, 1, 1, 0, 1, 1, 1]

[0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or
                           [1, 0, 0, 1, 1, 1, 1, 1] or
                           [1, 0, 1, 0, 1, 1, 1, 1] or
                           [1, 1, 0, 1, 1, 0, 1, 1]

[45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88]
= [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ...

[154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790]
= [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ...

Rules

This is code-golf so the shortest solution wins.
Builtins are allowed!
You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions.
The input will be a non-empty list of non-negative integers.
You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted.

For [0, 8, 6, 6, 3, 8, 7, 2], should [1, 0, 0, 1, 1, 1, 1, 1] be added to the list of valid outputs?

Does your own definitions of truthy and falsy values refer to the language or can we choose freely? Do they have to be consistent?

@atlasologist Thanks for catching the typo

@Dennis You are free to define your own boolean values, they do not have to be the same as the language you choose, but you have to be consistent with your own definitions. Instead of 1 and 0 for true and false in my examples, I could have done negative values as false and non-negative (zero or positive) values as true.

OK, thanks for clarifying. By consistent, I meant if there has to be a single truthy value or if there can be several.

MATL, 7 6 4 bytes
1 byte saved thanks to @Luis
2 bytes saved thanks to @Dennis
&=Rs

We define 1 to be truthy and all other values as falsey
Try it Online
All test cases
Explanation
    % Implicitly grab input array
&=  % 2D array of equality comparisons
R   % Get the upper triangular portion
s   % Sum down the columns
    % Implicitly display the result

1 byte fewer: &=Rs1=

@LuisMendo Ha I was literally just playing with that approach!

The OP has clarified what truthy and falsy mean in this challenge. If you define 1 as truthy and everything else as falsy, you can drop the l=.

Great use. The intent was to avoid having to add a filtering step and now you've matched Dennis' Jelly solution.

Jelly, 4 bytes
ĠṪ€Ṭ

Favors last occurrences. Try it online! or verify all test cases.
How it works
ĠṪ€Ṭ  Main link. Argument: A (array)

Ġ     Group; paritition the indices of A according to their corresponding values.
 Ṫ€   Tail each; select the last index of each group.
   Ṭ  Untruth; generate a Boolean array with 1's at the specified indices.

Would this not chop off the zeroes at the end?

There can't be a zero at the end, because we select the last occurrence of each unique integer.

That's clever .

Python 3, 47 35 39 36 bytes
lambda n:[n.pop(0)in n for x in n*1]

Pops the first item from the list, checks if it exists elsewhere in the list, and inserts True or False into a new list.
For this function, False indicates a distinct value, and True is otherwise (True=0 and False=1)
Thanks to Dennis for a ton of bytes
Original, 47 bytes:
lambda n:[(1,0)[n.pop()in n]for x in[1]*len(n)]

Try it

lambda n:[1-(n.pop()in n)for x in n*1] saves a few bytes.

The OP has clarified that the truthy value doesn't actually have to be truthy, so lambda n:[n.pop()in n for x in n*1] works as well.

The new version had me lost for a bit until I realized it used the negated values like xnor did for truthy and falsy.

You need to do .pop(0) or the mask comes out reversed.

That not what xnor meant. .pop() processes the last element first, so the are in reversed order.

@Dennis D'oh! I was trying to flip the boolean, but yeah, I see the whole list is reversed. I just re-read the specs. I'll edit the change in. Thanks!

Yes, the OP said so in this comment.

Pyth, 6 bytes
.eqxQb

Outputs a list of bools (True and False). Checks for each element in the input, if its index is equal to the index of the first occurence of the value. In other words, this is checking if each element is the first occurence.
In pythonic pseudocode:
.e      enumerated_map(lambda b,k:    # maps with b as value and k as index
  q       equal(
   xQb      Q.index(b),
            k),                       # implicit lambda variable
          Q)                          # implicit argument to map

Test it here.

J, 2 bytes
~:

This was where the idea for this challenge originated from. The builtin ~: is called Nub-Sieve in J and creates a boolean list that performs the operation described in the challenge. Here, 1 represents true and 0 represents false.

05AB1E, 8 bytes
Code:
v¹ykN>Qˆ

Explanation:
y         # For each in the array
 ¹yk      # Get the index of that element in the array
    N>Q   # And see if it's equal to the index
       ˆ  # Add to the global array and implicitly output

Uses the CP-1252 encoding. Try it online!.

C#, 63 bytes
int[]l(List<int> i)=>i.Select((m,n)=>i.IndexOf(m)-n).ToArray();

I could also make it return 1 or 0 and therby make the parameter and return type the same one therby allowing me to make this a lambda expression by itself?
some guidance would be appreciated
same type code
    public static List<int>l(List<int>i){
        return i.Select((m,n)=>i.IndexOf(m)==n?1:0).ToList();
    }

if you define truthy to be 0 and falsy to be anything else you can replace the ==n with -n and return a int[]

thats a great idea

also use expression bodied function int[]l(Listi)=>i.Select((m,n)=>i.IndexOf(m)-n).ToArray();

oh my god, thats saving so many bytes in my answers from now on. thank you so much

Can you provide an example on .NetFiddle?

APL, 6 bytes
⍳∘⍴∊⍳⍨

Try it
Explanation:
   ⍳⍨  For each character in the string, get the index of its first occurrence
⍳∘⍴     Make a list 1 .. length of input
  ∊    Check if each index is present

Python, 35 bytes
f=lambda l:l and[l.pop(0)in l]+f(l)

Uses True as the falsy value and False for the truthy value. Marks the last appearance of each element.
Selects the first element only if it doesn't appear among the remaining elements, then recurses to the rest of the list as long as it's non-empty. The l.pop(0) extracts the first element while also removing it.

Retina, 23 bytes
(\d+)((?!.* \1\b))?
$#2

Input is a space-separated list. (Actually, other formats like [1, 2, 3] will also work as long as there's a space in front of each number except the first.)
Try it online! (Works on multiple linefeed-separated test cases at once.)
We simply turn each element into 0 if there's another copy of it later on in the input and into 1 otherwise.

PowerShell v2+, 40 bytes
$a=@();$args[0]|%{(1,0)[$_-in$a];$a+=$_}

Creates an empty array $a. Then we take the input list via $args[0] and pipe that into a loop |%{...}. Each iteration we select either 1 or 0 from a pseudo-ternary based on whether the current element is in $a or not. Those selections are left on the pipeline. We then add the current element into the array $a. The pipeline elements are gathered up, and output as an array is implicit.
Example:
(output here with a newline separator, since that's the default .ToString() for an array)
PS C:\Tools\Scripts\golfing> .\distinct-sieves.ps1 1,2,3,4,1,3,5,7
1
1
1
1
0
0
1
1

JavaScript (ES6), 31 bytes
f=a=>a.map((e,i)=>i-a.indexOf(e))

Zero is truthy and other numbers are falsy.

Mathematica, 53 31 bytes
Thanks to miles for giving me an idea that saved 22 bytes.
s[[;;x++]]~FreeQ~#&/@(x=0;s=#)&

How about using MapIndexed over the previous sublists? MapIndexed[s[[;;#-1&@@#2]]~FreeQ~#&,s=#]& takes 41 bytes.

@miles Ohh, that's much better (and I improved it a bit more ;))

Oo that's a nice way to shorten MapIndexed for this case and you don't even have to extract or decrement the index

Perl 5
push@o,map{$b=pop@a;(grep{/^$b$/}@a)?1:0}(1..~~@a);

.. provides scalar context, so you shouldn't need ~~. 2. grep returns truthy/falsy, so you shouldn't need ?1:0. 3. grep/.../,@a is shorter than grep{/.../}@a. 4. You shouldn't need the final ;. 5. You shouldn't need the parentheses around 1..@a. 6. You don't show where the input is coming from or the output is going to: see http://meta.codegolf.stackexchange.com/q/2447

Java, 96 bytes
void s(int[]a){for(int i=0,j,n=a.length,b=1;i<n;a[i++]=b,b=1)for(j=i+1;j<n;)b=a[i]==a[j++]?0:b;}

Modifies the array in-place. Favours the last occurrence.
The truthy value is 1 while the falsey value is 0.
Verify all testcases.
Ungolfed:
void sieve(int[]a){
    int n = a.length;
    for(int i=0;i<n;i++){
        int b = 1;
        for(int j=i+1;j<n;j++){
            if(a[i] == a[j]){
                b = 0;
            }
        }
        a[i] = b;
    }
}

Actually, 11 bytes
;╗ñ`i@╜í=`M

Try it online!
Explanation:
;╗ñ`i@╜í=`M
;╗           save a copy of input in reg0
  ñ          enumerate
   `i@╜í=`M  for each (index, value) pair:
    i@         flatten, swap
      ╜í       first index in input of value
        =      compare equality

Pyke, 4 bytes
F@oq

Try it here!
     - o = 0 #(Implicit)
F    - for i in input:
 @   -   input.index(i)
   q -  ^==V
  o  -   o+=1

Haskell, 29 27  bytes
f a=[elem x t|x:t<-tails a]

Uses False as true, True as false value:
λ> let f a=[elem x t|x:t<-tails a] in f [5, 9, 7, 5, 6, 0, 5]
[True,False,False,True,False,False,False]

You might have to import Data.List to use tails but,  tryhaskell.org runs the code as is.

No need for the outer parenthesis. \a->[...] is a proper function. If in doubt, give it a name: f a=[...].

@nimi couldn't call it without the parentheses. but giving it name works, thanks a lot.

I don’t like this justification of omitting import Data.List very much. a. is a very slippery slope as you could put any amount of imports (or even definitions!) in your GHCi config. b. treats tryhaskell.org as an authoritative implementation of the Haskell language, but it really isn’t one. (Again, what if I create my own try-Haskell-online environment that comes with all the imports and definitions golfers could ever want? Is that still really “Haskell”?)

I was told here once that if there is any platform that runs the  code as is, then that code is acceptable. I don't know what the exact rules are, I go by what I'm told. I think yes, if your site is available 24/7, and runs standard Haskell, why not. But you're right about the first one, I removed it. Thanks.

PHP, 66 62 39 bytes

accepts all atomic values (boolean, integer, float, string)
except for values evaluating to false (false, 0, "") and numeric strings ("1" equals 1)
flags first occurence

new version (program, 37+2 bytes)
beats Java and (now again) C#. Even almost beats Python now. Happy.
<?foreach($a as$v)$u[$v]=print$u[$v]|0;

+6 for PHP>=5.4, +16-3 for a function
prints undelimited list of 0 (true) and 1 (false)
insert ! after print to invert
usage: set register_globals=On, short_open_tags=On and error_reporting=0 in php.ini for php-cgi
then call php-cgi -f <filename> a[]=<value1> a[]=<value2> ...;echo"";
for PHP>=5.4: replace $a with $_GET[a] (+6), set short_open_tags=On and error_reporting=0
or replace $a with array_slice($argv,1) (+19), remove <?  (-2)
and call php -d error_reporting=0 -r '' <value1> <value2> ...;echo""

old version (function, 62 bytes)
function f($a){foreach($a as$v)$u[$v]=1|$m[]=$u[$v];return$m;}

returns array of false for true and true for false; (ouput as empty string or 1)
insert ! after $m[]= to invert
There is another way for a qualified function with 55 bytes, too.

tests (on old version)
function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function test($x,$e,$y){static $h='

input	output	expected	ok?
';echo"$h
",out($x),'	',out($y),'	',out($e),'	',(strcmp(out($y),out($e))?'N':'Y'),"
";$h='';}
$samples=[
    [0],[1],    [55],[1],    [32,44],[1,1],    [9001,9001,9001],[1,false,false],
    [5,4,7,1],[1,1,1,1],    [1,2,3,4,3,5],[1,1,1,1,false,1],
    [5,9,7,5,6,0,5],[1,1,1,false,1,1,false],    [0,8,6,6,3,8,7,2],[1,1,1,false,1,false,1,1],
    [45,47,47,45,24,24,24,8,47,41,47,88],[1,1,'','',1,'','',1,'',1,'',1],
    [154,993,420,154,154,689,172,417,790,175,790,790,154,172,175,
        175,420,417,154,175,172,175,172,993,689, 993,993,790],
        array_merge([1,1,1,false,false,1,1,1,1,1],array_fill(0,18,false))
];
for($i=count($samples);$i--;--$i)for($j=count($samples[$i]);$j--;)$samples[$i][$j]=!$samples[$i][$j];
while($samples)
{
    $a=array_shift($samples);
    $em=array_shift($samples);
    test($a,$em,$ym=s($a));
    $eu=[];foreach($em as$i=>$f)if($f)$eu[]=$a[$i];
    $yu=[];foreach($ym as$i=>$f)if($f)$yu[]=$a[$i];
#   sort($eu); sort($yu);
    test('unique values',$eu,$yu);
}
echo '
';

C++, 242 bytes

Admittedly an overkill solution, as it works on any standard container of any ordered type:
#include<algorithm>
#include<list>
#include<set>
template<class T>auto f(T a){using V=typename T::value_type;std::set<V>s;std::list<bool>r;std::transform(a.begin(),a.end(),std::back_inserter(r),[&](V m){return s.insert(m).second;});return r;}

Ungolfed:
(and further generalised)
template<class T>
auto f(T a)
{
    using std::begin;
    using std::end;
    using V=typename T::value_type;
    std::set<V>s;
    std::list<bool>r;
    std::transform(begin(a),end(a),std::back_inserter(r),[&](V m){return s.insert(m).second;});
    return r;
}

Test suite:
int test(const std::list<bool>& expected, const auto& x) { return f(x) != expected; }
#include<array>
#include<chrono>
#include<forward_list>
#include<initializer_list>
#include<string>
#include<vector>
using namespace std::literals::chrono_literals;
int main()
{
    return 0
        + test({},            std::vector<short>{})
        + test({1},           std::array<int,1>{})
        + test({1},           std::vector<char>{55})
        + test({true,true},   std::vector<unsigned>{32,44})
        + test({1,0},         std::list<std::string>{"zero", "zero"})
        + test({1,0,0},       std::vector<long>{9001,9001,9001})
        + test({1,1,1,1},     std::array<char,4>{5,4,7,1})
        + test({1,1,1,1,0,1}, std::initializer_list<std::string>{"one","two","three","four","three","five"})
        + test({1,0,1,0,0},   std::forward_list<std::chrono::seconds>{60s, 1min, 3600s, 60min, 1h});
}

TSQL 52 bytes
DECLARE @ TABLE(i int identity, v int)
INSERT @ values(1),(2),(3),(4),(3),(5)

SELECT i/max(i)over(partition by v)FROM @ ORDER BY i

Fiddle

Perl 5 + Perligata, 343 bytes
315 bytes, plus 28 for -MLingua::Romana::Perligata
Use as perl -MLingua::Romana::Perligata foo.pl; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata; I don't know whether it works with Perligata version 0.50.
huic vestibulo perlegementum da.qis _ scindementa da.dum qis fac sic
ao qis decumulamentum da.ao aum tum nullum addementum da.meo io.meo ro.per ium in qis fac sic
si ium tum aum aequalitas fac sic ro I da cis cis
ro nullum tum non rum addementum da.capita bis rum cis
per in bis fac sic hoc tum _ egresso scribe cis

Obviously this is clear as a bell. In case it's not, run it with -MLingua::Romana::Perligata=converte instead of -MLingua::Romana::Perligata, and perl will, instead of running the script, output a translation into regular Perl:
 $_ = Lingua::Romana::Perligata::getline (*STDIN );
 @q = split ( '_');
while (@q) { $a = pop (@q );
 $a =  ($a + 0);
my $i ;
my $r ;
for $i (@q) {if ( ($i eq $a)) { $r = 1}
}
;
 $r =  (0 +  ! ($r));
unshift (@b, $r)}
;
for $_ (@b) {print (STDOUT $_, '_')}

For a token-by-token analysis, use -MLingua::Romana::Perligata=discribe.

Golfing notes:

Undocumented (but unsurprising), you don't need a space after ..
(Also unsurprising,) scinde doesn't need a second argument, and uses hoc.
I had to use ao aum tum nullum addementum da because I couldn't get morde to work.
Similarly, I used per ium in qis... ro I da because I couldn't get vanne to work.
Instead of huic vestibulo perlegementum da, I tried -pMLingua::Romana::Perligata, but couldn't get it to work, either.

Just for kicks (although this whole answer was just for kicks):

After cleaning it up to Huic vestibulo perlegementum da. Qis lacunam scindementa da. Dum qis fac sic ao qis decumulamentum da. Ao aum tum nullum addementum da. Meo io. Meo ro. Per ium in qis fac sic si ium tum aum aequalitas fac sic ro I da cis cis. Ro nullum tum non rum addementum da. Capita bis rum cis. Per in bis fac sic hoc tum lacunam egresso scribe cis., Google Translate gives This court perlegementum grant. QIS gap scindementa grant. While QIS QIS decumulamentum do so ao da. Ao sum and no addementum grant. My io. My ro. Through ium in QIS do so if the sum ium equality do so ro 1 from cis. Ro was not any rum addementum grant. The heads of the bis side. Write, do so as soon as he at that time that in the gap by the Kish was taken..

GolfScript, 19 bytes
..|:i;{i,\i\-:i,-}%

Explanation!
..|:i;{i,\i\-:i,-}% #Distinct sieve
..                  #Duplicate twice. Stack is [A A A]
  |                 #Binary OR. Removes duplicates. Stack is [A (A|A)]
   :i;              #Call this A|A i, and remove it from the stack. [A], i=A|A
      {          }% #Block notation. For each element in the top array, perform this on it.
      {i,        }% #Size of i. Element in array is [E (i,)].
      {  \       }% #Swap the top two elements. [(i,) E]
      {   i\     }% #Put i in the actual second position. [(i,) i E]
      {     -    }% #Remove all instances of the top element from the second. [(i,) (i-E)]
      {      :i  }% #This (i-E) is our new i (for the next loop).
      {        , }% #Size of topmost element (either i, or i,-1 if index was found).
      {         -}% #Subtract. This gives us 1 if E was removed from i, 0 otherwise.

Try it online!

jq, 41 bytes
.[:range(length)+1]|[.[:-1][]!=.[-1]]|all

Try it online!
Takes an array, outputs a stream of jq booleans corresponding to its distinct sieve.
-10 from ovs.

If you use vectorized != and all instead of index and not, you don't need the assignment: .[:range(length)+1]|[.[:-1][]!=.[-1]]|all

great method to remove the variable. Thanks.

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


text:
Implement bag operations
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.
Operations
The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value
[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]
difference removes from a bag each element of another bag, or does nothing if no such element
[1,2,2,4] - [1,2] = [2,4] [1,2,3] - [2,4] = [1,3]
multiplication multiplies each element in the bag.
[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]
division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.
[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]
counting counts how many divisor bags can be produced from the dividend bag
[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2
equality test checks if two bags have the same numbers of each element
[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.
Formats
Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.
The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.
The output format should be a single bag of the same format.
Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)
standard loopholes apply
shortest answer wins

Test cases
[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy

Maybe relax the input format? For example allow to take the bag, bag/number, and operator as separate arguments, or in a free format. Otherwise an important part of the challenge is parsing the input, which is not particularly interesting

@LuisMendo split-on-space is sufficient to parse this, if you have a language that can evaluate strings as lists at all, don't you think? I'm inexperienced at posting challenges, so please enlighten me :-)

I couldn't find a relevant meta post, but see for example the wording here: you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type). Or here: Input and output formats are flexible as usual (arrays, lists, list of lists, strings with reasonable separators, etc).

@LuisMendo it's basically free now. And about the integer, I just meant that in the mathematical sense, not the data type.

Can the symbol used for the operator be chosen freely as part of the input format? For example, can it be a number? I'm not suggesting that it should or that it shouldn't; I just think it's important to know

@LuisMendo nope, the symbols need to make sense, even if only a little. Well, you can use one = for equality test.

"you may not use built-in functions, operations or libraries (including the standard library) that already implement these..." Does this mean that, for instance, in Python, I cannot simply do if bag1==bag2:print('1')?

@R.Kap You can use it if it helps. It's a list comparison, you need to add something to it to make it a bag comparison.

Can we use a different symbol for division and for counting?

You say "the symbols need to make sense", what does this objectively mean?

@LeakyNun I'd like them to be different, after all I don't want that to be an unnecessary difficulty, since for both operations the dividend is the product of the divisor and the quotient (not necessarily so as some bags may be "cut short", but the same goes to integer division), and the division symbol is intended to mean that for A/B=C, C is such that B*C=A, with both operations described by one symbol.

@LeakyNun now that you had me think about it, maybe having different symbols isn't a problem at all, since in logs and exponents the base, index and value are also three different values each expressible in the other two by three different operators.

05AB1E, 92 87 83 82 77 bytes
>i‚˜,}¹iÐ¸˜Qis}GD})˜,}¹<i³v²y¢O}){0è,}¹Íi{s{Q,}¹Í<iÙv²y¢O³‹_iy}}),}svy†¬yQi¦}}

Split by operation
>i                      # if 0
  ‚˜,}                  # addition
¹i                      # if 1
  Ð¸˜Qis}GD})˜,}        # multiplication
¹<i                     # if 2
   ³v²y¢O}){0è,}        # count
¹Íi                     # if 3
   {s{Q,}               # equality
¹Í<i                    # if 4
   Ùv²y¢O³÷Fy}}),}      # division
                        # else
   svy†¬yQi¦}}          # difference

Explanation
Addition
‚˜,}

Put one bag in other and flatten them to one bag.
Multiplication
Ð¸˜Qis}

Make sure the number is on the top of the stack. Call this X.
GD})˜,}

Duplicate the bag X times and join to one bag.
Count
³v²y¢O}){0è,}

For each element in the divisor bag, count number of occurences in dividend bag.
The minimum count will be the number of bags we can make.
Equality
 {s{Q,}

Sort both bags and check if they're equal.
Division
Ùv²y¢O³÷Fy}}),}

Count how many times each unique element occurs in the bag.
If it occurs at least as many times as the divisor. Keep (nr_of_copies_total // divisor) copies in the bag.
Difference
svy†¬yQi¦}}

For each element in the subtrahend, sort it to the front of the minuend.
If the current subtrahend if equal to the first element in the minuend, remove it from the minuend.

APL (155)
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕

This defines an operator ∆ 'bag', which defines bag operations for given functions. I.e. +∆ would be addition. It then reads a line from the keyboard and evaluates it as an APL expression.
The functions are:

+∆, addition
-∆, subtraction
×∆, multiplication
÷∆, division
⊂∆, counting
≡∆, equivalence (though due to golfing any unrecognized function will do equivalence)

Explanation:

∆←{...}: define an operator ∆:

O←⍺⍺: store the given function in O (⎕CR won't work with ⍺⍺ directly)
O←⎕CR'O': get the string representation of that function
'+'=O...:: for addition,

⍺,⍵: join the two lists together
R[⍋R←...]: and sort the result

'-'=O:: for subtraction,

⍺{...}⍵: run the following recursive function:

⍵≡⍬:⍺: if the subtrahend is empty, return the minuend
⍺/⍨(⍳⍴⍺)≢⍺⍳⊃⍵∇1↓⍵: otherwise, remove the first element of the subtrahend from both the subtrahend and the minuend and try again

(⍬=⍴⍵)∧K←'×'=O: for multiplication, and if the right argument is not a bag:

⍵/⍺: replicate each element in the left argument by the right argument

K:: ...and if the right argument is a bag:

⍺/⍵: replicate each element in the right argument by the left argument (this is so that multiplication is commutative)

'÷'=O:: for division,

⍵≤⍺∘.+⍺: see which elements in ⍺ occur at least ⍵ times,
⍺/⍨: select those from ⍺,
∪: and remove all duplicates from that list

'⊂'=O:: for counting,

⍵{...}⍺: run the following recursive function:

(∪⍺)≢∪⍵:0: if one list contains elements the other doesn't, the result is 0
1+⍺∇⍵-∆⍺: otherwise, subtract the dividend from the divisor, try again, and increment the result.

⋄: if none of the above, do the equivalence test:

⍺[⍋⍺]≡⍵[⍋⍵]: sort both lists and see if they are equal

⎕: read an expression from the keyboard, evaluate it, and output the result.

Test cases:
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 +∆ 1 2 4
1 1 2 2 2 3 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 4 -∆ 1 2
2 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 -∆ 2 4
1 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 3 4 ×∆ 3
1 1 1 2 2 2 3 3 3 3 3 3 4 4 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      2 ×∆ 1 3
1 1 3 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 ÷∆ 2
1 2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 3 3 ÷∆ 3
3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 2 3 3 3 ⊂∆ 1 2 3
2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      3 2 1 2 ≡∆ 1 2 2 3
1
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 ≡∆ 1 2 2 3
0

Really professional solution and great write-up! +1

Your writeup and explanation is really solid! One thing, though: for division, I believe the spec is worded in a way that [2,2,2,2,2,2]/3 should give [2,2], but yours seems to give [2].

You don't need to code the REPL. If you just define ∆, the user will be dumped into APL's native REPL, where ∆ is now valid. I think you can save some bytes by moving subtraction to the end as it is the only one that requires two lines. Instead of the ⎕CR, use * to symbolize count, and do O←⍺⍺2, then 2=O: for plus, 1=O for mult, 0=O: for equiv, 7<O: for count, and 0<O: for div (with implied 0>O: for subtr).

JavaScript (ES6), 260 bytes
(x,o,y,a=a=>a.reduce((r,e,i)=>[...r,...Array(e).fill(i)],[]),b=(a,r=[])=>a.map(e=>r[e]=-~r[e])&&r)=>[z=>a(b(y,z)),z=>y.map(e=>z[e]&&z[e]--)&&a(z),z=>a(z.map(e=>e*y)),z=>a(z.map(i=>i/y|0)),z=>b(y).map((e,i)=>r=Math.min(r,z[i]/e),r=1/0)|r,z=>``+z==b(y)][o](b(x))

Takes 3 parameters. The first parameter is an array, the second is an operator, the third depends on the operator. Bags are required to hold non-negative integers.
[...] 0 [...] -> addition
[...] 1 [...] -> difference
[...] 2 <n> -> multiplication
[...] 3 <n> -> division
[...] 4 [...] -> counting
[...] 5 [...] -> equality

Ungolfed:
function do_bag_op(lhs, op, rhs) {
    function bag2array(bag) {
        return bag.reduce(function (result, entry, index) {
            return result.concat(Array(entry).fill(index));
        }, []);
    }
    function array2bag(array, bag) {
        if (!bag) bag = [];
        array.forEach(function (entry) {
            if (bag[entry]) bag[entry]++;
            else bag[entry] = 1;
        }
        return bag;
    }
    var bag = array2bag(lhs);
    switch (o) {
    case 0: // addition
        return bag2array(array2bag(rhs, bag));
    case 1: // difference
        rhs.forEach(function(entry) {
            if (bag[entry]) bag[entry]--;
        });
        return bag2array(bag);
    case 2: // multiplication
        return bag2array(bag.map(function (entry) {
            return entry * rhs;
        }));
    case 3: // division
        return bag2array(bag.map(function (entry) {
            return Math.floor(entry / rhs);
        }));
    case 4: // counting
        return Math.floor(array2bag(rhs).reduce(function (count, entry, index) {
            return Math.min(count, bag[index] / entry);
        }, Infinity));
    case 5: // equality
        return String(bag) == String(array2bag(rhs));
    }
}

Can u make bad input not crash and remove some z=>?

@l4m2 I'm not sure what you're asking, but that might be because it's late and I've had a long day...

Octave, 253 244 226 bytes
function r=f(a,b,o)
u=union(a,b);p=hist(a,u);q=hist(b,u);m=d=0;if(numel(b)==1)m=p.*b;d=p/b;elseif(numel(a)==1)m=a.*q;end
r={p+q,p-q,m,d,min(fix(p./q)),isequal(p,q)}{o};if(o<5)r=[arrayfun(@(x,y)repmat(y,1,x),r,u,'un',0){:}];end

This function must be in a file. To write the function in the command window you must use endfunction or end.
Thanks to Luis Mendo for saving 18 bytes.
The operations are:
1 = addition
2 = difference
3 = multiplication
4 = division
5 = counting
6 = equality test

Usage example:
>> f([1,2,2,3], [1,2,4], 1)
ans = 1   1   2   2   2   3   4

>> f([1,2,2,4], [1,2], 2)
ans = 2   4

>> f([1,2,3], [2,4], 2)
ans = 1   3

>> f([1,2,3,3,4], 3, 3)
ans = 1   1   1   2   2   2   3   3   3   3   3   3   4   4   4

>> f(2, [1,3], 3)
ans = 1   1   3   3

>> f([1,1,2,2,2], 2, 4)
ans = 1   2

>> f([1,2,2,3,3,3], 3, 4)
ans =  3

>> f([1,1,2,2,2,2,3,3,3], [1,2,3], 5)
ans =  2

>> f([3,2,1,2], [1,2,2,3], 6)
ans =  1

>> f([1,2,3], [1,2,2,3], 6)
ans = 0

Ungolfed:
function r = f(a,b,o)
    u = union(a,b);
    p = hist(a,u);
    q = hist(b,u);
    m = d = 0;
    if (numel(b)==1)
        m = p.*b;
        d = p/b;
    elseif (numel(a)==1)
        m = a.*q;
    end
    r = {p+q, p-q, m, d, min(fix(p./q)), isequal(p,q)}{o};
    if (o<5)
        r = [arrayfun(@(x,y) repmat(y, 1, x), r, u, 'un', 0){:}];
    end
end

Mathematica, 387 347 300 284 bytes
k=KeyValueMap[Table,#]&;j=b@@Join@@#&;l=List;q=Counts
b~SetAttributes~Orderless
a_b+c_b^:=j@{a,c}
c_b-a_b^:=j@k@Merge[q/@(l@@@{a+c,2a}),-Min[0,+##2-#]&@@#&]
a_b*n_Integer/;n>0^:=a+a*(n-1)
a_Rational c_b^:=j@k[⌊a#⌋&/@q@*l@@c]
a_b==d_b^:=l@@a==l@@d
c_b/a_b^:=If[(c-a)+a==c,1+(c-a)/a,0]

Slightly degolfed (a.k.a old version), didn't have full support for equality tests (returned truthy values, but left unevaluated for non-matching bags).
SetAttributes[b,Orderless]
b/:-a_b:=d@@a
b/:a_b+c_b:=Join[a,c]
d/:a_b+c_d:=b@@Join@@KeyValueMap[Table,Merge[Counts/@(List@@@{a+b@@c,b@@c+b@@c}),Max[0,#-(+##2)]&@@#&]]
b/:Rational[1,a_]c_b:=b@@Join@@KeyValueMap[Table,Floor[#/a]&/@Counts@*List@@c]
b/:(a_b)^-1:=c@@a
c/:a_b d_c:=Min@Merge[Counts/@(List@@@{a,d}),If[+##2==0,\[Infinity],#/+##2]&@@#&]
b/:a_b*n_Integer:=a+a*(n-1)

Implements the required data type with head b.
First b is defined to be Orderless. Any object passed to the kernel with head b will autosort its arguments. So even if b[3,2,1] is typed in, the evaluator will never see anything other than b[1,2,3].
Addition is trivially defined as joining the elements.
A special rule for the difference of two bags is defined (explained below). Previous version had an auxiliary symbol for expressions of form -bag.
Then multiplication (as long as n is a positive integer) is recursively defined as n*b[...] = b[...] + (n-1)*b[...] which will eventually reduce to a simple sum.
The special rule for b[...] - b[...] counts the number of distinct elements in the sum of the bags and subtracts the bag to be subtracted twice from that result. Easier explained:
b[1,2,3,4,5] - b[2,3,6]
Element counts in sum of bags: <|1->1, 2->2, 3->2, 4->1, 5->1, 6->1|>
Element counts in 2x second bag:     <|2->2, 3->2, 6->2|>
Subtracting the corresponding values:
                               <|1->1, 2->0, 3->0, 4->1, 5->1, 6->-1|>

Above is a list of Keys->Values. KeyValueMap with Table creates lists of each Key Value times. (there's also a Max[...,0] there to not attempt creation of negative length tables). This comes out as:
{{1},{},{},{4},{5},{}}

which is flattened and head List is replaced with b.
Division by integers is somewhat similar in functions used, it is simply the floored division of the element counts by the integer.
Division by sets or counting I've changed since the original implementation. It is now recursively done as follows. Say, we divide bag b1 by b2 (which in the golfed code are c and a respectively. If (b1-b2) + b2 == b1, then add 1 and add to that the result of dividing (b1-b2)/b2. If not, return 0 and exit the recursion.
If bags match, built-in == gives True. The last line forces a False if they don't.
Test cases:
Input:
b[1, 2, 2, 3] + b[1, 2, 4]
b[1, 2, 2, 4] - b[1, 2]
b[1, 2, 3] - b[2, 4]
b[1, 2, 3, 3, 4]*3
2*b[1, 3]
b[1, 1, 2, 2, 2]/2
b[1, 2, 2, 3, 3, 3]/3
b[1, 1, 2, 2, 2, 2, 3, 3, 3] /b[1, 2, 3]
b[3, 2, 1, 2] == b[1, 2, 2, 3]
b[1, 2, 3] == b[1, 2, 2, 3]

Output:
b[1, 1, 2, 2, 2, 3, 4]
b[2, 4]
b[1, 3]
b[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4]
b[1, 1, 3, 3]
b[1, 2]
b[3]
2
True
False

Ruby, class definition answer, 323 291 bytes
Mostly just wanted to make the Bag an actual class because of Ruby's flexibility with classes. In this case, it inherits from Array because it's shorter than having to initialize an internal array and dealing with the other stuff.
I'll probably do a more-serious golfing answer that uses a function to deal with the operations tomorrow. I'm very tired and I had too much fun with this even though I had to wrangle with the numerics class definition to get Number * Bag working properly PRAISE THE COERCE FUNCTION FOR MAKING IT SO I DIDN'T NEED TO MESS UP THE NUMERICS CLASS DEFINITIONS
Try it online! (Whitespace doesn't matter in Ruby, so the code is slightly ungolfed there.)
class B<Array
def == o
sort==o.sort
end
def + o
B.new super
end
def - o
r=to_a
o.map{|i|r[r.index(i)||size]=p}
B.new r-[p]
end
def * i
B.new super
end
def / i
B.new uniq.map{|o|[o]*(count(o)/i)}.flatten
end
def c o
o.map{|i|count i}.min
end
def inspect
sort
end
def coerce o
[self,o]
end
end

Q - 219 characters
a:(,)
s:{[x;y]x((!:)(#:)x)except(,/)({.[(#);x]}')flip(7h$(({(+/)x=y}[y]')(?:)y);(({where x=y}[x]')y))}
m:{(,/)$[0>(@:)x;(#[x]')y;(#[y]')x]}
d:{(?:)x(&:)({y<=(+/)x=z}[x;y]')x}
c:{min({(+/)x=y}[x]')y}
e:{(asc x)~asc y}

a for addition, s for difference (subtraction), m for multiplication, d for division, c for counting, e for equality.
The addition algorithm is the obvious one, just joining the bags.
The subtraction function indexes in input bag (represented as an array) with the entire index range, except for the first n indices of each equivalence class formed by equality to each element in y, where n is the number of copies of that representative in y. Handling possible duplicates in y makes this a real monster of a function.
The multiplication function takes x values from each y, in the case that y is a single value, instead of an array, it just replicates them.
The division function produces the values whose count in the array is greater than y, and then removes duplicates.
The counting function calculates the counts of each element in y, and then returns the minimum.
Two bags are equal if their sorted array representations are equal.

Ruby, 201 bytes
As promised in my other answer, here's one that uses functions instead of building a new class. I'm so close to breaching the 200 byte mark... Try it online
This uses the same opcodes as @Neil in his JavaScript answer, and the same order of arguments (lhs, opcode, rhs)
0: Addition
1: Difference
2: Multiplication
3: Division
4: Counting
5: Equality

The code:
->x,o,y{[->{(x+y).sort},->r=[*x]{y.map{|i|r[r.index(i)||x.size]=p};r-[p]},->{(x==[*x]?x*y :y*x).sort},->{x.uniq.map{|i|[i]*(x.count(i)/y)}.flatten},->{y.map{|i|x.count i}.min},->{x.sort==y.sort}][o][]}

Python 2.7 - 447B (filesize)
This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)
Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:

pythons self argument in a class can be replaced by anything
indentation only has to be a single space
the builtin sorted - funktion (I knew I had seen it, but I thought it to be a method in lists)
__ radd __ is not needed (I only support adding B-objects(Bag-type) anyways)

Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.
Code:
class B:
 def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])

checks:
print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add

print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3])   - B([2,4]) == B([1,3]) #Substract

print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3])                            #

print B([1,1,2,2,2])   /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3])   #

print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times

print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3])   == B([1,2,2,3]) # Unequal

Output:
True
True
True
True
True
True
True
True
True
False

I might try it an other time with set as basis some time.
Edit: Maybe I'll even try with functions only.

Welcome to PPCG! A thing to note about Python is you don't actually need to call the first parameters in class functions self -- something like S would do just as well. Another trick is that the built-in sorted function does exactly what you want out of your new function s, so you can forgo the function definition (seeing as you only use it once). You don't ever need __radd__ because you never add non-bags with bags, although you still need __rmul__. Finally, you only need one space of indent instead of four, which trims down your byte count by quite a bit

C++, 555 551 bytes
(line breaks added for readability - only the first newline is required and counted)
#include<map>
struct B:std::map<int,int>{
B(std::initializer_list<int>l){for(auto i:l)++(*this)[i];}};
B operator+(B a,B b){for(auto m:b)a[m.first]+=m.second;return a;}
B operator-(B a,B b){for(auto m:b){int&x=a[m.first];x-=x>m.second?m.second:x;if(!x)a.erase(m.first);};return a;}
B operator*(B b,int n){for(auto m:b)b[m.first]*=n;return b;}
B operator*(int n,B b){return b*n;}
B operator/(B b,int n){for(auto m:b)if(!(b[m.first]/=n))b.erase(m.first);return b;}
int operator/(B a,B b){auto r=~0u;for(auto m:b){int x=a[m.first]/m.second;r=r>x?x:r;}return r;}

Explanation
We implement our bag as a map of (value, count).  The basic operations can be implemented by manipulating the counts; subtraction and integer division also need to remove any elements whose count reaches zero, so that std::map::operator== will work as the equality test.
The following expanded code is a generic version of the above, much less golfed: we use a separate s() to squeeze out any zero-count values, and we implement const operations in terms of assignment operators in the idiomatic C++ way.  We also use s() to make multiplication by 0 return a truly empty bag (tested by adding (B{1}*0 != B{}) to main()); the original fails this test, and it's not clear whether it's a requirement.
template<class T>
struct Bag{
    std::map<T,int>b;
    Bag(const std::initializer_list<T>& l){for(auto i:l)++b[i];}
    Bag&s(){for(auto i=b.begin();i!=b.end();i=i->second?++i:b.erase(i));return*this;}
    Bag&operator+=(const Bag& o){for(auto m:o.b)b[m.first]+=m.second;return*this;}
    Bag&operator-=(const Bag& o){for(auto m:o.b){auto&x=b[m.first];x-=x>m.second?m.second:x;}return s();}
    Bag&operator*=(int n){for(auto m:b)b[m.first]*=n;return s();}
    Bag&operator/=(int n){for(auto m:b)b[m.first]/=n;return s();}
    auto operator/=(const Bag& o){auto r=~0u;for(auto m:o.b){int x=b[m.first]/m.second;r=r>x?x:r;}return r;}
    bool operator==(const Bag& o)const{return b==o.b;}

    Bag operator+(Bag o)const{return o+=*this;}
    Bag operator-(const Bag& o)const{Bag t=*this;return t-=o;}
    Bag operator*(int n)const{Bag t=*this;return t*=n;}
    friend Bag operator*(int n,const Bag& b){return b*n;}
    auto operator/(auto n)const{Bag t=*this;return t/=n;}
    bool operator!=(const Bag& o)const{return b!=o.b;}
};

using B = Bag<int>;

Tests
bool operator!=(B a,B b){return!(a==b);}
int main()
{
    return 0
        + (B{1,2,2,3}+B{1,2,4}  !=  B{1,1,2,2,2,3,4})
        + (B{1,2,2,4}-B{1,2}  !=  B{2,4})
        + (B{1,2,3}-B{2,4}  !=  B{1,3})
        + (B{1,2,3,3,4}*3  !=  B{1,1,1,2,2,2,3,3,3,3,3,3,4,4,4})
        + (2*B{1,3}  !=  B{1,1,3,3})
        + (B{1,1,2,2,2}/2  !=  B{1,2})
        + (B{1,2,2,3,3,3}/3  !=  B{3})
        + (B{1,1,2,2,2,2,3,3,3}/B{1,2,3} != 2)
        + (B{3,2,1,2}  !=  B{1,2,2,3})
        + (B{1,2,3}  ==  B{1,2,2,3})
        ;
}

Nice answer! +1. Your code needs proper formatting in the post.

I deliberately wanted the code to wrap, so you can see it all.  The alternative was to add line breaks.

Line breaks added - I think this is better, because prettify now works.

Go, 642 bytes
type B struct{C map[int]int}
func N(c...int)B{b:=B{make(map[int]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B)L()(o[]int){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B)A(O B)B{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B)S(O B)B{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B)M(n int)B{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B)D(n int)B{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B)O(O B)int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B)E(O B)bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}

Attempt This Online!
Methods ASMDOE are the methods described in-order in the OP. N is the constructor, taking a list of ints, and L is a utility function that turns a bag into a list of ints.
Go, generic, 712 bytes
type B[T comparable]struct{C map[T]int}
func N[T comparable](c...T)B[T]{b:=B[T]{make(map[T]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B[T])L()(o[]T){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B[T])A(O B[T])B[T]{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B[T])S(O B[T])B[T]{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B[T])M(n int)B[T]{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B[T])D(n int)B[T]{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B[T])O(O B[T])int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B[T])E(O B[T])bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}

Attempt This Online!


text:
Meta Obfuscate a String
There are numerous reasons for trying to obfuscate input. These include preventing decompiling, and being a nuiscance.

With this in mind your challenge should your choose to accept it is to write a meta-obfuscator. Your code must in some Language X receive input as a String, and output a program in language X that outputs the input String.

Rules

Standard loopholes disallowed
It should be hard to tell whether the output prints anything (I.E the code should be heavily obfuscated)
Your program should be testable
Cryptographic approaches are permitted, but it should not be obvious.
Try to submit an interesting solution as this is a popularity contest

Winning Criterion

Although it is up to you to decide which question deserves your upvote. Here are the guidelines.

Hardest to reverse engineer output based on the source code (i.e most encrypted/obfuscated)
Effort and quality of answer

tl;dr
Output a program which prints the input, but make it hard to understand what is going on. Although many people have discussed this (especially for javascript) and even python. I have seen no formal repository of such programs in any arbitrary languages.

This conversation has been moved to chat.

This looks like it's trying to be an underhanded challenge without explicitly being an underhanded challenge. An underhanded underhanded challenge perhaps, which makes it doubly off-topic.

Java
Just out of curiosity I decided to write a simple block of code that outputs code that does not look obfuscated.
Here is the generator code
package metaobfuscate;

import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author rohan
 */
public class MetaObfuscate {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String s = (new Scanner(System.in)).nextLine().toLowerCase();
        int i = 0;
        int numChar = s.length();

        String randomlyGenerated;
        String alphabet = " abcdefghijklmnopqrstuvwxyz!?.";
        do {
            Random rand = new Random(i);
            randomlyGenerated = "";
            i++;
            for (int j = 0; j < numChar; j++) {
                randomlyGenerated += alphabet.charAt((int) (rand.nextDouble() * alphabet.length()));
            }
        } while (!s.equals(randomlyGenerated));
        i--;
        System.out.println("import java.util.Random;\n//Simple demonstration of generating random characters");
        System.out.println("public class RandomNessTest {");
        System.out.println("\t//args are the command line arguments");
        System.out.println("\tpublic static void main(String[] args){");
        System.out.println("\tRandom rand = new Random(" + i + ");//replace the seed with whatever seed you want");
        System.out.println("\t//the seed was generated by random keyboard mashing");
        System.out.println("\tString alphabet = \" abcdefghijklmnopqrstuvwxyz!?.\";");
        System.out.println("\tfor(int i = 0;i<" + numChar + ";i++)");
        System.out.println("\t\tSystem.out.print(alphabet.charAt((int)(rand.nextDouble()*alphabet.length())));");
        System.out.println("\t//print out a few random characters");
        System.out.println("\t}\n}");
    }

}

It takes in whatever string you wish to obfuscate and outputs a program that looks reliable as output. It takes exponential runtime with larger strings, but it works great for strings of length 1-5. The outputted program claims to be a tutorial, and is even formatted nicely!
import java.util.Random;
//Simple demonstration of generating random characters
public class RandomNessTest {
    //args are the command line arguments
    public static void main(String[] args){
    Random rand = new Random(2727915);//replace the seed with whatever seed you want
    //the seed was generated by random keyboard mashing
    String alphabet = " abcdefghijklmnopqrstuvwxyz!?.";
    for(int i = 0;i<5;i++)
        System.out.print(alphabet.charAt((int)(rand.nextDouble()*alphabet.length())));
    //print out a few random characters
    }
}


text:
Print the "even" permutations of symmetric group Sn in cyclic notation
THE TASK
DEFINITIONS
Consider the points {1,2,3,4,5} and all their permutations. We can find the total number of possible permutations of these 5 points by a simple trick: Imaging filling 5 slots with these points, the first slot will have 5 possible numbers, the second 4 (as one has been used to fill the first slot) the third 3 and so on. Thus the total number of Permutations is 5*4*3*2*1; this would be 5! permutations or 120 permutations. We can think of this as the symmetric group S5, and then Symmetric Group Sn would have n! or (n*n-1*n-2...*1) permutations.
An "even" permutation is one where there is an even number of even length cycles. It is easiest to understand when written in cyclic notation, for example (1 2 3)(4 5) permutes 1->2->3->1 and 4->5->4 and has one 3 length cycle (1 2 3) and one 2 length cycle (4 5). When classifying a permutation as odd or even we ignore odd length cycles and say that this permutation [(1 2 3)(4 5)] is odd as it has an odd number {1} of even length cycles.
Even examples:

(1)(2 3)(4 5) = two 2 length cycle | EVEN |
(1 2 3 4 5) = no even length cycles | EVEN | * note that if no even length cycles are present then the permutation is even.

Odd Examples:

(1 2)(3 4 5) = one 2 length cycle | ODD |
(1)(2 3 4 5) = one 4 length cycle | ODD |

As exactly half of the permutations in any Symmetric Group are even we can call the even group the Alternating Group N, So as S5 = 120 A5 = 60 permutations.
NOTATION
Permutations should, for this at least, be written in cyclic notation where each cycle is in different parenthesis and each cycle goes in ascending order. For example (1 2 3 4 5) not (3 4 5 1 2). And for cycles with a single number, such as: (1)(2 3 4)(5) the single / fixed points can be excluded meaning (1)(2 3 4)(5) = (2 3 4). But the identity {the point where all points are fixed (1)(2)(3)(4)(5)} should be written as () just to represent it.
THE CHALLENGE
I would like you to, in as little code possible, take any positive integer as an input {1,2,3,4...} and display all the permutations of the Alternating Group An where n is the input / all the even permutations of Sn. For example:
Input = 3
()
(1 2 3)
(1 3 2)

and
Input = 4
()
(1 2)(3 4)
(1 3)(2 4)
(1 4)(2 3)
(1 2 3)
(1 3 2)
(1 2 4)
(1 4 2)
(1 3 4)
(1 4 3)
(2 3 4)
(2 4 3)

And as with in the examples I would like for all cycles of one length to be elided, and as for the identity: outputs of  nothing, () {not only brackets but with whatever you are using to show different permutations} or id are acceptable.
EXTRA READING
You can find more information here:

https://en.wikipedia.org/wiki/Permutation
https://en.wikipedia.org/wiki/Alternating_group

GOOD LUCK
And as this is codegolf whoever can print the Alternating Group An's permutations in the shortest bytes wins.

Welcome to Programming Puzzles and Code Golf! Normally, we allow the output to be flexible, so that languages which have problems with outputting in the right format don't have an unfair disadvantage. Is it allowed to output for example [[1, 2], [3, 4]] instead of (1 2)(3 4)?

@Adnan Yes, I should've clarified. As long as the different cycles are shown separately there should be no problem with how you have represented this.

"An "even" permutation is one where there is an even number of even permutations." This looks like a cyclic definition. Maybe introduce cycle notation first and then rewrite that sentence to "... even number of even-length cycles"?

Also, how do I put the cycle (2 3 1 4) in ascending order? Do you mean we should just put the smallest element at the front?

@MartinEnder Yes the smallest element should go first as long as it doesn't mess with the order, so as (2 3 1 4) does 2->3->1->4->2 it can be written (1 4 2 3) with its smallest element first

One more thing. I'm assuming you've already accepted an answer because you're planning to update it when a shorter one comes in. That's how it would work ideally, but some people will assume the contest is already over when they see the checkmark, which means you might get fewer answers than you would otherwise. That's why most people usually wait at least a week before accepting an answer. Nice first challenge by the way! :)

For the identity permutation can we also output an empty list of cycles as opposed to an empty cycles? Otherwise, that seems like an odd special case.

@MartinEnder Thanks, and yeah it's just I always write id for the identity which i assumed would be harder but if you mean print it like miles (J, 53 Bytes) did {nothing} then yeah that would be acceptable

When you say that “fixed points can be excluded”, is this a requirement or an option? May we write (1)(2 3 4)(5), or must we write (2 3 4)?

Pyth, 26 bytes
t#Mf%+QlT2mcdf<>dTS<dTd.pS

          m            .pSQ   Map over permutations d of [1, …, Q]:
             f        d         Find all indices T in [1, …, Q] such that
               >dT                the last Q-T elements of d
              <   S<dT            is less than the sorted first T elements of d
           cd                   Chop d at those indices
   f                          Filter on results T such that
      Q                         the input number Q
     + lT                       plus the length of T
    %    2                      modulo 2
                                is truthy (1)
t#M                           In each result, remove 0- and 1-cycles.

Try it online
This solution is based on a neat bijection between permutations in one-line notation and permutations in cycle notation. Of course, there’s the obvious bijection where the two notations represent the same permutation:
[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] = (1 8 9 2 4 3 6)(5 10 7)
but that would take too much code.  Instead, simply chop the one-line notation into pieces before all numbers that are smaller than all their predecessors, call these pieces cycles, and build a new permutation out of them.
[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] ↦ (8)(4 6)(3 10)(1 5 9 2 7)
To reverse this bijection, we can take any permutation in cycle form, rotate each cycle so its smallest number is first, sort the cycles so that their smallest numbers appear in decreasing order, and erase all the parentheses.

The OP requires the identity permutation to be represented without one-cycles. I do think it'd be better if it weren't the case.

Harry seemed to okay my Jelly answer, which prints 1-cycles even for id. Maybe he could chime in?

I'm not so sure too with the way it's worded, and I didn't notice that your (Lynn's) solution did the same too.

My understanding was that you couldn't represent the identity permutation using the empty string, so I amended my answer to keep all the 1-cycles (also conveniently saving 6 bytes).

I have edited my question to be more clear, I would like the "one cycles" to be elided as you have done in the second part of your answer. Well done by the way.

@Harry Thanks, I have removed the other solution.

Mathematica, 84 49 31 bytes
GroupElements@*AlternatingGroup

Composition of two functions. Outputs in the form {Cycles[{}], Cycles[{{a, b}}], Cycles[{{c, d}, {e, f}}], ...} representing (), (a b), (c d)(e f), ....

J, 53 bytes
[:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]

The cycles in each permutation are represented as boxed arrays since J will zero-pad ragged arrays.
If the output is relaxed, using 41 bytes
[:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]

where each permutation may contain one-cycles and zero-cycles.
Usage
   f =: [:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]
   f 3
┌┬───────┬───────┐
││┌─────┐│┌─────┐│
│││1 2 3│││1 3 2││
││└─────┘│└─────┘│
└┴───────┴───────┘
   f 4
┌┬───────┬───────┬─────────┬───────┬───────┬───────┬───────┬─────────┬───────┬───────┬─────────┐
││┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌───┬───┐│
│││2 3 4│││2 4 3│││1 2│3 4│││1 2 3│││1 2 4│││1 3 2│││1 3 4│││1 3│2 4│││1 4 2│││1 4 3│││2 3│1 4││
││└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└───┴───┘│
└┴───────┴───────┴─────────┴───────┴───────┴───────┴───────┴─────────┴───────┴───────┴─────────┘

For the alternative implemenation,
   f =: [:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]
   f 3
┌─────┬─┬─┐
│1    │2│3│
├─────┼─┼─┤
│1 2 3│ │ │
├─────┼─┼─┤
│1 3 2│ │ │
└─────┴─┴─┘

This is actually beautiful... well done.

Jelly, 34 28 bytes
L€’SḂ
ṙLR$Ṃµ€Ṣ
Œ!ŒṖ€;/Ç€ÑÐḟQ

Try it here.
Explanation
Each line in a Jelly program defines a function; the bottom one is “main”.

The first line defines a function that tests whether a cycle product is odd.
L€      Length of each
  ’     Add 1 to each length
   S    Take the sum
    Ḃ   Modulo 2

The second line normalizes a partition of a permutation of [1…n] into a cycle product as follows:
     µ€    For each list X in the partition:
ṙLR$          Rotate X by each element in [1…length(X)].
    Ṃ         Get the lexicographically smallest element.
              Thus, find the rotation so that the smallest element is in front.
       Ṣ   Sort the cycles in the partition.

This will turn e.g. (4 3)(2 5 1) into (1 2 5)(3 4).

Here is the main program. It takes an argument n from the command line, and:
Œ!              Compute all permutations of [1…n].
  ŒṖ€           Compute all partitions of each permutation.
     ;/         Put them in one big list.
       Ç€       Normalize each of them into a cycle product.
         ÑÐḟ    Reject elements satisfying the top function,
                i.e. keep only even cycle products.
            Q   Remove duplicates.

I tried running it with 5 as an input, and got no output at all. Is this  script for just Groups A3 and A4 or can it potentially give any group? I have never even seen Jelly before so any explanation would be helpful.

No I only put 3 and 4 in the challange so, so far you are winning but I really just want to learn more.

Jelly actually has a built-in for partitions, which I forgot about! Thankfully, a friend reminded me. So now it’s more efficient (handles n=5, yay!) and shorter.

OP has edited the question to clarify that 1-cycles must be elided.

JavaScript (Firefox 30-57), 220 218 212 211 bytes
f=(a,p)=>a[2]?[for(i of a)for(j of f(a.filter(m=>m!=i),p,p^=1))[i,...j]]:[[a[p],a[p^1]]]

Sadly 88 bytes only suffices to generate the alternating group as a list of permutations of a, so it then costs me an additional 132 130 124 123 bytes to convert the output to the desired format:
n=>f([...Array(n).keys()],0).map(a=>a.map((e,i)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&s)

I've managed to trim my ES6 version down to 222 216 215 bytes:
n=>(g=(a,p,t=[])=>a[2]?a.map(e=>g(a.filter(m=>m!=e),p,[...t,e],p^=1)):[...t,a[p],a[p^1]].map((e,i,a)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&r.push(s))([...Array(n).keys(r=[])],0)&&r

I don't mind if the format is not in perfect cyclic notation as long as: each permutation and its cycles are shown separate ( like [1 2 3][4 5] and <<123><45>> would both be acceptable) and cycles of one length are elided. Perhaps this can shorten your answer

@Harry I'd never show (1,2,3)(4,5) - that's an odd permutation! Currently I'd show e.g. (1,2,3)(4)(5) - not only does removing cycles of length one cost me 6 bytes I then end up with an empty result for the identity cycle which would cost me another 4 bytes to fix.

If you mean nothing is printed for the identity then I will accept that as I said
as for the identity outputs of nothing ... are accepatble. And also what would be shown if you output your "raw data", does it come in the form (1,2,3)(4)(5) or as something else?

@Harry Now excluding cycles of length one, including a blank entry for the identity, and still managing to save a byte!

@Harry Raw data would be [1, 2, 0, 3, 4] for that particular example, so nowhere near what you want.

GAP, 32 bytes
Thanks to @ChristianSievers  for cutting the count in half.
f:=n->List(AlternatingGroup(n));

Usage at the prompt:
gap> f(4);
[ (), (1,3,2), (1,2,3), (1,4,3), (2,4,3), (1,3)(2,4), (1,2,4), (1,4)(2,3), (2,3,4), (1,3,4), (1,2)(3,4), (1,4,2) ]

Very nice formatting, I think GAP was a very good choice for answering this problem.

Your answer doesn't show where one permutation ends and the next starts. Assuming the function doesn't need to print the values as a side effect, but may just return the values as a list to be printed by the interpreter, I'd do f:=n->List(AlternatingGroup(n));