text:
XOR multiplication
You goal is to implement the operation of XOR (carryless) multiplication, defined below, in as few bytes as possible.
If we think of bitwise XOR (^) as binary addition without carrying
   101   5
^ 1001   9
  ----
  1100  12

  5^9=12

we can perform XOR multiplication @ by doing binary long-multiplication but doing the adding step without carrying as bitwise XOR ^.
     1110  14
   @ 1101  13
    -----
     1110
       0
   1110
^ 1110
  ------
  1000110  70

  14@13=70

(For mathematicians, this is multiplication in the polynomial ring \$F_2[x]\$, identifying polynomials with natural numbers by evaluating at \$x=2\$ as a polynomial over \$\mathbb Z\$.)
XOR multiplication commutes a@b=b@a, associates (a@b)@c=a@(b@c), and distributes over bitwise XOR a@(b^c)=(a@b)^(a@c). In fact, it is the unique such operation that matches multiplication a@b=a*b whenever a and b are powers of 2 like 1,2,4,8....
Requirements
Take two non-negative integers as input and output or print their XOR-product. This should be as numbers or their decimal string representations, not their binary expansions. Fewest bytes wins.
Don't worry about integer overflows.
Here are some test cases formatted as a b a@b.
0 1 0
1 2 2
9 0 0
6 1 6
3 3 5
2 5 10
7 9 63
13 11 127
5 17 85
14 13 70
19 1 19
63 63 1365

This is better known as "carry-less multiplication", which you might want to add the the question title, and with high probability the smallest entry is the 6-byte x86 instruction PCLMULQDQ from the CLMUL extension. Unfortunately I got downvoted for my knowledge of the x86 instruction set before (Related to PEXT/PDEP), so I'm going to just leave this as a comment here.

@IwillnotexistIdonotexist Thanks for the note, it's nice to have a name to Google.

If that above is not "xor" you have to call in a different way as xorc or xornc ... It is not xor

@RosLuP It's not xor, it's xor multiplication.

@boboquack Actually, I believe nimber multiplication  is different. For instance, it has 2*2==3. Both of these distribute over nim addition, but the one in this challenge matches multiplication on powers of 2, whereas the nimber on matches only on 2^(2^n).

x86 machine code: 7 bytes
66 0F 3A 44 C1 00 C3  pclmulqdq xmm0, xmm1, 0 \ ret

Only two instructions. pclmulqdq does the heavy lifting, it literally implements that type of xor-multiplication. ret to make it a callable function, hopefully satisfying the requirement of "outputting" the result (in the return value, xmm0). Putting integer arguments in xmm args is a bit unusual, but I hope you'll forgive me.

Using a built in operation sounds like cheating...

@CJDennis On the Standard Loopholes meta post, there is no consensus on whether it should be banned or not. There are 44 votes for banning, 31 votes against.

@isaacg I'm really not trying to be nit-picky but the wording of the question is: Your goal is to implement the operation of XOR (carryless) multiplication. Does this answer "implement" the operation itself or simply call someone else's function? All the other answers do the hard work themselves, often within a few bytes of this answer. I think they're all a lot cleverer and deserve upvoting more than this one.

@CJDennis I agree with you on that. I think this is a valid but uninteresting answer.

I don't really feel able to blame an answer if the question is so trivial it is implemented directly by a common CPU, one can hardly get any lower level than that. It isn't particularly interesting or memorable but does seem a valid answer, so +1.

I have no problem with a built-in being used to solve this -- otherwise, I wouldn't have know such a built-in exists.

@xnor: Carryless multiply (https://en.wikipedia.org/wiki/CLMUL_instruction_set) is useful in software RAID-6 I think, and apparently the GCM (Galois/Counter Mode) of AES.  Also for CRC computations.  pclmulqdq was new in Westmere, the generation after Nehalem which added SSE4.2.  (SSE4.2 added dedicated instructions for crc32c, but carryless multiply is still the best option for CRC with other polynomials.)  x86 existed for many years without this, but yeah now it's widespread, and various other ISAs have hardware support for it.

Z80, 11 bytes
B7 CB 32 30 01 B3 C8 CB 23 18 F6

The code is called as a function. a and b are in D and E (the order doesn't matter) and the answer is stored in A when the code returns (there are no I/O functions).
B7      XOR A     //  A^=A (A=0)
CB 32   SRL D     //    CARRY = lsb(D), D>>=1, ZERO = D==0
30 01   JR NC, 1  //    jump 1 byte if not CARRY
B3      XOR E     //      A^=E, ZERO = A==0
C8      RET Z     //    return if ZERO
CB 23   SLA E     //    E<<=1
18 F6   JR -10    //    jump -10 bytes

It produces the correct results for all test input except 63@63 which returns 85 because all the registers are 8-bit and 1365 mod 256 = 85 (integer overflow).

Pyth, 13 12 bytes
uxyG*HQjvz2Z

Demonstration.
uxyG*HQjvz2Z
                  Implicit:
                  z = input()
                  Q = eval(input())
                  Z = 0

       jvz2       The first input, written in base 2, like so: [1, 0, 1, ...
u      jvz2Z      Reduce over the binary representation, starting with 0.
 x                XOR of
  yG              Twice the previous number
    *HQ           and the second input times the current bit.

Old version, 13 bytes:
xFm*vz.&Q^2dQ

Demonstration.

I guess then there isn't a good way to avoid vz in taking two integer inputs.

@xnor No, unfortunately.

C, 44 38 bytes
Thanks to nimi, we now use recursion for 6 fewer bytes!
f(a,b){return b?(b&1)*a^f(a*2,b/2):0;}

We define a function f which takes a, b.
This can be called like:
printf("%d @ %d = %d\n", 13, 14, f(13, 14));

Which outputs:
13 @ 14 = 70
Try the test cases online!

Why not a recursive version f(a,b)={return(b)?(b&1)*a^f(2*a,b/2):0;}?

@nimi Ah, clever! I knew there was a way to get rid of that dumb parameter. I've got 38 bytes now. Thanks!

Struck out 44 is still regular 44. :(

The inputs are non-negative so you can replace (b&1) with b%2 to save a further two bytes since % has the same left-to-right precedence level as *.

Suggest b%2 instead of (b&1)

J, 14 bytes
*/(~://.@)&.#:

Usage:
   5 (*/(~://.@)&.#:) 17     NB. enclosing brackets are optional
85

Explanation (reading mostly from right to left; u and v stand for arbitrary functions):

u&.#: applies u to the vectors of the binary representations of the input numbers then turn the result back to an integer (u&.v == v_inverse(u(v(input_1), v(input_2))))
*/ products (*) of inputs in the Descartes product (/) of the two binary vector
v(u@) apply u to v (to the Descartes product)
u/. apply u to every anti-diagonal of the Descartes product (anti-diagonals represent the 1st, 2nd, ... digits in the binary representation)
~:/ reduce (/) an anti-diagonal with XOR operation (~:)
The last step is generating an integer from the binary vector which the first point takes care of.

Try it online here.

CJam, 14 13 bytes
q~2bf*{\2*^}*

How it works:
We first get the long multiplication results and then work our way up starting from the bottom two pairs.
q~                e# Eval the input. This puts the two numbers on stack
  2b              e# Convert the second number to binary
    f*            e# Multiply each bit of second number with the first number
                  e# This leaves an array with the candidates to be added in the long
                  e# multiplication step
      {    }*     e# Reduce on these candidates. Starting from the bottom
       \2*        e# Bit shift the lower candidate
          ^       e# XOR each other and continue

Try it online here

Python 2, 35 bytes
f=lambda m,n:n and n%2*m^f(2*m,n/2)

Call like f(13, 14). I think most languages with a similar construct will converge on something like this.

Java, 62
(x,y)->{int r=0,i=0;for(;i<32;)r^=x*((y>>i)%2)<<i++;return r;}

Expanded
class XORMultiplication {
    public static void main(String[] args) {
        IntBinaryOperator f = (x, y) -> {
                    int r = 0, i = 0;
                    for (; i < 32;) {
                        r ^= x * ((y >> i) % 2) << i++;
                    }
                    return r;
                };
        System.out.println(f.applyAsInt(14, 13));
    }
}

Is there a reason you prefer for(;i<32;) to while(i<32)? They're the same length, but the second seems like a more natural way to write it.

@JohnE I would guess that i++ was originally in the for loop and got golfed to its present position. Since while isn't any smaller there's no reason to change it.

I know it's been 7 years, but (y>>i)%2 can be y>>i&1 for -2 bytes and (x,y)-> can be a currying lambda x->y-> for an additional -1 byte: try it online.

Perl - 35 Bytes
#!perl -p
$\^=$`>>$_&1&&$'<<$_ for-/ /..31}{

Counting the command line option as one. Input is taken from STDIN, space separated.
Sample usage:
$ echo 13 11 | perl xormul.pl
127
$ echo 5 17 | perl xormul.pl
85
$ echo 14 13 | perl xormul.pl
70
$ echo 19 1 | perl xormul.pl
19
$ echo 63 63 | perl xormul.pl
1365

Jelly, 12 bytes
BJ’2*U×B{×^/

Try it online!
How it works
BJ’2*U×B{×^/ - Main link. Takes a on the left, b on the right
B            - Binary representation of a
 J           - Replace each element with its index
  ’          - Decrement
   2*        - Raise each to the power 2
     U       - Reverse
       B{    - Yield the binary representation of a
      ×      - Multiply the bits by the powers
         ×   - Multiply b by the results
          ^/ - Reduce by XOR

Jelly, 7 6 bytes
Bæc/ḂḄ

Try it online!
-1 thanks to Jonathan Allan
Takes a list of [a, b]. (The dyadic equivalent is the very fun-looking BæcḂḄɓB.)
B         Convert a and b to their binary digits,
 æc/      and convolve them.
    Ḃ     Take each mod 2
     Ḅ    and convert from binary.

Hah nice, was just about to post BæcB}ḂḄ

That's what I had too, but then I realized BæcḂḄɓB had more Bs :P

6 bytes as a monadic Link accepting a list of integers (works for any non-empty list). EDIT: sorry, less Bs :p

Haskell, 50 bytes
import Data.Bits
_#0=0
a#b=b.&.1*a`xor`2*a#div b 2

A translation of @BrainSteel's C answer. Usage example:
map (uncurry (#)) [(0,1),(1,2),(9,0),(6,1),(3,3),(2,5),(7,9),(13,11),(5,17),(14,13),(19,1),(63,63)]
[0,2,0,6,5,10,63,127,85,70,19,1365]

Julia, 35 33 30 bytes
f(a,b)=b%2*a$(b>0&&f(2a,b÷2))

This creates a recursive function f which takes two integers and returns the XOR product of the inputs.
Ungolfed:
function f(a, b)
    # Bitwise XOR : $
    # Short-circuit AND : &&

    b % 2 * a $ (b > 0 && f(2a, b ÷ 2))
end

Saved a couple bytes with encouragement from Sp3000!

MMIX, 28 bytes (7 instrs)
(jelly xxd)
00000000: e3020000 7aff0001 c60202ff 3f000001  ẉ£¡¡z”¡¢İ££”?¡¡¢
00000010: 37010101 5b00fffc f8030000           7¢¢¢[¡”‘ẏ¤¡¡

Disassembly:
clmul   SETL $2,0       // r = 0
0H      ZSOD $255,$0,$1 // loop: t = a odd? b : 0
        XOR  $2,$2,$255 // r ^= t
        SRU  $0,$0,1    // a >>= 1
        SLU  $1,$1,1    // b <<= 1
        PBNZ $0,0B      // iflikely(a) goto loop
        POP  3,0        // return r

You could get a 128-bit answer out of this with about three more instructions, I think.

Python 2, 104 91 78 66 bytes
def y(a,b,c=0):
 for _ in bin(b)[:1:-1]:c^=int(_)*a;a<<=1
 print c

Take the bits of b in reverse order, ending before you hit the '0b' at the start of the string. Multiply each one by a and xor with the total, then left-shift a. Then print the total.

Mathematica, 40 bytes
BitXor@@(#2BitAnd[#,2^Range[0,Log2@#]])&

What does mathematica do when you have two@signs in a row?

@Pavel f@@{a,b,c,d} = f[a,b,c,d]. http://reference.wolfram.com/language/ref/Apply.html

Go, 63 bytes
func f(a,b uint)uint{if a<1{return 0};return a%2*b^f(a/2,b*2)}

Complete example:
http://play.golang.org/p/-ngNOnJGyM

GAP, 368 Bytes

For mathematicians, this is multiplication in the polynomial ring F_2[x], identifying polynomials with natural numbers by evaluating at x=2 as a polynomial over Z.

Sure, let's do that! (this is only loosly golfed, the point was more to move into F2[x] and do the calculations more than any attempt at being a winning entry)
Here's the code
f:=function(i,j)R:=PolynomialRing(GF(2));x:=IndeterminatesOfPolynomialRing(R);x:=x[1];a:=function(i)local n,r;r:=0*x;while not i=0 do n:=0;while 2^n<=i do n:=n+1;od;n:=n-1;r:=r+x^n;i:=i-2^n;od;return r;end;b:=function(r)local c,i,n;i:=0;n:=0;for c in CoefficientsOfUnivariatePolynomial(r) do if c=Z(2)^0 then n:=n+2^i;fi;i:=i+1;od;return n;end;return b(a(i)*a(j));end;

Here's the ungolfed code with explanation:
xor_multiplication:=function(i,j)
    R:=PolynomialRing(GF(2));
    x:=IndeterminatesOfPolynomialRing(R);
    x:=x[1];
    to_ring:=function(i)
        local n,r;
        r:=0*x;
        while not i=0 do
            n:=0;
            while 2^n<=i do
                n:=n+1;
            od;
            n:=n-1;
            r:=r+x^n;
            i:=i-2^n;
        od;
        return r;
    end;
    to_ints:=function(r)
        local c,i,n;
        i:=0;n:=0;
        for c in CoefficientsOfUnivariatePolynomial(r) do
            if c=Z(2)^0 then
                n:=n+2^i;
            fi;
            i:=i+1;
        od;
        return n;
    end;
    return to_ints( to_ring(i)*to_ring(j));
end;

Okay, so first off, we create the univariate polynomial ring over the field F2 and call it R. Note that GF(2) is F2 in GAP.
R:=PolynomialRing(GF(2));

Next, we are going to assign the GAP variable x to the indeterminate of the ring R. Now, whenever I say x in GAP, the system will know I am talking about the indeterminate of the ring R.
x:=IndeterminatesOfPolynomialRing(R);
x:=x[1];

Next, we have two functions, which are inverse maps of each other. These maps are both onto, but they are not structure preserving, so I couldn't figure out a better way to implement them in GAP. There almost certainly is a better way, if you know it, please comment!
The first map, to_ring takes an integer and maps it to its corresponding ring element. It does this by using a conversion to binary algorithm, where every 1 that would appear in binary is replaced by an x^n where n is the appropriate power that 2 would take if the number was indeed binary.
    to_ring:=function(i)
        local n,r;
        r:=0*x;                 # initiate r to the zero element of R
        while not i=0 do        # this is a modified binary algorithm
            n:=0;
            while 2^n<=i do
                n:=n+1;
            od;
            n:=n-1;
            r:=r+x^n;
            i:=i-2^n;
        od;
        return r;
    end;

The next function reverses this. to_ints takes a ring element and maps it to its corresponding integer. I do this by getting a list of the coefficients of the polynomial and for each nonzero coefficient, the result is increased by 2^n, in the same way that we would convert binary to decimal.
    to_ints:=function(r)
        local c,i,n;
        i:=0;n:=0;
        for c in CoefficientsOfUnivariatePolynomial(r) do
            if c=Z(2)^0 then

                 # ^-- Right here you'll notice that the Z(2) is basically '1' in GF(2). So Z(2)^0 ~ 1 and Z(2)*0 ~ 0
                 # effectively, this line checks for nonzero coefficients

                n:=n+2^i;
            fi;
            i:=i+1;
        od;
        return n;
    end;

For the final step, we call these functions. We take the two integer inputs, convert them into elements in the ring R, then multiply these elements together, and send the product back to the integers.
return to_ints( to_ring(i)*to_ring(j));

Jelly, 16 bytes
Ḥ⁴BL’¤Ð¡U×"⁴B¤^/

Try it online!

ARM Thumb-2 (NEON), 6 bytes
Eat my Thumb, pclmullqlqdqdqdqdq. ARM has boring builtins, too!
ef80 0e01 4770

Assembly code:
        .syntax unified
        .arch armv7-a
        .fpu neon
        .thumb
        .globl xormul_boring_neon
        .thumb_func
xormul_boring_neon:
        // q0[0-8] = d0[0-8] @ d1[0-8]
        vmull.p8 q0, d0, d1
        bx       lr

Input: two 8-bit values in d0 and d1
Output: the 16-bit product in q0
This actually multiplies 8 packed bytes together.
ARM Thumb-2, manual, 14 bytes
Ok, to make up for it, here is a fully scalar version which does a 32x32 multiply with a 32-bit result.
2300 0849 bf28 4043 0040 d1fa 4770

Assembly code:
        .syntax unified
        .arch armv6t2
        .thumb
        .globl xormul_scalar
        .thumb_func
        // r3 <- r0 @ r1
xormul_scalar:
        // acc <- 0
        movs    r3, #0
.Lloop:
        // test each bit in y by using lsrs carry-out
        lsrs    r1, r1, #1
        // was the bit set?
        it      cs
        // if so, acc ^= x
        eorcs   r3, r0
        // shift x left
        lsls    r0, r0, #1
        // loop while x is non zero
        bne     .Lloop
.Lend:
        // return in r3
        bx      lr

Equivalent C code:
uint32_t xormul_scalar(uint32_t x, uint32_t y)
{
    uint32_t acc = 0;
    do {
        if (y & 1)
            acc ^= x;
        y >>= 1;
    } while ((x <<= 1));
    return acc;
}

The numbers to be multiplied are in r0 and r1, and the result is in r3.
It is a fairly basic shift and xor loop.
Yet another case of lsls and lsrs being far too useful than they deserve to be.
Try it online! (sorta): demo in Travis

05AB1E, 8 bytes
Îbv·yI*^

Try it online or verify all test cases.
Explanation:
Î         # Push 0 and the first input
 b        # Convert it to a binary string
  v       # Loop over each bit `y` of this string:
   ·      #  Double the current integer
    y     #  Push bit `y`
     I*   #  Multiply it by the second input
       ^  #  Bitwise-XOR the two together
          # (after the loop, the result is output implicitly)

Wolfram Language (Mathematica) v13.3+, 38 bytes
(F=2~FiniteField~+##;F@#2F@#)@"Index"&

Input [a, b].
Version 13.3 introduced FiniteField, which is nicer to golf with than FiniteFields`GF. Getting an integer out of a FiniteFieldElement is still a little verbose, though.

Dart, 34 32 bytes
m(a,b)=>a<1?0:a%2*b^m(a~/2,b*2);

Straight-forward recursive implementation.

Ruby, 76 75 73 bytes
a,b=$*.map{|x|x.to_i}
o=0
while(b>0)
o^=a&-(b&1)
a<<=1
b>>=1
end
puts(o)

Ruby, 60 bytes (function only, no I/O)
def t(a,b)
o=0
while(b>0)
o^=a&-(b&1)
a<<=1
b>>=1
end
t
end

gnuplot, 29 bytes
m(a,b)=a<1?0:a%2*b^m(a/2,b*2)

just like in Dart (see above)

GNU Assembler(x86_64 Mac OS X), 97 bytes
This is a proper function that can be called from C:
.text
.globl _f
_f:
movq %rdi,%xmm0;movq %rsi,%xmm1;pclmulqdq $0,%xmm1,%xmm0;movq %xmm0,%rax;ret

& can be tested with this C program:
#include <stdio.h>
int f(int a, int b);
#define p(a,b) printf("%d %d %d\n", a, b, f(a, b))
int main(void)
{
    p(0,1);
    p(1,2);
    p(9,0);
    p(6,1);
    p(3,3);
    p(2,5);
    p(7,9);
    p(13,11);
    p(5,17);
    p(14,13);
    p(19,1);
    p(63,63);
}

Note that on Mac OS X, you have to use clang -x c to compile it as C & not C++.
For linux(if I remember right), the code would be 95 bytes:
.text
.globl f
f:
movq %rdi,%xmm0;movq %rsi,%xmm1;pclmulqdq $0,%xmm1,%xmm0;movq %xmm0,%rax;ret

Strangely enough, this version is actually longer than defining the function in inline assembly, but that one was longer than the pure C solution we already have, so I decided to try assembly.
edit
If it's counted by the assembled size(excluding any labels &c.), then it's
x86_64 Assembler, 22 bytes:
0:  66 48 0f 6e c7          movq         %rdi,  %xmm0
5:  66 48 0f 6e ce          movq         %rsi,  %xmm1
a:  66 0f 3a 44 c1 00       pclmullqlqdq $0,    %xmm1,%xmm0
10: 66 48 0f 7e c0          movq         %xmm0, %rax
15: c3                      ret

I'd think you'd measure assembly languages by their compiled form though.

R, 53 bytes
f=function(x,y)`if`(y,bitwXor(x*y%%2,2*f(x,y%/%2)),0)

Try it online!

JavaScript (Node.js), 29 bytes
f=(x,y)=>x&&f(x>>1,y)*2^x%2*y

Try it online!
Similar to https://codegolf.stackexchange.com/a/50246/

Vyxal, 9 bytes
₌0b(dn⁰*꘍

Try it Online!
Ports the 05AB1E answer, so go upvote that too
Explained
₌0b(dn⁰*꘍
₌0b       # Push 0 and the binary of the first input
   (      # to each bit:
    d     # double the top of the stack
     n⁰*  # multiply the bit by the second input
        ꘍ # and bit xor

Pyt, 37 bytes
ɓąƖĐŁř⁻↔2⇹^**ĐŁ2%¬?ŕ:ŕÁ0á;ĐŁ`ŕʁ⊻ĐŁ⁻łŕ

Try it online!
Takes two integers a,b on separate lines
The following is worked on a=13, b=14

Code
Stack
Description

ɓąƖ
[1,1,0,1]
Pushes the ąrray corresponding to the ɓits of 13

ĐŁř⁻↔2⇹^*
[8,4,0,1]
Converts array to corresponding powers of 2

*
[112,56,0,14]
Multiplies the array by 14

ĐŁ2%¬?
[112,56,0,14], True
does the array have an even length?

ŕ
[112,56,0,14]
If so, pop the boolean check

:ŕÁ0á
(skipped in this run)
Otherwise, append a 0 to the array

;ĐŁ`ŕʁ⊻ĐŁ⁻ł
[70], 0
ʁeduce the array using XOR (⊻) while the Łength of the resulting array is greater than 1

ŕ
[70]
ŕemove the 0; implicit print

Itr, 9 bytes
BàBC*µRxB
online interpreter
Explanation
            ; implicit input
BàB         ; convert input to bit lists
   C*µRx    ; polynomial multiplication in F2[X]
        B   ; convert bit-list to number
            ; implicit output

Nekomata, 5 bytes
ᵃƂ×Öƃ

Attempt This Online!
ᵃƂ×Öƃ
ᵃƂ      Convert both inputs to binary digits
  ×     Convolve
   Ö    Modulo 2
    ƃ   Convert back to decimal

golflua 68
x,y=I.r("*n","*n")r=0~@i=0,31r=B.x(r,x*B.ls(B.rs(y,i)%2,i+1))$w(r/2)

Does basically the same bitshifting as Ypnypn's Java answer, but seems to require the divide by 2 at the end to work correctly. Takes in values as stdin, examples below
> 14 13
70
> 19 1
19
> 5 17
85

Ceylon, 90 bytes
alias I=>Integer;I x(I a,I b)=>[for(i in 0:64)if(b.get(i))a*2^i].fold(0)((y,z)=>y.xor(z));

This is just the algorithm as described: multiply a by 2^i wherever the ith bit is set in b, and add them all together using xor. Iterates over 0:64 because Integers are 64-bit in Ceylon when running on JVM (lower when running as Javascript, but then b.get(i) just returns false).
Formatted:
alias I => Integer;

I x(I a, I b) =>
      [
        for (i in 0:64)
            if (b.get(i))
                a * 2^i
      ].fold(0)((y, z) => y.xor(z));

The alias safes here just a single byte.

JavaScript (Node.js), 42 bytes
Port of the Java answer. Go upvote that!
x=>y=>(g=i=>i&&g(--i)^x*((y>>i)%2)<<i)(32)

Try it online!

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


text:
Detecting anagrams within a Parent String
Given two strings, a parent string and a query string respectively, your task is to determine how many times the query string, or an anagram of the query string; appears in the parent string, in a case-sensitive search.
Examples of Behaviour
Input 1
AdnBndAndBdaBn
dAn

Output 1
4

Explanation
The substrings are highlighted in bold below:
AdnBndAndBdaBn
AdnBndAndBdaBn
AdnBndAndBdaBn
AdnBndAndBdaBn
Note the search MUST be case sensitive for all searches.
Input 2
AbrAcadAbRa
cAda

Output 2
2

This must work for standard ASCII only. This is code-golf, so shortest number of characters will get the tick of approval. Also please post a non-golfed version of your code along with the golfed version.

Important test case: abacacaba aac

Will the parent string always be longer than the query string ?

Oh very good point! Yes @Optimizer, the parent string will always be longer than the query string.

@WallyWest What about the additional test case? Should overlapping occurrences of a single permutation be counted?

Can you give a test case and its correct solution for your most recent comment?

Can the input be on one line, space seperated?

@WallyWest, your most recent comment contradicts the question and, as far as I can tell, all seven undeleted answers. I think the only sensible option you have is to delete the comment and to edit the question to be explicit that the substrings may overlap.

@PeterTaylor A valid point... granted, a substring may overlap...

Pyth, 11 10 bytes
lfqSzST.:w

1 byte golf thanks to @Jakube.
Demonstration.
Takes the query string, followed by the parent string on a new line.
Ungolfed:
z = input()
len(filter(lambda T: sorted(z) == sorted(T), substrings(input())

1 byte save, simply remove the last character of your solution ;-)

@Jakube Oh, of course, that's wonderful.

CJam, 13 bytes
le!lf{\/,(}:+

(12 bytes, if overlapping is allowed)
l$_,lew:$\e=

Input goes like:
dAn
AdnBndAndBdaBn

i.e.
<query string>
<parent string>

Thanks to Dennis for saving 3 bytes in the overlapping scenario
Try it online here

You can handle overlapping with the same byte count: ll1$,ew:$\$e=

@Dennis That's really nice. 12 bytes : l$_,lew:$\e= But not sure if this would be valid now that OP has said that overlapping is not allowed. Let me see if I can reduce my current one.

Python 2, 124 118 bytes
Try it here
This is an anonymous lambda function. It can probably still be golfed further.
import re,itertools as i
lambda p,q:sum(len(re.findall('(?='+''.join(i)+')',p))for i in set(i.permutations(q,len(q))))

Ungolfed:
from itertools import*
import re
def f(p,q):
    c=0
    for i in set(permutations(q,len(q))):
        c+=len(re.findall('(?='+''.join(i)+')',p))
    print c

don't need re, you can just do string.count(substring) for each permutation

@sirpercival No, string.cound doesn't count overlapping occurrences, like in the f('aaa','aa').

ah, good call! i forgot about that.

import re,itertools as i saves 6 chars. (I haven't known before that it works.)

JavaScript ES6, 95 bytes
f=(p,q,n=0,s=a=>[...a].sort().join(''))=>[...p].map((_,i)=>n+=s(p.substr(i,q.length))==s(q))&&n

This is a function that takes two arguments like this: f(parent,query).
It goes through all substrings of the parent string of the length of the query string and sorts them. If they are the same as the sorted query string, it increments n. Sorting string is annoying because it must be converted to an array, sorted, and converted back to a string. Ungolfed and testable code below.

var f = function(p, q) {
  var n = 0
  var s = function(a) {
    return a.split('').sort().join('')
  }

  p.split('').map(function(_, i) {
    n += s(p.substr(i, q.length)) == s(q)
  })
  return n
}

// testing code below
document.getElementById('go').onclick = function() {
  var parent = document.getElementById('parent').value,
    query = document.getElementById('query').value;
  document.getElementById('output').innerHTML = f(parent, query);
}
Parent: <input id="parent" value="AdnBndAndBdaBn"/>

Query:  <input id="query" value="dAn"/>

<button id="go">Go</button>

<samp id="output">—</samp> anagrams found

Haskell, 77 68 bytes
import Data.List
p#s=sum[1|x<-tails p,sort s==sort(take(length s)x)]

Usage:
*Main> "AdnBndAndBdaBn" # "dAn"
4
*Main> "AbrAcadAbRa" # "cAda"
2
*Main> "abacacaba"# "aac"
2

How it works: parent string is p, query string is s.
tails creates a list of it's parameter with successively removing the first element, e.g. tails "abcd" -> ["abcd","bcd","cd","d",""]. For every element x of this list take a 1 if the sorted first n elements (where n is the length of s) equal the sorted s.  Sum the 1s.
Edit: tails instead of explicit recursion

Python 2, 76 70 bytes
This lambda function iteratively compares each sorted substring with the target substring. The matches are counted and returned.
lambda a,d:sum(sorted(d[n:n+len(a)])==sorted(a)for n in range(len(d)))

The ungolfed code:
f = lambda substr, text: sum(
    sorted(text[n:n+len(substr)]) == sorted(substr)
    for n in range(len(text))
    )

def test(tests):
    for t in tests.split():
        substr, text  = t.split(',')
        print t, f(substr, text)

tests = '''ba,abcba dAn,AdnBndAndBdaBn aac,abacacaba'''
test(tests)

and the test output:
ba,abcba 2
dAn,AdnBndAndBdaBn 4
aac,abacacaba 2

ZOUNDS! I never saw that. I will edit and save some bytes. Thanks Jakube.

Python, 61 bytes
s=sorted
f=lambda a,b:a>''and(s(b)==s(a[:len(b)]))+f(a[1:],b)

This is a recursive algorithm. It checks whether the initial characters of the parent string, once sorted, are the same as the query string, sorted. Then, it recursive on the parent string with its first character removed. It terminates when the parent string is empty.

source: Stack Exchange

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

sort: votes


text:
We're Spiralling out of control, Doctor!
The Doctor, in trying to escape from the Dalek forces has decided to send them in a spin by traveling in various pockets of space in a spiral motion.
Depending on the nature of the available space-time, The Doctor needs to enter into the TARDIS controls the height and width of the section of space and his entry point with which to begin the spiral.
The section of space can be envisioned as a h x w grid filled with sequential integers from left to right, top to bottom, starting with 1.
The starting position is provided as r c for the row and column... From this the TARDIS's software needs to spit out the ordered list of integers obtained by spiraling outward in an anti-clockwise direction from row r column c, starting upwards...
Your task, as the Doctor's companion is to program the TARDIS to take four numbers, in the format height width row column and have it determine which sector of space the TARDIS needs to travel to match the spiral movement described below...
Input 1
5 5 3 3

(5 x 5 grid, starting at position 3,3)
Output 1
13 8 7 12 17 18 19 14 9 4 3 2 1 6 11 16 21 22 23 24 25 20 15 10 5

Explaining output
Original grid

Generated spiral

Input 2
2 4 1 2

(2 x 4 grid starting at position 1,2)
Output 2
2 1 5 6 7 3 8 4

Explaining output
Slightly different as spiral now must circle around grid to generate respective output...
Original grid

Generated spiral

Rules:

This is code-golf, so shortest code length gets the tick of approval.
The above examples must be used to test your code. If it doesn't provide the respective output, there's something wrong...
Both golfed and in-golfed versions of code must be provided in your answer...

Good luck!

May I point you to http://draw.io where one can quickly make rather reasonable drawings (you've got excellent legibility with your hand drawn version... just I don't see any red circles).  Consider http://i.stack.imgur.com/xbLSA.png as an example of what could be done.  Note that that has the xml embeded in it, so if you go to draw.io you can import from url.

I'll bear that in mind for my next need for a drawing, @MichaelT, thank you...

I post an answer with a function returning array as output. Is it acceptable?

@edc65 Mate, you and I go way back here on CG, I'll allow a function of S(h,w,r,c) or the like for this... :)

JavaScript (ES6) 124 163 177
Edit Totally different way, no need of an array to store visited cells. Using the fact that the side of the spiral increase of 1 after every 2 turns.

// New way
f=(h,w,y,x)=>
  (e=>{
    for(o=[],d=i=t=l=0;l<w*h;i<t?i+=2:[i,d,e]=[1,-e,d,++t])
      o[l]=y*w-w+x,l+=x>0&x<=w&y>0&y<=h,x+=d,y-=e
  })(1)||o

// Golfed
g=(h,w,y,x)=>
  (g=>{
    for(e=n=0;n<h*w;)g[[n%w+1,-~(n/w)]]=++n;
    for(o=[g[[x,y]]],l=d=1;l<n;l+=!!(o[l]=g[[x+=d,y+=e]]))
      g[[x,y]]=0,
      g[[x+e,y-d]]!=0&&([d,e]=[e,-d])
  })([])||o

// Not golfed
u=(h,w,y,x)=>{
  var i,j,dx,dy,kx,ky,o,n,
    g={} // simulate a 2dimensional array using a hashtable with keys in the form 'x,y'

  for(n=i=0; i++<h;) // fill grid (probably better done in a single loop)
    for(j=0; j++<w;)
      g[[j,i]] = ++n;
  o=[g[[x,y]]] // starting point in output
  dx=1, dy=0 // start headed right

  for(; !o[w*h-1]; ) // loop until all w*h position are put in output
  {
    g[[x, y]] = 0 // mark current position to avoid reusing
    kx=dy, ky=-dx // try turning left
    if(g[[x+kx, y+ky]] != 0) // check if position marked
    { // found a valid position
      dx=kx, dy=ky // change direction
    }
    x+=dx, y+=dy // move
    k=g[[x, y]] // get current value
    if (k) o.push(k) // put in output list if not 'undefined' (outside grid)
  }
  return o
}

// TEST - In FireFox

out=x=>O.innerHTML+=x+'\n';
[
 [[5,5,3,3],'13 8 7 12 17 18 19 14 9 4 3 2 1 6 11 16 21 22 23 24 25 20 15 10 5'],
 [[2,4,1,2],'2 1 5 6 7 3 8 4']
].forEach(t=>out(t[0] + '\n Result: ' + f(...t[0])+'\n Check:  ' + t[1]))

test=()=>
{
  var r, i=I.value.match(/\d+/g), h=i[0]|0, w=i[1]|0, y=i[2]|0, x=i[3]|0
  if (y>h||x>w) r = 'Invalid input'
  else r = f(h,w,y,x)
  out(i+'\n Reault: ' +r)
}

Your test:<input id=I><button onclick="test()">-></button>

Amazing golfing! From 300 to 163... I take my hat off to you...

@WallyWest with that comment you push me to do better. Thnx

Nice! My Python solution was a lot longer but I was like, it is all right, you use a better method. Now you use the same and it it is even shorter... I have some work to do. :)

@randomra I'd still love to see it...

Python 3, 191
Probably not a great score, but here it goes:
def f(b,a,d,c):
 p,r,l,s,h=c+1j*d,-1j,1,0,0
 for _ in [0]*((a+b)**2):x,y=p.real,p.imag;0<x<a+1and 0<y<b+1and print(int((y-1)*a+x),end=' ');p+=r;s=(s+1)%l;t=s==0;h=(h+t)%2;l+=h<t;r*=(-1j)**t

We move along the spiral by increasing side-length after every second turns. If our position is inside the given grid we print its corresponding number.
Variables are:

p is complex position
x and y are position coordinates
r is direction
s is position on current side
l is current side length
h is the parity of the current side's ordinal

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


text:
CodeGolf - Heads or Tails
Instructions
Given an unknown input string i with a value of either heads or tails, return 1 for heads or -1 for tails with the shortest code.
Sample not golfed code (55b):
if(i == "heads"){
    print(1);
}else{
    print(-1);
}

Sample golfed code (16b):
print("t">i||-1)

Javascript was used for the example but it's not a requirement. Sorry if it's too simple for most users, it can be improved.

Welcome to PPCG! This is too simple to be an interesting challenge. In the future, please consider posting challenges to the Sandbox, where they can get feedback before posting them live.

6 answers, not so a bad challenge indeed. Try again

Got down voted to earth, can't see the score but at least there are four down votes, I'm not trying again, sticking to so

At 4 upvotes and 5 downvotes, your question wasn't really unpopular; it just got mixed reviews. While the task at hand is a little basic, it is well-defined and attracted 7 answers so far which feature several different approaches. Not that bad for a first attempt.

Let's see if I can at least score 0 and maybe I'll post the next one, I have so many ideas for puzzles..

@JuanCortés Don't give up on making puzzles; it might be hard starting out, but once you get the hang of it, it'll be a whole lot more fun.

I'm so confused right now, yesterday -4, now +4, this sure ain't stackoverflow :P

I've been waiting for a short challenge like this for ages, most of the challenges are too long and complicated for a novice like me.

I don't think you'll have to post a golfed example in the question – better do this as an answer.

CJam, 4 bytes
I'e#

Assumes that the variable I holds the input, since i isn't a valid identifier in CJam.
Try it online.
This is equivalent to the JavaScript code I.indexOf('e').

Probably unbeatable for this challenge.

Sorry I didn't understand the requirements enough and made a fool of myself with this question. I'll go back and hide now

Why do you not include the p in this? Is it standard in CJam not to?

@Tim CJam always prints the stack contents at the of the program automatically.

@Tim: The question says to return 1 or -1, so I assumed leaving the number on the stack would be fine. I've edited the permalink to show that p is not needed.

C, 18 bytes
Pretty easy, but let's do it just for fun...
puts("-1"+*i/8%2);

Given the string char *i it prints 1 for heads and -1 for tails, with trailing newline.
Explanation
In C, "-1" + 1 points to 1 character forward, so it is the same as "1". Let's take a look at the first characters:
"heads"[0] = 'h' = 104 = 0b01101000
"tails"[0] = 't' = 116 = 0b01110100

If we count the bits from the rightmost one starting at zero, bit 3 is 1 in heads and 0 in tails: summing it to "-1" gives the right string. It looks like this:
"-1" + ((i[0] >> 3) & 1)

Now, substitute i[0] with *i and the right shift with the power-of-two division to save some bytes. Also remove useless parentheses:
"-1" + (*i / 8 & 1)

Now, & 1 can be substituted with % 2. The character count is the same, but the modulus has higher priority, allowing to drop the parentheses. Remove the whitespace:
"-1"+*i/8%2

Bonus
I think the shortest way to get an integer 1 or -1 (not a string) in C is:
18-*i/6

Explanation:
'h' = 104
't' = 116

('h' + 't') / 2 = 110
110 - 'h' =  6
110 - 't' = -6

(110 - 'h') / 6 =  1
(110 - 't') / 6 = -1

Apply distributive property (integer division):
18 - 'h' / 6 =  1
18 - 't' / 6 = -1

Beautiful, love it

Ruby, 8 (6 without output)
p ?t<=>i

Rocketship operator!

Clearly the right tool for the job.

PHP - 11 Bytes
<?=1-$i^=F;

This works because 'tails' ^ 'F' → '2' and 'heads' ^ 'F' → '.', which when typed as an integer is 0.
You may test this solution (or any of the below) in the following way:
<?php foreach(['heads', 'tails'] as $i): ?>
 <?=1-$i^=F;
endforeach; ?>

Ideone Link

Alternatives
15: <?=1-md5($i)%3;
16: <?=md5($i)[5]-5;
16: <?=-crc32($i)%5;

With the short version I'm always getting a 1, care to explain what it does with the XOR?

@JuanCortés I've added an explanation, and a link to Ideone.

Now that's thinking outside the box!

TI-BASIC, 9-10 bytes
cos(πʳinString(Ans,"t

Straightforward. "t" is in position 1 of "tails", but "t" is not in the string "heads", so inString( returns 1 for tails and 0 for heads.
If your calculator is in radian mode (as any mathematician's should be), it takes only nine bytes:
cos(πinString(Ans,"t

Note that TI calculators do not have named strings, so the input is in the calculator's answer variable. Also note that lowercase letters are two bytes each, so this solution actually takes less memory than than the word "heads".

This is awesome. Your byte count is off, though-- cos(, π and the radian symbol are all one byte, so it's actually 8-9 bytes.

The t and inString( are each two bytes.

Oh, I'd forgotten about lowercase letters being two bytes. Never mind, then.

Fission, 26 21 Bytes
O/';'1
"S@]_"-
R? <tL

Martin (and his excellent answer here) convinced me to learn a new language, and what better place than a quick golf? This is almost certainly not optimal, but hey, it was fun! Once I feel good about it, I may provide some form of explanation if it is requested.

x86-16 machine code, 8 bytes
As a callable function, input string at DS:SI, output in AL.
80 3C 74    CMP  BYTE PTR[SI], 't'      ; if 'h': CF = 1, if 't': CF = 0
1A C0       SBB  AL, AL                 ; AL = AL - AL - CF (AL = -CF)
                                        ;  if 't': AL = 0 and CF = 0
                                        ;  if 'h': AL = -1 and CF = 1
1C FF       SBB  AL, -1                 ; AL = AL - (-1) - CF
                                        ;  if 't': AL = AL + 1 = 1
                                        ;  if 'h': AL = AL + 0 = -1
C3          RET

x86-16 machine code, IBM PC DOS, 17 bytes
Or as a standalone DOS COM executable. Input from command line, output to stdout.
00000000: b402 0826 8200 7a04 b22d cd21 b231 cd21  ...&..z..-.!.1.!
00000010: c3

Unassembled:
B4 02           MOV  AH, 02H        ; DOS API display char function
08 26 0082      OR   DS:[82H], AH   ; set parity flag from input
7A 04           JPE  HEADS          ; if even, heads - display just '1'
B2 2D           MOV  DL, '-'        ; otherwise first display a '-''
CD 21           INT  21H            ; output DL to console
            HEADS:
B2 31           MOV  DL, '1'        ; display the '1'
CD 21           INT  21H            ; output DL to console
C3              RET

Explanation:
Use the CPU's parity flag to determine if first char is an 'h' (even number of binary 1's) or a 't' (odd number of binary 1's). This saves one byte over comparing the char in ASCII.
Input/Output:

Tr: 17 13 characters
(Or 14 10 if you count only the arguments…)
tr -s ta-s -1

Sample run:
bash-4.3$ tr -s ta-s -1 <<< heads
1

bash-4.3$ tr -s ta-s -1 <<< tails
-1

Brief explanation:
tr stands for transliterate, that means, replaces each character of the input found in the first argument with character at the same position in the second argument:
tr ta -1 <<< tails         # replaces t ⇢ -, a → 1
⇒ -1ils

If the first argument is longer, the characters without positional match in the second argument are replaced with second argument's last character:
tr tals -1 <<< tails       # replaces t ⇢ -, a → 1, l → 1, s → 1
⇒ -1i11

When -s (--squeeze-repeats) option is used, successive characters which would be replaced with the same character are replaced at once:
tr -s tals -1 <<< tails    # replaces t ⇢ -, a → 1, l+s → 1
⇒ -1i1

So if we enumerate all characters in “tails”, we get what we need:
tr -s tails -1 <<< tails    # replaces t ⇢ -, a+i+l+s → 1
⇒ -1

Same for “heads”, but wee need to keep the “t” in front to consume the minus (characters sorted alphabetically for creepiness):
tr -s taedhs -1 <<< heads   # replaces h+e+a+d+s → 1
⇒ 1

Merging all uniques characters of “tails” and “heads” in a single first argument, keeping “t” in front leads to final solution:
tr -s tadehils -1 <<< tails # replaces t → -, a+i+l+s → 1
⇒ -1

tr -s tadehils -1 <<< heads # replaces h+e+a+d+s → 1
⇒ 1

To avoid enumerating the characters, an interval in from-to format can be used instead.

Care to explain it?

That assumes BSD/GNU tr. POSIXly: tr -s ta-s '-[1*]'

C, 22 bytes
puts(*i>'h'?"-1":"1");

Credits goes to @TheE for telling me about this!
Explanation:
If the first character of the string is greater than 'h', the string "-1" is printed. Otherwise, the string "1" gets printed. Note that this approach comes with a trailing newline character.

Old version (25 bytes):
printf("%d",*i>'h'?-1:1);

Explanation:
If the first character of the string is greater than 'h', -1 is printed. Otherwise, 1 is printed.

i just said t before , use i as type char , the actual definition would exceed by 1byte like this return -(-1)**i/16

@Agawa001 , But that returns 6 for h and 7 for t.

oh i forgot , i must use power :p

Cool guy unfortunately C doesnt have such arithmetic operation thus u have to use -1*pow(-1,*i/16) which makes it waaay longer, in other hand, python and matlab use ** and ^

@CoolGuy would using puts puts(*i>'h'?"-1":"1"); not be better? (22 bytes)

@TheE , Good idea. I hadn't thought of puts as I have to print a number and puts is used to print a string. Thanks!

While keeping the conditional core, you can use the method I used in my answer by flipping the statement: puts("-1"+(*i<'t')); or puts(&"-1"[*i<'t']); are both 20 chars.

@AndreaBiondo , Awesome! I really liked puts(&"-1"[*i<'t']);! You can add that in your answer as it is your idea. BTW, I'm truly impressed by your answer. Its just cool. Very cool indeed. :D

Python 2, 16 bytes
print(i<'t')*2-1

Pyth - 4 bytes

 xz"e

Run with heads or tails. As i is int in Pyth, this uses z as the variable name, which contains any user input. It is equivalent to the Python print(z.find("e")), so uses @Dennis's method.

VBA (Excel), 12 bytes
Not a fantastic bit of golfing, but it's fun to try with VBA to get anywhere near to a proper programming language...
?13-asc(i)/6

i is the string, and it just exploits the ASCII value of the first character, divided by 6 and substracted from 13 to give 1 or -1. Very simple.
Example run in immediate window (10 extra bytes to set the input variable) :
i="Heads":?13-asc(i)/6
 1

Japt, 2 bytes
ae

Try it online

shell (portable/POSIX), 16 bytes
expr $i : he - 1
Try It Online!
Thanks to @StéphaneChazelas in unix.stackexchange.com
Other solutions tried:
echo $[30#$i%7-1]               # 17 bytes but only in bash, zsh. Try It Online!
echo $((30#$i%7-1))             # 19 bytes but only bash,ksh,zsh. Try It Online!
he=2;echo $[${i%a*}-1]          # 22 bytes But only in bash,zsh . Try It Online!
a=${i%h*};echo ${a:+-}1         # 23                   . portable . Try It Online!
he=2;echo $((${i%a*}-1))        # 24 bytes             . portable . Try It Online!
IFS=h;set $i;echo ${1:+-}1      # 26 (change IFS)      . portable . Try It Online!
(IFS=h;set $i;echo ${1:+-}1)    # 28 (subshell)        . portable . Try It Online!
(IFS=h;set $i;echo $(($#*2-3))) # 31 bytes             . portable . Try It Online!
Note: Using dash as a reasonable simile of a portable shell tester.

expr $i : he - 1 works by counting how many characters match he with $i : he. A heads match 2 and a tails match 0 (none).Then substracting 1 with - 1.

$[30#$i%7-1] works by converting the string to an integer. The base 30 and the mod by 7 were selected to obtain a difference of 2 between heads and tails. Then subtracting 1 converts the numbers to 1 and -1.
Note that a $[...] is an archaic form of arithmetic expression $((...)) valid only in some shells.

he=2;echo $[${i%a*}-1] works by making a variable of some value and then using Arithmetic Expansion to expand that variable (from the text value). The ${i%a*} converts heads to he and tails to t (that, as a variable, has a value of 0).

IFS=h;set $i;echo ${1:+-}1 works in two steps. Setting IFS to h breaks the unquoted $i in set $i into parts divided by the character h, heads is divided to '' and 'eads', thus setting $1 to null. tail is not divided by h, thus making $1 equal to tails. Then, ${1:+-} generates a - if the value of $1 is non-null (as in tails) or nothing (as with a null $1). That sign (or nothing) is concatenated with 1.

(IFS=h;set $i;echo $(($#*2-3))) works in a similar way but use the number of parts ($#) that the string in $i got broken into.

Python, 20 bytes
print(('h'in i)*2-1)

This returns False if it isn't, and True if it is. In python False and 0 are the same, and True and 1 are as well.
So:
True (1) * 2 -1 = 2-1 = 1
False (0) * 2 - 1 = 0-1 = -1

Python 2, 17 bytes
print'-1'['t'>i:]

'heads' is less than 't', so it evaluates to True == 1, and prints the string after the first character. 'tails' is greater than 't', so it evaluates to False == 0 and the whole string is printed.
If we're doing this from the command line, with implicit printing, it just becomes:
'-1'['t'>i:]

...for 12 bytes, but it adds single quotes to the output.

QBasic, 11 bytes
This has got to be the shortest piece of QBasic I've ever written.
c=i>"t
?c^c

Explanation:
The above is some pretty heavily golfed QBasic. Once the autoformatter gets through with it, it'll look like this:
c = i > "t"
PRINT c ^ c

The first line compares the string i with "t". If i is "heads", i > "t" is false and c = 0. If i is "tails", i > "t" is true and c = -1. Yes, -1 is the default value for boolean true in QBasic!
The second line maps -1 to -1 and 0 to 1 via a math trick: (-1)^(-1) == 1/(-1) == -1, and 0^0, though technically mathematically undefined, returns 1.
This code requires that i be explicitly declared as a string variable; otherwise, it would have to be i$. Full test program (tested on QB64):
DIM i AS STRING
DATA heads, tails

FOR x = 1 TO 2
READ i

c=i>"t
?c^c

NEXT x

ed, 27 25 21 bytes
ed gave me a headache. Finally figured it out with help from @ed1conf on twitter and some peeps on unix.se. You can't just match things with s/re/newtext/, you have to prefix it with g otherwise ed packs a sad. It's like a grumpy 50 year old unix program saying "get off my lawn".
g/t/s//-
,s/\w\+/1
w

Try it online!
-2 bytes by dropping the final /s
-4 bytes thanks to @manatwork (& whose sed answer i plagiarised)
Old version:
g/t/s//-
g/\w\+/s//1
wq
.

But you need the address trick only for the 1st command, as the 2nd will never fail. And no need to explicitly q, it will quit by itself when nothing left to do. And you only need a newline after them, the “.” (or “roblogic”…) is unnecessary. Try it online!

Ahh thanks I will try your suggestions when I get home. At the pub now

Gaia, 5 4 bytes
'eI(

Similar to Dennis' CJam answer, finds the index of e in the input string
Saved one byte since I didn't realise input was automatically used as an argument if there isn't enough stack values
How it works
'e  Push e
I   Index of e in the the input. 2 if heads, 0 if tails
(   Subtract One
Stack gets automatically outputted

Try it Online!

Bash, 22
echo $[0x${1:1:1}/2-6]

Takes the 2nd letter (e or a) and interprets it as a hex digit (14 or 10), then divide by 2 and subtract 6 to get the right answers.
Try it online!

Awesome trick, I'm gonna borrow it :)

For bash, use: echo $[30#$i%7-1] only 17 bytes. :-)

Sed: 16 characters
s/t/-/
s/\w\+/1/

Sample run:
bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'heads'
1

bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'tails'
-1

Nice, I used your regex for my ed solution, but it still took 23 bytes, because ed is old and grumpy!

\w and \+ are GNU extensions though.

golflua 25 20 18
w(I.r():f'h'&1|-1)

Probably could be golfed some more by using some tricks that I'm not thinking about at the moment. (see history for old version) Saved 5 chars by moving input to write and ignoring the if statement there. Two more chars were saved by ignoring the optional parenthesis on find. It does not check for failed conditions (i.e., input that isn't heads or tails).
A Lua equivalent would be
io.write(io.read():find('h') and 1 or -1)

Haskell, 18 bytes
f('h':_)=1
f _= -1

Every string starting with the letter h is mapped to 1, all others to -1.

APL (Dyalog Unicode), 5 bytes
3-3⊃⍋

Try it online!

Stax, 3 bytes
'eI

Run and debug it

Stax, 4 bytes
└0Y.

Run and debug it
It's the codepoint of the first character mod 7 minus 5.

Keg, 8 12 8 bytes
_d=2*1-.

Try it online!
Explanation (syntactically invalid)
_        Take input and discard the last item
 d=      If the top of the stack is d:
   2*    Re-set the top of the stack as 2
     1-  Decrement the top of the stack by 1
       . Explicitly output the top of the stack

 -4 bytes thanks to manatwork

May there be some TIO interpreter version difference? Looks like it doesn't handle neither “heads” or “tails”.

Now I fixed the program.

May there be some TIO interpreter version difference? Seems it takes input implicitly and reverses it on any attempt to process inexistent data, making it work without ^.

BTW, you not need to discard 4 characters until “t” as the 2nd one “d” or “l” already identifies which input you got. Just have to explicitly output so can leave the unprocessed input on the stack: Try it online!.

I think I can still -1 bytes by switching to "Reg": TIO!

PowerShell, 15 bytes
($args[1]-99)/2

Try it online!
Takes input via splatting. Uses the e vs the a to do ASCII math

dc, 8 bytes
?z2*1r-p

dc can't do anything meaningful with strings other than read them in and attempt to evaluate them.  Doing this, "heads" outputs some warnings about unimplemented commands and empty stack, which we ignore, but importantly the stack remains empty.  "tails" does almost the same with the important exception that the final "ls" loads a value from the s register to the stack.
We then use "z" to get the stack length and arithmetically fiddle to get the right answers.
Try it online!

Triangular, 10 bytes
F.~%.7/-_<

Try it online!
Divides the ASCII value of a character input by 7. Subtracts the quotient from 15. Execution stops when the IP runs out of the program space. This works because Triangular can only manage integer division. Conveniently, "h" has a value of 104, which is 14 when integer divided by 7; "t" is 116, which is 16 when integer divided by 7.
Ungolfed/Explanation:
   F
  . ~
 % . 7
/ - _ <
---------------------------------------------------------------
F                 - Push 15 to Top of Stack
 ~                - Read a character from input, push its value to ToS
   7              - Push 7 to ToS
     <_           - Change directions, then pop ToS-1 and ToS, push their integer quotient
        -         - Pop ToS-1 and ToS, push their difference
          %       - Print ToS as an integer

Previous version (14 bytes):
~\81|m/,!<.>i%

Read a character from input; if that character's ASCII value divided by 8 has a remainder, print -1, otherwise print 1.

Vyxal, 3 bytes
\eḟ

Try it Online!
Direct translation of the CJam answer (find the index of e, or -1 if not found).
Some more fun ones:
Vyxal, 5 bytes
14βǒ‹

Try it Online!
14β     Convert given string from base 14 to integer
        (invalid digits are treated as -1)
   ǒ    Modulo 3
    ‹   Decrement

Vyxal, 4 bytes
18β±

Try it Online!
18β     Convert from base 18 to integer
   ±    Sign
        "heads" is positive -> 1
        "tails" is negative (because leading digit is invalid) -> -1

Did not expect to see base conversion used like this today. Had to stop for a bit and remember how the implementation of invalid characters works after seeing this. Very clever!

Vitsy, 13 bytes
So what, I'm late for the party. ¯\_(ツ)_/¯
zv&v'h'=)i1rN
z             Grab all input.
 v            Capture the top item (h or t) as a temp variable.
  &           Generate new stack, move to it.
   v'h'=      Test if the variable is h.
        )i    If it isn't, push -1.
          1   Push 1.
           r  Reverse the stack.
            N Print out the top item as a number.

SmileBASIC, 15 bytes
H=2?VAR(I[T])-1

Not the shortest possible solution, but I didn't want to post a boring program that's the same as all the others.
The VAR "function" converts a variable name into a variable. VAR("X") = 1 is equivalent to X = 1, for example.
The program sets H to 2, then uses VAR() on the first character in the input string.
(I[T] is the same as I[0], because T is 0. I had to include T here because VAR is not allowed to create new variables).
If the input is heads, VAR() returns the variable H, which has a value of 2.
If the input is tails, VAR() returns the variable T, which has a value of 0.
Then, it subtracts 1 from this and outputs either -1 or 1.
Because variable names in SmileBASIC are not case sensitive, this program works for any capitalization of the input string.
Note:
Normally, string variables must have names ending in $, but there are several ways to avoid this restriction. The simplest is to put the code inside a function, because function arguments are not type checked:
TEST "heads"
TEST "tails"

DEF TEST I
 H=2?VAR(I[T])-1
END

Homespring, 50 bytes
youth. fountain bear 1 pump heads    -1 pump tails

very simple, make the input salmon young, block him after he enters the right branch so he spawns early, then bear eats the downstream input salmon

What does make the input salmon young mean?

Could you add a tio link so others can easily verify the solution?

@EmbodimentofIgnorance, bears eat all mature salmon, so without making the input salmon young it would be eaten by the bear before it has a chance to spawn. This way it can slip past the bear, but matures again after spawning.

@FrownyFrog, tio doesn't appear to be entering the input properly. I tried a small sample program, bird, which should return the input, but didnt get any output. I doubt i'll use homespring again but maybe i'll throw up an online interpreter if i cant find one

Commodore BASIC (PET, VIC-20, C64/128, C16/+4, TheC64Mini) 44 Tokenized and BASIC bytes
 0b$="heads":inputa$:?-1*(b$=a$)+1*(a$<>b$)

Commodore BASIC returns -1 as TRUE and 0 as FALSE, so a bit of simple maths is required to output the right required answer here.

Zsh, 25 19 bytes
-5 bytes using @Digital Trauma's bash solution; get the second letter, either e or a. Then 0xe and 0xa are interpreted as hex, i.e. decimal 14 and 10. Then we do a bit of arithmetic to output 1 or -1.
Try it Online!
<<<$[0x${1[2]}/2-6]

24 bytes:
<<<${1[1]:s/h//:s/t/-/}1
25 bytes:
<<<${1[1]:s/h/1/:s/t/-1/}

I need to stop following you around... 13 bytes

Perl 5 -p, 10 bytes
$_=o cmp$_

Try it online!

Old I know, but 7 bytes with flag abuse: https://tio.run/##K0gtyjH9/18l3tbBTdfo//@M1MSUYq6SxMyc4n/5BSWZ@XnF/3ULctw0MjQB

Java (JDK), 18 bytes
i->i=="heads"?1:-1

Try it online!

Welcome! This is a well-golfed solution but when the input is heads it only works when i is interned because of the reference comparison (==). For this reason strings are usually compared in Java using String#equals. Your TIO works because your inputs are string literals, but this approach doesn't work in general. I don't think assuming strings are interned/literal is typical on here, so you should probably make sure your solution doesn't rely on that.

@Jakob yeah, but it's 25 now...

True, but it works for any input, which is the most important thing. Now the question is can you find a shorter version? (I think you'll find there's a 17-byte solution).

@, 16 bytes
I will expand it later.
?-ň*8+94{1}{-1}

Explanation
?               If statement
 -ň             Subtract input with
   *8+94        The ASCII code of h
        {1}     If true, return 1
           {-1} Otherwise, return -1

05AB1E, 3 bytes
'ek

Try it online or verify both test cases.
Explanation:
'ek '# Get the 0-based index of "e" in the (implicit) input-string
     # (or -1 if no "e" is present)
     # (and output the result implicitly)

Gema, 7 characters
t=-
*=1

Generally the same thing as my Sed solution does, but there is a big difference: Sed executes all commands on the pattern space (so later commands act on previous command's result), while Gema handles each piece of input once and discards it.
So although in the 1st step Gema's t=- does the same as Sed's s/t/-/, in the 2nd step Gema's *=1 will act either on “ails” or “heads”, while Sed's s/\w\+/1/ has to handle either “-ails” or “heads”.
Sample run:
bash-5.0$ gema 't=-;*=1' <<< 'heads'
1

bash-5.0$ gema 't=-;*=1' <<< 'tails'
-1

Try it online!

Zsh, 13 12 bytes
-1 from @Isaac
<<<$[#1%7-5]

Try it online!
Try it online!

man zshmisc, under Arithmetic Evaluation:

An  expression  of  the  form  ##x  where  x  is any character sequence such as a, ^A, or \M-\C-x gives the value of this character and an expression of the  form  #name  gives  the value  of  the first character of the contents of the parameter name.

Brain-Flak, 52 34 bytes
({}[{}()()()])({<{{}}>[()()]}()<>)

Output is the top element of the stack
-18 bytes thanks to Jo King
Try it with heads!
Try it with tails!

34 bytes. Try to combine consecutive pops and pushes, especially in that first section

Oh wow, could you make an explanation, since I don't really understand the second part?

Explanation plus another byte saved in the loop

C-INTERCAL, 177 bytes
This is my first, and hopefully last, INTERCAL program. INTERCAL is a truly remarkable language. Those who haven't heard of it should immediately investigate (here is the manual I used).
PLEASEDO,1<-#2PLEASEDOWRITEIN,1PLEASEDO.1<-',1SUB#1'~#4DO(2)NEXTDO,1SUB#1<-#76(1)DO,1SUB#2<-#40(2)DO(3)NEXTDO,1<-#1DO,1SUB#1<-#116DOCOMEFROM(1)DOREADOUT,1(3)DOFORGET.1DORESUME#1

The program reads from standard input and writes to standard output. After printing the appropriate string, the program crashes with one of two humorous error messages depending on the input.
Try It Online
Ungolfed
    PLEASE DO ,1 <- #2
    PLEASE DO WRITE IN ,1
    PLEASE DO .1 <- ',1 SUB #1' ~ #4
    DO (2) NEXT
    DO ,1 SUB #1 <- #76
(1) DO ,1 SUB #2 <- #40
(2) DO (3) NEXT
    DO ,1 <- #1
    DO ,1 SUB #1 <- #116
    DO COME FROM (1)
    DO READ OUT ,1
(3) DO FORGET .1
    DO RESUME #1

Well, that didn't help much...
In the first three lines, we read 2 (#2 in INTERCAL) characters from the input into array ,1 and store in variable .1 whether the first character read has bit 2 set (mask of 4); in ASCII h is 0b1101000 and t is 0b1110100, so this variable now indicates whether the input is tails. This uses the "select" operator ~, which in this case performs both masking and shifting to select bit 2 as 0 or 1.
The rest of the program is an if/else conditional and a print statement. Unfortunately, control flow is very limited in INTERCAL. The only mechanism is a call stack that's pushed to when the program executes DO (x) NEXT. DO RESUME #1 then operates like a return statement (but with no return value), popping the stack and jumping to the next statement after the most recent DO (x) NEXT. But the value passed to DO RESUME can be any number. DO RESUME #3 pops the call stack three times and jumps to the third-from-last DO NEXT.
A similar construct is DO FORGET, which only pops the stack the specified number of times but does not jump. DO RESUME always jumps, so passing it 0 is a run-time error. But the instruction DO FORGET #0 is valid, and doesn't do anything.
And so with the statements DO (2) NEXT and DO (3) NEXT I push two locations onto the call stack. At (3) I then discard .1 frames, which has the effect of "forgetting" the call at (2) if and only if the input was tails. As a result, we end up just after either DO (2) NEXT or DO (3) NEXT after the return on the last line, depending on the input.
Each branch then loads the appropriate character data into ,1 (see here for why the values don't make any sense), and COME FROM (1), an inverted goto, joins the two branches at the output statement DO READ OUT. Control then continues, but luckily in either case the program crashes before printing anything else.

JavaScript, 14 bytes
s=>s.search`e`

Try it online!

J, 8 6 bytes
2-2{/:

Same approach as FrownyFrog's APL answer. -2 thanks to Bubbler
Attempt This Online!
2-2{/:
    /:  NB. grade up
  2{    NB. take the third item
2-      NB. subtract from 2

2-2{/: is the more direct translation.

Oh. I've got egg on my face. I thought i. was happening...

Python 3, 18 bytes
print(i.find("e"))

str.find returns -1 if it can't find the required character. In heads, e is in position 1 (Python is 0-indexed), whereas in tails it doesn't exist.

Befunge, 28 bytes
28 bytes including whitespace and newlines:
<v"heads"
 >94+%v
,,"-1"_1.@

Assumes that either heads or tails is put into the string above (this is the equivalent of assuming the input is stored in i). Works by performing modulo 13 on the top character on the stack - h divides exactly, t does not.
I also made a 22 character version (excluding whitespace/newlines) but the input has to be backwards:
"sdaeh"v
       9
       4
       +
       %
@,,"-1"_1.

You can make this code shorted by using d instead of 94+ to get the number 13.

Unefunge 98, 15 or 16 bytes
'h-4j@.-1_1.@

The above code assumes input is stored on top os the stack in reverse order. There are two 16-byte solutions that don't make this assumption:
$'d-4j@.-1_1.@

Assuming input is on top of the stack in normal order.
~'h-4j@.-1_1.@

Reading input from stdin

R, 58 55 bytes
for(i in scan(,''))print(`if`(utf8ToInt(i)[1]%%8,-1,1))

Try it online!
Really poor attempt, but I the utf8ToInt values for "h","H","t","T" are 104, 72, 116, 84 respectively. As a result, "h" and "H" values are both evenly divisible by 8, while "t" and "T" are not. So a conversion and check for even divisibility yields the desired results.
This method compared to the following method takes different spellings of heads/Heads/HEADS/etc. and tails/Tails/TAILS/etc. As long as it starts with an h/H or t/T it will work properly.
EDIT: -3 bytes switching to a for loop. Prints each value on newline instead of a single array of 1's and -1's.
R, 49 bytes
for(i in scan(,''))print(ifelse(i=="heads",1,-1))

This method was suggested by @user5957401 and is much simpler. The difference here is that this method assumes that the user will input strictly "heads" or "tails" (technically anything but "heads").
Try it online!

ifelse(i=="heads",1,-1) seems like a quicker way to vectorize

That's pretty simple actually, I don't know why I didn't think of that. I'll add yours in.

><>, 9 bytes
ab*i-6,n;

Try it online!
I'm honestly surprised that there wasn't a fish answer yet.
Subtracts the ASCII value of the first character input from 110 and divides by 6.

brainfuck, 42 bytes
,>,+++[-<->]<[-[->+++<]>.>]-[>+<-----]>--.

Try it online!
Checks if it is heads or tails by checking if the ordinal values of first two characters are only three away from each other.

MathGolf, 3 bytes
'e=

Try it online!
Basically identical to a lot of other solutions. Checks the index of 'e', and returns -1 if not found.

JavaScript (V8) - 19 Bytes
Since OPs solution returns 'true' and '-1' (see here), the following function:
f=i=>i[0]=='h'?1:-1

returns '1' and '-1' - see here. Just to be a smart-ass and so.
// Adaption of Java (SDK) version as a JS function.

Runic Enchantments, 10 bytes
1i3%1C=?Z@

Try it online! (heads)
Try it online! (tails)
Works by determining if the 4th character is a d (compare to number literal 100) and if not, multiplies a 1 by -1, then prints and terminates.
1              Push 1 (the output)
  i            Read input string
   3%          Get 4th character (0-indexed)
     1C=?      Compare with 100 (decimal value of d)
         Z     If false, multiply TOS with -1
          @    Output entire stack (the only thing left with be a 1 or -1) and terminate

Whitespace, 40 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_input_as_character][T   T   T   _Retrieve][S S S T  T   T   N
_Push_7][T  S T T   _Modulo][S S S T    S T N
_Push_5][T  S S T   _Subtract][T    N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Since Whitespace inputs one character at a time, I use that to my advantage here by only looking at the first character and porting @recursive's Stax answer (so make sure to upvote him as well!)
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Integer c = STDIN as character code-point
c = c % 7
c = c - 5
Print c to STDOUT as integer

33, 12 bytes
P110mz6dzcmo

Try it online!
Requires heads or tails non-capitalised.
This only accepts the first character of the input. If it needs to accept all input, replace the P with Ij.
Explanation
P            | Get the first character of input as its ASCII value
             |              ( h | t )
 110mz       | Subtract 110 (-6 | 6 )
      6dz    | Divide by 6  (-1 | 1 )
         cm  | Flip sign    ( 1 |-1 )
           o | Print it

jq, 14 characters
index("e")//-1

That's searching character position in the string. Unfortunately on not found it returns null, so the // (alternative operator) has to be used. (Still shorter than an .[:1]<"i" check as that results boolean and there is no way to cast that to integer.)
Sample run:
bash-5.0$ jq -R 'index("e")//-1' <<< 'heads'
1

bash-5.0$ jq -R 'index("e")//-1' <<< 'tails'
-1

Try it online!

Vyxal, 8 bytes
`e`c[1|u

Try it Online!
u is -1.

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


text:
Plus one sheep minus one sheep
Once upon a time long long ago... when there was no money or stocks yet, people were trading sheep. Even before (but close to) the invention of abacus, the great-grandfather of Warren Buffet decided it was hard to keep track of sheep. He wanted to collect all his belongings and clear all his debt, so that he could invest in a new counting machine he heard that his friend, great-grandfather of Bill Gates was building from sticks and beads. All his trades were atomic i.e. he was either supposed to give exactly one sheep to someone or get exactly one sheep. Of course Grandpa Buffet has more sheep to get then to give. Actually he exactly had 749 sheep to collect and he owed 250 sheep, so he was up by 499 sheep. Because of that he built a barn exactly for 499 sheep beforehand. Then he called all 999 people and told them to get into a queue. The very first man, wanted his sheep but there was no sheep in the barn yet. He didn't like this order and wanted everyone to get in order again but first the givers and then the collectors now. At the 500th men there were no space for new sheep in the barn but there were still 250 to collect before starting to give. He gave all the collected sheep back and make them get in a queue again and went to Grandpa Gates to help him ordering. Somehow they figured out and with the help of 499 sheep, they built a lot of Abacus and lived happily ever after.
Years later, yesterday Bill Gates and Warren Buffet met in a Giving Pledge meeting. They told this story and laughed a lot. Then Gates told Buffet: "You know what, I don't know how my great-grandpa ordered 999 people but I know there are so many ways. Actually I can tell you how many if you let me...". Then he went to his room to write a code to calculate the number of possible orderings that always guarantee there is always sheep or space in the barn until the queue is empty. And he did so but being Bill Gates he has written a recursive function which solves the problem correctly but slowly. So everybody still waits for his answer. Buffet is bored, can you write a better and faster function?
p = 749
n = 250
orderings(p,n) = ?

Shortest code wins, but it must finish in minutes, not hours or days.

Thanks for the challenge. For questions on this site, an objective winning conditions is required. It seems like some combination of short code and low runtime is required, but you should make it specific.

Any code that can solve this problem for given values should be good as it is calculating instead of counting. Otherwise, an algorithm that tries to count would never end for combination(999,250) = 361713029387773775435372891749922395099728363852766445058516124309371608811061565063360358477711651559664410648010377363865113901777290418162699620613880083274233922126850199373014270598629359178877646230097380575431434538474979162651084932896 number of trials, I guess. So objective for code is to give a result for 749 and 250

Alright, how about putting that in the problem statement. Something like Shortest code wins, but it must finish in minutes, not hours or days.

Wouldn't the easiest ordering be 499p 250n 250p?

@JerryJeremiah Sure, that would be one of the different ways (it's the easiest). This question asks about the number of different ways. You could also do 400p 250n 349p or even 1p 1n 1p 1n ... 1n 499p. How many such ways are there?

This sounds like Catalan numbers, although it isn't. I wonder if an elegant analytical solution is possible.

Questions that are in paragraph format also don't do so well here, try to break your rules up into bullets. That way we don't have to dissect what's relevant.

I'm not reading that wall of text. Just get to the point with the specs.

Also, with time constraints you must specify a computer to test them on. Most programs will run in second with 10^30 FLOPS.

Pyth, 33 bytes
M?+&<HGgtGH&+-499GHgGtHH1g749 250

Try it online: Pyth Compiler/Executor. Takes about 3 seconds on my laptop. The online compiler is a bit slower, but also computes the answer in about 15 seconds.
The answer is:
160547283350099323317963999889002394629262478407796913030854915361460989263675794524349914992326520887556329626280682363011590724268659750627030457440692447081328860242720905181098211539560301455338502543318855115593179999323115473879753632000

Explanation:
First some pseudo-code of the recursive function. This is quite easy to write.
function g(p, n):
   if (p > 0 and n > 0):
      count = 0
      if (occupied_places_in_barn < 499):
         count += g(p-1, n)
      if (occupied_places_in_barn > 0):
         count += g(p, n-1)
      return count
   else:
      return 1 # only one way possible

And the Pyth translation:
M                                  def g(G,H): return _
    <HG                               H < G
   &   gtGH                                 and g(G-1,H)
            +-499GH                   499-G+H
           &       gGtH                       and g(G,H-1)
  +                                   return sum of these two numbers
 ?                     H1             if H else 1
                         g749 250  call g(749,250) and print

Why is this recursive code so fast? Doesn't the function g iterate over all 1.6*10^199 possibilities?
No it doesn't. The key here is dynamic programming. We store known results in a cache and lookup the results, when we call the function with the same parameters again. One really cool feature of Python is the @lru_cache decorator, which does all the work for you. No need to manually generate such a cache and handle stuff like lookup, storing results, ... And in Pyth it's even simpler, since each function automatically uses such a cache. So in total the function g gets executed only 125499 times. Way less than 1.6*10^199 times.


text:
Normalise my decision map
Write a function or program that processes a block of text and returns the new text. Smallest valid program wins.
Each line in the block of text will have the following format:
12:34,56

The first number is the line ID, the other two comma separated numbers are references to other lines.
In the input text the numbers can be any integer greater than or equal to 0. All numbers will be in ASCII encoded decimal with no leading zeros. There will be no duplicate line IDs. There will be no references to non-existent line IDs, although there may be line IDs that are not referenced.
In the output text the lowest numbered line will be moved to the start of the text block and renumbered to 0. Any references to this line must be updated too. The first reference on that line must be 0 or 1. The second reference can only be 2 if the first reference is 1. Otherwise it must be 0 or 1.
All the lines must be in ascending, incrementing order (no skipped numbers). You can only have a reference to line n if there has been a previous reference to line n-1 or the current line ID is n. There must be no lines that are not referenced by lower line IDs except for line 0. Any such lines must be removed before the final output.
You may assume that the input text is always in the correct format.
Test input #1:
45:73,24
78:24,78
89:24,73
73:45,3
72:3,24
3:24,24
24:3,89

Reordered:
3:24,24
24:3,89
89:24,73
73:45,3
45:73,24
78:24,78
72:3,24

Renumbered:
0:1,1
1:0,2
2:1,3
3:4,0
4:3,1
78:1,78
72:0,1

Unreferenced lines removed for final output:
0:1,1
1:0,2
2:1,3
3:4,0
4:3,1

Of course, your program doesn't have to follow this order, just produce the correct output. The output must be a single block of text or the closest equivalent in your language, i.e. no character by character direct output. You may either return it (preferred) or output the whole block directly. Assume your output will be passed to another function or program.
Test input #2
5:2,3
7:3,2
2:4,2
4:2,3
3:4,3

Output:
0:1,0
1:0,2
2:1,2

Test input #3
7:6,3
3:9,7
9:7,3
2:9,6
6:6,7

Output:
0:1,2
1:3,4
2:2,3
3:2,4
4:1,3

Python 3, 226 215 211 209 179 bytes
def f(s):
 S=dict(map(eval,i.split(":"))for i in s.split("\n"));r="";L=[min(S)];i=0
 while L[i:]:a=S[L[i]];L+=set(a)-set(L);r+="%%d:%d,%d\n"%tuple(map(L.index,a))%i;i+=1
 return r

Try it online!


text:
Mixing characters in a string
You have to write a function/program that takes input via the stdin/command-line arguments/function arguments, mixes up characters in a string, and then output the final string via the stdout.
Input will first contain a string (not empty or null), a space, and then an even number of non-negative numbers all separated by spaces. If input is taken via function arguments, the string will be the one of the arguments while the integers, which are seperated by a space, will be the other. You must swap the characters of the string at the indices corresponding to consecutive pairs of numbers.
For instance:
Hello_world! 0 6

must result in
wello_Horld!

Assumptions

You may choose between 0-based and 1-based indexing, and may assume that the given indexes will always be in range.
The string will not be longer than 100 characters and will only contain ASCII characters in range ! to ~ (character codes 0x21 to 0x7E, inclusive). See ASCII table for reference.
The two indices in a pair may be identical (in which case, nothing is swapped in that step).

Scoring
This is code golf, so the shortest submission (in bytes) wins.
Test Cases
Hello_world! 0 6 => wello_Horld!
First 1 2 1 0 0 4 => tFisr
(Second!$$) 8 7 10 1 => ()econd$!$S
~Third~ 0 0 6 6 0 6 6 0 => ~Third~

For future challenges, let me recommend the sandbox where you can get feedback and polish your challenge before posting it on main (this minimises the risk of invalidating existing answers if someone discovers a serious flaw in your challenge that needs fixing).

Why require input on stdin, and not, e.g., as command line arguments?

@lrn , Right. Added 2 more options.

I see a bunch of solutions below that assume that they can get the list of indices as an array that gets passed into the function they implement. The way I read your definition, the input is a single string, which contains the indices as well as the string they operate on, and extracting the indices from the input string is part of the code that needs to be golfed. Can you clarify which interpretation is correct?

@RetoKoradi , No. Input is not a full string. It has a string, and then numbers. The numbers are not included in the string.

That contradicts the definition in your question, at least the way I read it: "Input will first contain a string, a space, and then an even number of non-negative numbers all separated by spaces." Particularly the "separated by spaces" suggests that the original input is all one sequence of characters that needs to be parsed. It doesn't say anywhere that you can assume to get an integer array as input to your code.

@RetoKoradi , I edited the post.

CJam, 11 bytes
rr{irie\r}h

How it works
This is a slightly different approach, in which I simply run a do-while loop till I have pairs of numbers left in the input.
r                 e# Read the first string
 r                e# Read the first number of the first number pair in the input
  {      }h       e# Do a do-while loop
   i              e# Convert the first number from the pair to integer
    ri            e# Read the second number from the pair and convert to intger
      e\          e# String X Y e\ works by swapping the Xth index with the Yth index in the
                  e# String
        r         e# This is our exit condition of the do-while loop. If we still have
                  e# a number on the input left, that means there are more pairs to swap.
                  e# Otherwise, we exit the loop and the result is printed automatically

Try it online here

Python 3, 89 86 bytes
[*s],*L=input().split()
while L:a,b,*L=map(int,L);s[a],s[b]=s[b],s[a]
print(*s,sep="")

Unpack all the things. (3 bytes saved thanks to @potato)

Save a few bytes and do this:
[*s],*L=input().split()
you can then take the line after it away.
I really like your solution btw, it's almost elegant even though it is very golfed.

@potato Oh wow, I didn't know you could have two unpacks together like that (I thought you could only do that in 3.5). Thanks!

CJam, 13 bytes
r[q~]2/{~e\}/

Test it here.
Explanation
r             e# Read the first token, i.e. the string.
 [q~]         e# Read the rest of the input, eval it and wrap it in an array.
     2/       e# Split the array into pairs of consecutive elements.
       {   }/ e# For each pair.
        ~     e# Unwrap the array.
         e\   e# Swap the corresponding elements in the string.

Whoa. Did not expect an answer that fast!

C (137 b)
f(char*T,int*V,int L){int C=0;for(int j=0;j<strlen(T);C=++j){for(int i=L-1;i+1;i--)if(C==V[i]){C=V[i-i%2*2+1];i-=i%2;}printf("%c",T[C]);}}

Explanation is coming ...
Arguments
T = a word of type char*.
V = an array of an even number of integer elements.
L = length of V
Output
mixed string
How does it work ?:
sweeps numbers of array V vice versa , and puts the nth element of the string after tracking all its progress until the actual point . Example
input= T="First" , V={1,2,1,0,0,4}
V inversed={4,0,0,1,2,1}
V[0] = 4th element -> index 0
0 -> 1
1->2

4th element 't' receives the second = 'r'

V[1] = 0 -> index 4
4 isnt mentionned after so , no changes

0 element='F' receives the fourth= 't'

V[3] = 1st element -> index 0
no changes

V[4] = 2 -> index 1
no changes after ..

Try it here

@Agawa001 , You can golf this a lot more. Return type int is not needed(may result in unexpected behavior), and int variables which are parameters do not need an int, variables, instead of declaring in the loop can be declared in one place outside the loop, use putchar instead of printf etc

Python 3 - 161 149
import sys
t=sys.stdin.read().split()
q=list(t[0])
c=1
i=int
while c<len(t):n=q;a=i(t[c]);b=i(t[c+1]);n[a]=q[b];n[b]=q[a];q=n;c+=2;
print(''.join(q))

Golfed more by swapping around some variables, and using ; as in Tim's comment.
I expected it to come out looking golfed, just not this much.

You can golf this a lot. Change the while to while c<len(t):line1;line2;line3.... c=c+2 goes to c+=2

@Tim Thanks for your help!

Shouldn't c start at 0?

@Tim Nope. c actually is indexing t (the input) to get the positions we need to swap. But since t[0] is the string we need to swap around, t[1] and t[2] hold the first pair of swaps.

Ahh I see, yes. Sorry, my solution split off the input, so i guessed you'd done the same :)

C, 109 107 102 bytes
i;f(l){l=sizeof(a)/sizeof(*a);char t;for(;i<l;i+=2){t=s[a[i]];s[a[i]]=s[a[i+1]];s[a[i+1]]=t;}puts(s);}

Note: s and a needs to be declared as global arrays. s is the string which you want to swap and a is an array of int with all the number values.
If the above code does not work, try using void f(){...} instead of f(){...}
Ungolfed code:
int a[]={1, 2, 1, 0, 0, 4};//Integer elements
char s[]="First";          //String to be swapped

i; //Auto initialized to 0 and defaults to type int
void f(l){ //Variables defaults to type int
  l=sizeof(a)/sizeof(*a); //Gets number of elements in array a
  char t;

  for(;i<l;i+=2){

    t=s[a[i]];
    s[a[i]]=s[a[i+1]];
    s[a[i+1]]=t;  //Swap each character

  }

  puts(s); //Print the final char array
}

Test it here

hmm ur code is smaller :)

lol where is variable declaration ? thats a cheaty way to tighten ur code :p

@Agawa001 , I didn't include the variable declaration as the bytes would vary with each test case.

This does not match the input as defined in the problem. The input is a single string. Unless I completely misunderstood the problem, you need to extract the index values from the input string.

Dart - 123
Assumes input on the command-line is automatically split at spaces. Otherwise it needs an initial x=x[0].split(' '); to split the string into text and indices.
main(x,{c,i:1,a,t}){c=x[0].split("");n()=>a=int.parse(x[i++]);for(;i<x.length;t=c[n()],c[a]=c[n()],c[a]=t);print(c.join());}

With more whitespace:
main(x,{c,i:1,a,t}){
  c=x[0].split("");
  n()=>a=int.parse(x[i++]);
  for(;i<x.length;t=c[n()],c[a]=c[n()],c[a]=t);
  print(c.join());
}

Run/test this on dartpad.dartlang.org.

Do you know of any online compilers where I could test this?

Add link to DartPad.

C, 70 bytes
Given that the input string is at most length 100 I decided to make the 'NULL' byte indicating the end of the integer array be the unambiguous 0xFF. Presumably this doesn't count as extra input, though for a cost of (at most) 7 3 bytes it can be made into 1-based indexing and use '\0' as the end of the array.
f(s,i,t)char*s,*i;{for(;~*i;)t=s[*i],s[*i]=s[*++i],s[*i++]=t;puts(s);}

Pretty much just does regular swapping with a tmp variable and uses that the comma operator introduces sequence points to have defined behaviour (unlike some manifestations of xor swaps that would have a lower character count but lead to undefined behaviour).
Edit: As requested you can test it out: http://rextester.com/OVOQ23313.

I don't think you can assume that you get an array with the indices to be swapped. The indices are part of the input string, and you need to parse them out of the string as part of the posted (and counted) code. From the description: "Input will first contain a string, a space, and then an even number of non-negative numbers all separated by spaces."

Rebol - 71
s: take i: split input" "foreach[a b]i[swap at s do a at s do b]print s

Ungolfed:
s: take i: split input " "
foreach [a b] i [swap at s do a at s do b]
print s

How do I test this? Is there any online compiler for testing this?

@CoolGuy - Yes you can test it at http://try.rebol.nl/     The input function won't be able to call STDIN from there.  The workaround is to simple set input to be the value you wish to test.  Here's full example of the first test - input: "hello_World 1 7" s: take i: split input" "foreach[a b]i[swap at s do a at s do b]print s   and click on Do in Rebol 3 NB. Rebol uses 1-based indexing.

@CoolGuy - Alternatively you can download Rebol 3 binaries from http://rebolsource.net/

Python 3, 135
x=input().split()
y=list(x[0])
z=[int(i)for i in x[1:]]
while z:p,c=y[z[0]],y[z[1]];y[z[0]],y[z[1]]=c,p;del z[0],z[0]
print(''.join(y))

Explanation:
x=input().split()         # Split the input into a list at each space
y=list(x[0])              # First item in list (the word) into a list of chars
z=[int(i)for i in x[1:]]  # Make the list of numbers, into integers
while z:                  # Loop untill the list z is empty
    p,c=y[z[0]],y[z[1]]   # Assign p to the first char and c to the second
    y[z[0]],y[z[1]]=c,p   # Swap around using p and c
    del z[0],z[0]         # Remove the first 2 items in the list of integers
print(''.join(y))         # Print out the altered list as a string

C, 143 bytes
main(a,v,i)char** v;{i=2;char s[101],t;strcpy(s,v[1]);for(;i<a;i+=2){t=s[atoi(v[i])];s[atoi(v[i])]=s[atoi(v[i+1])];s[atoi(v[i+1])]=t;}puts(s);}

The above program takes input from command-line arguments, copies the string into an array, swaps corresponding characters and then, outputs the modified string.
Ungolfed code:
main(int a,char** v,int i){ //Arguments of main
  i = 2;
  char s[101],t;

  strcpy(s,v[1]); //Copy string literal into an array

  for(;i<a;i+=2){
    t=s[atoi(v[i])];
    s[atoi(v[i])]=s[atoi(v[i+1])];
    s[atoi(v[i+1])]=t;  //Swap each character
  }

  puts(s); // Output the final string
}

Are you assuming that the numbers have only one digit? Considering that the input can be up to 100 characters, I don't think that will be valid. Also look at the 3rd example, which has 10 as one of the indices.

@RetoKoradi , Thanks for spotting that. I fixed the code.

JavaScript (ES6), 95
95 bytes with a single string input (function f below)
75 bytes with 2 parameters, string and number array (function g below)
(EcmaScript 6, Firefox only)

f=i=>
(
  n=i.split(' '),
  s=[...n.shift()],
  n.map((v,i)=>i&1?[s[v],s[w]]=[s[w],s[v]]:w=v),
  s.join('')
)

g=(s,n)=>
  n.map((v,i)=>i&1?[s[v],s[w]]=[s[w],s[v]]:w=v,s=[...s])
  &&s.join('')

// TEST
out=x=>O.innerHTML+=x+'\n'

;[['Hello_world! 0 6', 'wello_Horld!']
,['First 1 2 1 0 0 4','tFisr']
,['(Second!$$) 8 7 10 1','()econd$!$S']
,['~Third~ 0 0 6 6 0 6 6 0','~Third~']]
.forEach(t=>{
  u=f(t[0]),
  ok=u==t[1],
  out('Test '+(ok?'OK: ':'FAIL: ')+t[0]+'\n Result:' +u + '\n Check: '+t[1]+'\n')
})

Vyxal, 11 bytes
$⌈⌊2ẇ(n~İṘȦ

Try it Online!
7 bytes by taking the string and then a list of lists of the indices to swap
Explained
$⌈⌊2ẇ(n~İṘȦ
$⌈           # Push the numbers split on spaces then the string.
  ⌊2ẇ        # eval each number in the rest and wrap into lists of size 2
     (       # to each pair:
      n~İ    #   without popping anything, index the pair into the string
         Ṙ   #   reverse that
          Ȧ  #   assign back to the string, vectorises


text:
Searching for a sum
In this challenge you will take two inputs
One input will be a string of numbers of any length which you will put into an array/table/whatever you call it in your language
Ex:
10 10 145 20 53 102 20

Would become
arraynameofyourchoice = {10, 10, 145, 20, 53, 102, 20}

You can assume the input will have spaces in between each number and no newlines.
The second input will be our sum, which will be a number
Ex:
165

Your challenge is to make a script that will search through your array and find every possible way to get 165 by adding numbers in the array. You can output your code in any way that clearly shows what numbers you are adding.
So in our example the output would be:
10, 10, 145
145, 20
53, 102, 10

Because each of those sequences of numbers added together equal 165
Note that even though there are 2 twenties in the sequence we did not output
145, 20

twice. You can never have a repeated sequence.
Your code will take a +5 byte penalty if it does something like this:
145, 20
20, 145

This is fastest code challenge so fastest code wins! good luck!

If I changed this to a fastest code challenge would it still be a duplicate?

It's probably different then, but this needs some work to be a proper fastest code challenge. For a start the 5-byte penalty no longer makes sense. Furthermore, you'll have to run all submissions on your own machine, so that timings can be compared fairly. And lastly, you would have to include some large test sets that actually allow you to measure timings meaningfully.