text:
TuppenceValue *TuppenceValue_EMPTYWORD;
TuppenceValue *TuppenceValue_ZERO_1BIT;
TuppenceValue *TuppenceValue_ONE_1BIT;
TuppenceValue *TuppenceValue_ONE;
TuppenceValue *TuppenceValue_ZERO;
TuppenceValue *TuppenceValue_MINUS_ONE;
TuppenceValue *TuppenceValue_EMPTYLIST;

TuppenceValue *TuppenceValue_INFINITY;

TuppenceValue *TuppenceValue_PRINT;
TuppenceValue *TuppenceValue_EXIT;
TuppenceValue *TuppenceValue_RATIONALIZE;
TuppenceValue *TuppenceValue_SIZE;
TuppenceValue *TuppenceValue_TRANSIENT;
TuppenceValue *TuppenceValue_PERIOD;
TuppenceValue *TuppenceValue_NUMERATOR;
TuppenceValue *TuppenceValue_DENOMINATOR;

void Value_initialize() {
    FiniteWord_initialize();
    RationalWord_initialize();

    List_initialize();

    BuiltinSymbol_initialize();
    BuiltinFunction_initialize();

    TuppenceValue_EMPTYWORD = Value_createFromFiniteWord(FiniteWord_EMPTY);
    TuppenceValue_ZERO_1BIT = Value_createFromFiniteWord(FiniteWord_ZERO_1BIT);
    TuppenceValue_ONE_1BIT = Value_createFromFiniteWord(FiniteWord_ONE_1BIT);
    TuppenceValue_ONE = Value_createFromRationalWord(RationalWord_ONE);
    TuppenceValue_ZERO = Value_createFromRationalWord(RationalWord_ZERO);
    TuppenceValue_MINUS_ONE = Value_createFromRationalWord(RationalWord_MINUS_ONE);
    TuppenceValue_EMPTYLIST = Value_createFromList(List_EMPTY);

    TuppenceValue_INFINITY = Value_createFromBuiltinSymbol(BuiltinSymbol_INFINITY);

    TuppenceValue_PRINT = Value_createFromBuiltinFunction(BuiltinFunction_PRINT);
    TuppenceValue_EXIT = Value_createFromBuiltinFunction(BuiltinFunction_EXIT);
    TuppenceValue_RATIONALIZE = Value_createFromBuiltinFunction(BuiltinFunction_RATIONALIZE);
    TuppenceValue_SIZE = Value_createFromBuiltinFunction(BuiltinFunction_SIZE);
    TuppenceValue_TRANSIENT = Value_createFromBuiltinFunction(BuiltinFunction_TRANSIENT);
    TuppenceValue_PERIOD = Value_createFromBuiltinFunction(BuiltinFunction_PERIOD);
    TuppenceValue_NUMERATOR = Value_createFromBuiltinFunction(BuiltinFunction_NUMERATOR);
    TuppenceValue_DENOMINATOR = Value_createFromBuiltinFunction(BuiltinFunction_DENOMINATOR);
}

//TuppenceValue *Value_CreateBuiltinFunction(tuppence::PrototypeAST *Proto) {
//    copy XXX;
//    TuppenceValue *val = new TuppenceValue;
//    val->tag = TuppenceValueTag_FiniteWord;
//    val->builtin = Proto;
//    return val;
//}

 TuppenceValue *Value_createFromFiniteWord(FiniteWord *word) {
     TuppenceValue *val = new TuppenceValue;
     val->tag = FiniteWordTag;
     val->finite = FiniteWord_createFromFiniteWord(word);
     return val;
 }

 TuppenceValue *Value_createFromError(const char *msg) {
     TuppenceValue *val = new TuppenceValue;

     auto len = strlen(msg);
     auto printableMsg = new char[len+2+1];

     strncpy(printableMsg+1, msg, len);
     printableMsg[0] = '!';
     printableMsg[len+1] = '!';
     printableMsg[len+1+1] = '\0';

     val->tag = ErrorTag;
     val->error = printableMsg;
     return val;
 }

TuppenceValue *Value_createFromList(List *list) {
    TuppenceValue *val = new TuppenceValue;
    val->tag = ListTag;
    val->list = List_createFromList(list);
    return val;
}

TuppenceValue *Value_createFromRationalWord(RationalWord *rat) {
    TuppenceValue *val = new TuppenceValue;
    val->tag = RationalWordTag;
    val->rational = RationalWord_createFromRationalWord(rat);
    return val;
}

TuppenceValue *Value_createFromBuiltinSymbol(BuiltinSymbol *sym) {
    TuppenceValue *val = new TuppenceValue;
    val->tag = BuiltinSymbolTag;
    val->builtinSymbol = BuiltinSymbol_createFromBuiltinSymbol(sym);
    return val;
}

TuppenceValue *Value_createFromBuiltinFunction(BuiltinFunction *F) {
    TuppenceValue *val = new TuppenceValue;
    val->tag = BuiltinFunctionTag;
    val->builtinFunction = BuiltinFunction_createFromBuiltinFunction(F);
    return val;
}

TuppenceValue *Value_createFromValue(TuppenceValue *val) {
    switch (val->tag) {
        case FiniteWordTag:
            return Value_createFromFiniteWord(val->finite);
        case RationalWordTag:
            return Value_createFromRationalWord(val->rational);
        case ListTag:
            return Value_createFromList(val->list);
        case BuiltinFunctionTag:
            return Value_createFromBuiltinFunction(val->builtinFunction);
        default:
            assert(false);
    }
}

int Value_CreateString(TuppenceValue *val, char** str_p) {

    auto tag = val->tag;

    switch (tag) {
        case FiniteWordTag:
            FiniteWord_newString(val->finite, str_p);
            break;
        case RationalWordTag:
            RationalWord_newString(val->rational, str_p);
            break;
        case ListTag:
            List_newString(val->list, str_p);
            break;
        case ErrorTag:
            *str_p = val->error;
            break;
        case BuiltinSymbolTag:
            BuiltinSymbol_newString(val->builtinSymbol, str_p);
            break;
        case BuiltinFunctionTag:
            BuiltinFunction_newString(val->builtinFunction, str_p);
            break;
        default:
            llvm_unreachable("fallthrough");
    }

    return 0;
}

uint8_t Value_tag(TuppenceValue *Val) {
    return Val->tag;
}

//void Value_dump(TuppenceValue *Val) {
//    char *S;
//    Value_CreateString(Val, &S);
//    llvm::errs() << S << "\n";
//}

// void Value_ReleaseString(TuppenceValue val, char* str) {

//     auto tag = val.tag;
// //    auto payload = val.payload;

//     switch (tag) {
//         case TuppenceValueTag_FiniteWord:
//             FiniteWord_releaseString(str);
//             break;
//         default:
//             return;
//     }
// }

// void Value_ReleaseValue(TuppenceValue val) {

//     auto tag = val.tag;

//     switch (tag) {
//         case TuppenceValueTag_FiniteWord:
//             FiniteWord_release(val.finite);
//             break;
//         default:
//             return;
//     }
// }

std::string stringFromToken(char);

TuppenceValue *Value_Unary(char Op, TuppenceValue *OperandValue) {

    if (!OperandValue) {
        return nullptr;
    }

    // For arithmetic, bitwise, and structural operations, concatenate all lists together
    if (OperandValue->tag == ListTag) {
        auto ListOperand = OperandValue->list;
        auto Data = List_data(ListOperand);
        auto Size = List_size(ListOperand);
        OperandValue = List_concatenateArgs(Data, Size);
        if (!OperandValue) {
            return nullptr;
        }
    }

    switch (Op) {
    case '-': {
        if (OperandValue->tag == FiniteWordTag) {
            auto FiniteWordOperand = OperandValue->finite;
            return Value_createFromFiniteWord(FiniteWord_minus(FiniteWordOperand));
        }
        else if (OperandValue->tag == RationalWordTag) {
            auto RationalWordOperand = OperandValue->rational;
            return Value_createFromRationalWord(RationalWord_minus(RationalWordOperand));
        }

        {
            char *str;
            Value_CreateString(OperandValue, &str);
            return Value_createFromError((std::string("Invalid type for operator ") + stringFromToken(Op) + ": " + str).c_str());
        }
    }
    case tok_dot_dot_dot: {
        if (OperandValue->tag == FiniteWordTag) {
            auto FiniteWordOperand = OperandValue->finite;
            if (FiniteWord_size(FiniteWordOperand) == 0) {
                return Value_createFromFiniteWord(FiniteWord_EMPTY);
            }
            else {
                return Value_createFromRationalWord(RationalWord_createFromPeriodTransient(FiniteWordOperand, FiniteWord_EMPTY));
            }
        }

        {
            char *str;
            Value_CreateString(OperandValue, &str);
            return Value_createFromError((std::string("Invalid type for operator ") + stringFromToken(Op) + ": " + str).c_str());
        }
    }
    case '~': {
        if (OperandValue->tag == FiniteWordTag) {
            auto FiniteWordOperand = OperandValue->finite;
            return Value_createFromFiniteWord(FiniteWord_not(FiniteWordOperand));
        }
        else if (OperandValue->tag == RationalWordTag) {
            auto RationalWordOperand = OperandValue->rational;
            return Value_createFromRationalWord(RationalWord_not(RationalWordOperand));
        }

        {
            char *str;
            Value_CreateString(OperandValue, &str);
            return Value_createFromError((std::string("Invalid type for operator ") + stringFromToken(Op) + ": " + str).c_str());
        }
    }
    default:
            return Value_createFromError((std::string("Unary operator not found: ") + stringFromToken(Op)).c_str());
    }
}

TuppenceValue *Value_Binary(char Op, TuppenceValue *LL, TuppenceValue *RR) {

    TuppenceValue *LVal;
    TuppenceValue *RVal;
    // For arithmetic and bitwise operations, concatenate all lists together
    {
        if (LL->tag == ListTag) {
            auto ListVal = LL->list;
            auto Data = List_data(ListVal);
            auto Size = List_size(ListVal);
            auto FlatVal = List_concatenateArgs(Data, Size);
            if (FlatVal->tag == ErrorTag) {
                return FlatVal;
            }
            LVal = FlatVal;
        } else {
            LVal = LL;
        }

        if (RR->tag == ListTag) {
            auto ListVal = RR->list;
            auto Data = List_data(ListVal);
            auto Size = List_size(ListVal);
            auto FlatVal = List_concatenateArgs(Data, Size);
            if (FlatVal->tag == ErrorTag) {
                return FlatVal;
            }
            RVal = FlatVal;
        } else {
            RVal = RR;
        }
    }

    switch (Op) {
        case tok_percent_percent: {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *str;
                        Value_CreateString(RVal, &str);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + str).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    return Value_createFromFiniteWord(RationalWord_residue(RationalWordL, i));
                } else if (RVal->tag == BuiltinSymbolTag) {
                    auto BuiltinSymbolR = RVal->builtinSymbol;
                    if (BuiltinSymbol_same(BuiltinSymbolR, BuiltinSymbol_INFINITY)) {
                        return LVal;
                    }
                }
            }
            else if (LVal->tag == FiniteWordTag) {
                auto FiniteWordL = LVal->finite;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *str;
                        Value_CreateString(RVal, &str);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + str).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    if (i > FiniteWord_size(FiniteWordL)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Requested residue is too large: ") + Lstr + " " + Rstr).c_str());
                    }
                    return Value_createFromFiniteWord(FiniteWord_residue(FiniteWordL, i));
                }
                else if (RVal->tag == BuiltinSymbolTag) {
                    auto BuiltinSymbolR = RVal->builtinSymbol;
                    if (BuiltinSymbol_same(BuiltinSymbolR, BuiltinSymbol_INFINITY)) {
                        return LVal;
                    }
                }
            }

            {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Incorrect types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case tok_greater_greater: {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + Rstr).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    return Value_createFromRationalWord(RationalWord_shiftRight(RationalWordL, i));
                }
            }
            else if (LVal->tag == FiniteWordTag) {
                auto FiniteWordL = LVal->finite;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + Rstr).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    if (i > FiniteWord_size(FiniteWordL)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Requested shift is too large: ") + Lstr + " " + Rstr).c_str());
                    }
                    return Value_createFromFiniteWord(FiniteWord_shiftRight(FiniteWordL, i));
                }
            }

            {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Incorrect types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case tok_greater_percent: {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + Rstr).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    FiniteWord *Lo;
                    RationalWord *Hi;
                    RationalWord_shiftRightResidue(RationalWordL, i, &Hi, &Lo);
                    std::vector<TuppenceValue *> Vec;
                    Vec.push_back(Value_createFromFiniteWord(Lo));
                    Vec.push_back(Value_createFromRationalWord(Hi));
                    return Value_createFromList(List_createFromVals(&Vec[0], Vec.size()));
                }
            }
            else if (LVal->tag == FiniteWordTag) {
                auto FiniteWordL = LVal->finite;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (!RationalWord_isNonNegativeInteger(RationalWordR)) {
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected non-negative integer on RHS of ") + stringFromToken(Op) + ": " + Rstr).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordR);
                    if (i > FiniteWord_size(FiniteWordL)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Requested shift is too large: ") + Lstr + " " + Rstr).c_str());
                    }
                    FiniteWord *Lo;
                    FiniteWord *Hi;
                    FiniteWord_shiftRightResidue(FiniteWordL, i, &Hi, &Lo);

                    std::vector<TuppenceValue *> Vec;
                    Vec.push_back(Value_createFromFiniteWord(Lo));
                    Vec.push_back(Value_createFromFiniteWord(Hi));
                    return Value_createFromList(List_createFromVals(&Vec[0], Vec.size()));
                }
            }

            {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Incorrect types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case '-': {
            if (LVal->tag == FiniteWordTag) {
                auto FiniteWordL = LVal->finite;
                if (RVal->tag == FiniteWordTag) {
                    auto FiniteWordR = RVal->finite;
                    if (FiniteWord_size(FiniteWordL) != FiniteWord_size(FiniteWordR)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected same sizes for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                    }
                    if (FiniteWord_size(FiniteWordL) == 0) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected positive sizes for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                    }

                    std::vector<FiniteWord *> Args;
                    Args.push_back(FiniteWordR);
                    Args.push_back(FiniteWordL);

                    FiniteWord *Lo;
                    FiniteWord *Hi;
                    FiniteWord_arraySubtract(&Args[0], 2, &Hi, &Lo);

                    std::vector<TuppenceValue *> Vals;
                    Vals.push_back(Value_createFromFiniteWord(Lo));
                    Vals.push_back(Value_createFromFiniteWord(Hi));
                    return Value_createFromList(List_createFromVals(&Vals[0], Vals.size()));
                }
                else {
                    char *Lstr;
                    Value_CreateString(LVal, &Lstr);
                    char *Rstr;
                    Value_CreateString(RVal, &Rstr);
                    return Value_createFromError((std::string("Invalid types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                }
            }
            else if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    return Value_createFromRationalWord(RationalWord_subtract(RationalWordL, RationalWordR));
                }
                else {
                    char *Lstr;
                    Value_CreateString(LVal, &Lstr);
                    char *Rstr;
                    Value_CreateString(RVal, &Rstr);
                    return Value_createFromError((std::string("Invalid types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                }
            }
            else {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Invalid types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case '/': {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    if (FiniteWord_equal(RationalWord_residue(RationalWordR, 1), FiniteWord_ZERO_1BIT)) {
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Divisor cannot have 0 first bit for ") + stringFromToken(Op) + ": " + Rstr).c_str());
                    }
                    return Value_createFromRationalWord(RationalWord_divide(RationalWordL, RationalWordR));
                }
                else {
                    char *Lstr;
                    Value_CreateString(LVal, &Lstr);
                    char *Rstr;
                    Value_CreateString(RVal, &Rstr);
                    return Value_createFromError((std::string("Invalid types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                }
            }
            else {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Invalid types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case tok_star_star: {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == FiniteWordTag) {
                    auto FiniteWordR = RVal->finite;
                    if (!RationalWord_isNonNegativeInteger(RationalWordL)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        return Value_createFromError((std::string("Expected non-negative integer on LHS of ") + stringFromToken(Op) + ": " + Lstr).c_str());
                    }
                    auto i = RationalWord_integerValue(RationalWordL);
                    return Value_createFromFiniteWord(FiniteWord_createFromRepsWord(i, FiniteWordR));
                }
            } else if (LVal->tag == BuiltinSymbolTag) {
                auto BuiltinSymbolL = LVal->builtinSymbol;
                if (RVal->tag == FiniteWordTag) {
                    auto FiniteWordR = RVal->finite;
                    if (BuiltinSymbol_same(BuiltinSymbolL, BuiltinSymbol_INFINITY)) {
                        return Value_createFromRationalWord(RationalWord_createFromPeriodTransient(FiniteWordR, FiniteWord_EMPTY));
                    }
                }
            }

            {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Incorrect types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
        case tok_slash_percent: {
            if (LVal->tag == RationalWordTag) {
                auto RationalWordL = LVal->rational;
                if (RVal->tag == RationalWordTag) {
                    auto RationalWordR = RVal->rational;
                    RationalWord *Remainder;
                    RationalWord *Quotient;
                    RationalWord_quotientRemainder(RationalWordL, RationalWordR, &Quotient, &Remainder);

                    std::vector<TuppenceValue *> Vals;
                    Vals.push_back(Value_createFromRationalWord(Remainder));
                    Vals.push_back(Value_createFromRationalWord(Quotient));
                    return Value_createFromList(List_createFromVals(&Vals[0], Vals.size()));
                }
            } else if (LVal->tag == FiniteWordTag) {
                auto FiniteWordL = LVal->finite;
                if (RVal->tag == FiniteWordTag) {
                    auto FiniteWordR = RVal->finite;
                    if (FiniteWord_size(FiniteWordL) != FiniteWord_size(FiniteWordR)) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected same sizes for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                    }
                    if (FiniteWord_size(FiniteWordL) == 0) {
                        char *Lstr;
                        Value_CreateString(LVal, &Lstr);
                        char *Rstr;
                        Value_CreateString(RVal, &Rstr);
                        return Value_createFromError((std::string("Expected positive sizes for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
                    }
                    FiniteWord *Remainder;
                    FiniteWord *Quotient;
                    FiniteWord_udivrem(FiniteWordL, FiniteWordR, &Quotient, &Remainder);

                    std::vector<TuppenceValue *> Vals;
                    Vals.push_back(Value_createFromFiniteWord(Remainder));
                    Vals.push_back(Value_createFromFiniteWord(Quotient));
                    return Value_createFromList(List_createFromVals(&Vals[0], Vals.size()));
                }
            }

            {
                char *Lstr;
                Value_CreateString(LVal, &Lstr);
                char *Rstr;
                Value_CreateString(RVal, &Rstr);
                return Value_createFromError((std::string("Incorrect types for ") + stringFromToken(Op) + ": " + Lstr + " " + Rstr).c_str());
            }
        }
    default:
        {
            return Value_createFromError((std::string("Binary operator not found: ") + stringFromToken(Op)).c_str());
        }
    }
}

TuppenceValue *Value_Infix(char Op, TuppenceValue **Args, size_t Count) {

    std::vector<TuppenceValue *> Vals(Args, Args + Count);

    if (Op == tok_equal_equal || Op == tok_bang_equal) {
        // == and != operators are special, if any word values are present, then only consider
        // the first element of any lists
        // if all arguments are lists, then compare element-wise
        // functions are not comparable to anything

        // first determine if any are FiniteWords, and the necessary size
        auto finiteWordIsPresent(false);
        auto rationalWordIsPresent(false);
        size_t finiteWordSize(0);
        size_t listSize(0);
        for (auto& Val : Vals) {
            if (Val->tag == FiniteWordTag) {
                finiteWordIsPresent = true;
                // use first size that is encountered
                auto FiniteWordVal = Val->finite;
                finiteWordSize = FiniteWord_size(FiniteWordVal);
            }
            else if (Val->tag == RationalWordTag) {
                rationalWordIsPresent = true;
            }
            else if (Val->tag == ListTag) {
                auto ListVal = Val->list;
                listSize = List_size(ListVal);
            }
        }

        // if FiniteWords are present, then check sizes are correct
        // ensure only FiniteWords and RationalWords are present
        if (finiteWordIsPresent) {
            std::vector<FiniteWord *> FiniteWordVals;

            for (auto& Val : Vals) {
                if (Val->tag == FiniteWordTag) {
                    auto FiniteWordVal = Val->finite;
                    if (FiniteWord_size(FiniteWordVal) != finiteWordSize) {
                        char *str;
                        FiniteWord_newString(FiniteWordVal, &str);
                        std::string s = std::string(str);
//                        FiniteWord_releaseString(str);
                        return Value_createFromError((std::string("Incorrect size for ") + stringFromToken(Op) + ":" + s).c_str());
                    }
                    FiniteWordVals.push_back(FiniteWordVal);
                }
                else if (Val->tag == ListTag) {
                    auto ListVal = Val->list;
                    auto First = List_get(ListVal, 0);
                    if (First->tag == FiniteWordTag) {
                        auto FiniteWordVal = Val->finite;
                        if (FiniteWord_size(FiniteWordVal) != finiteWordSize) {
                            char *str;
                            FiniteWord_newString(FiniteWordVal, &str);
                            std::string s = std::string(str);
//                            FiniteWord_releaseString(str);
                            return Value_createFromError((std::string("Incorrect size for ") + stringFromToken(Op) + ":" + s).c_str());
                        }
                        FiniteWordVals.push_back(FiniteWordVal);
                    }
                }
                else {
                    char *str;
                    Value_CreateString(Val, &str);
                    std::string s = std::string(str);
//                    Value_ReleaseString(Val, str);
                    return Value_createFromError((std::string("Invalid type for ") + stringFromToken(Op) + ":" + s).c_str());
                }
            }

            switch (Op) {
                case tok_equal_equal:
                    if (FiniteWord_arrayEqual(&FiniteWordVals[0], FiniteWordVals.size())) {
                        return Value_createFromFiniteWord(FiniteWord_ONE_1BIT);
                    } else {
                        return Value_createFromFiniteWord(FiniteWord_ZERO_1BIT);
                    }
                case tok_bang_equal:
                    if (FiniteWord_arrayNotEqual(&FiniteWordVals[0], FiniteWordVals.size())) {
                        return Value_createFromFiniteWord(FiniteWord_ONE_1BIT);
                    } else {
                        return Value_createFromFiniteWord(FiniteWord_ZERO_1BIT);
                    }
                default:
                    llvm_unreachable("fallthrough");
            }
        }
        else if (rationalWordIsPresent) {
            std::vector<RationalWord *> RationalWordVals;

            // ensure only RationalWords are present
            for (auto& Val : Vals) {
                if (Val->tag == RationalWordTag) {
                    auto RationalWordVal = Val->rational;
                    RationalWordVals.push_back(RationalWordVal);
                }
                else if (Val->tag == ListTag) {
                    auto ListVal = Val->list;
                    auto First = List_get(ListVal, 0);
                    if (First->tag == RationalWordTag) {
                        auto RationalWordVal = First->rational;
                        RationalWordVals.push_back(RationalWordVal);
                    }
                }
                else {
                    char *str;
                    Value_CreateString(Val, &str);
                    std::string s = std::string(str);
//                    Value_ReleaseString(Val, str);
                    return Value_createFromError((std::string("Invalid type for ") + stringFromToken(Op) +":" + s).c_str());
                }
            }

            switch (Op) {
                case tok_equal_equal:
                    if (RationalWord_arrayEqual(&RationalWordVals[0], RationalWordVals.size())) {
                        return Value_createFromFiniteWord(FiniteWord_ONE_1BIT);
                    } else {
                        return Value_createFromFiniteWord(FiniteWord_ZERO_1BIT);
                    }
                case tok_bang_equal:
                    if (RationalWord_arrayNotEqual(&RationalWordVals[0], RationalWordVals.size())) {
                        return Value_createFromFiniteWord(FiniteWord_ONE_1BIT);
                    } else {
                        return Value_createFromFiniteWord(FiniteWord_ZERO_1BIT);
                    }
                default:
                    llvm_unreachable("fallthrough");
            }
        }
        else {
            // assume comparing lists element-wise
            std::vector<List *> ListVals;

            // ensure only Lists are present
            for (auto& Val : Vals) {
                if (Val->tag == ListTag) {
                    auto ListVal = Val->list;
                    if (List_size(ListVal) != listSize) {
                        char *str;
                        Value_CreateString(Val, &str);
                        std::string s = std::string(str);
//                        Value_ReleaseString(Val, str);
                        return Value_createFromError((std::string("Incorrect list size for ") + stringFromToken(Op) + ":" + s).c_str());
                    }
                    if (!List_isComparable(ListVal)) {
                        char *str;
                        Value_CreateString(Val, &str);
                        std::string s = std::string(str);
//                        Value_ReleaseString(Val, str);
                        return Value_createFromError((std::string("List contains non-comparable object: ") + s).c_str());
                    }
                    ListVals.push_back(ListVal);
                }
                else {
                    char *str;
                    Value_CreateString(Val, &str);
                    std::string s = std::string(str);
//                    Value_ReleaseString(Val, str);
                    return Value_createFromError((std::string("Invalid type for ") + stringFromToken(Op) + ":" + s).c_str());
                }
            }

            switch (Op) {
                case tok_equal_equal: return Value_createFromFiniteWord(List_arrayEqual(&ListVals[0], ListVals.size()));
                case tok_bang_equal: return Value_createFromFiniteWord(List_arrayNotEqual(&ListVals[0], ListVals.size()));
                default:
                    llvm_unreachable("fallthrough");
            }
        }
    }

    if (Op == '#') {

        if (Vals[0]->tag == FiniteWordTag) {
            return List_concatenateArgs(&Vals[0], Vals.size());
        } else if (Vals[0]->tag == ListTag) {
            return Value_createFromList(List_concatenateLists(&Vals[0], Vals.size()));
        } else {
            char *str;
            Value_CreateString(Vals[0], &str);
            std::string s = std::string(str);
            //                    Value_ReleaseString(Val, str);
            return Value_createFromError(std::string("Invalid type: " + s).c_str());
        }
    }

    // For arithmetic and bitwise operations, concatenate all lists together
    {
        std::vector<TuppenceValue *> FlattenedVals;
        for (decltype(Vals.size()) i = 0; i < Vals.size(); i++) {
            auto Val = Vals[i];
            if (Val->tag == ListTag) {
                auto ListVal = Val->list;
                auto Data = List_data(ListVal);
                auto Size = List_size(ListVal);
                auto FlatVal = List_concatenateArgs(Data, Size);
                if (FlatVal->tag == ErrorTag) {
                    return FlatVal;
                }
                FlattenedVals.push_back(FlatVal);
            }
            else {
                FlattenedVals.push_back(Val);
            }
        }
        Vals = FlattenedVals;
    }

    // Now, only remaining operators are those that cast to either FiniteWord or RationalWord

    if (Op == '+' ||
        Op == '*' ||
        Op == '|' ||
        Op == '&' ||
        Op == '^') {
        // first determine if any are FiniteWords, and the necessary size
        auto finiteWordIsPresent(false);
        auto rationalWordIsPresent(false);
        size_t finiteWordSize(0);
        for (auto& Val : Vals) {
            if (Val->tag == FiniteWordTag) {
                auto FiniteWordVal = Val->finite;
                finiteWordIsPresent = true;
                // use first size that is encountered
                finiteWordSize = FiniteWord_size(FiniteWordVal);
            }
            else if (Val->tag == RationalWordTag) {
                rationalWordIsPresent = true;
            }
        }

        // if FiniteWords are present, then check sizes are correct
        // ensure only FiniteWords and RationalWords are present
        if (finiteWordIsPresent) {
            std::vector<FiniteWord*> FiniteWordVals;

            for (auto& Val : Vals) {
                if (Val->tag == FiniteWordTag) {
                    auto FiniteWordVal = Val->finite;
                    if (FiniteWord_size(FiniteWordVal) != finiteWordSize) {
                        char *str;
                        Value_CreateString(Val, &str);
                        std::string s = std::string(str);
//                        Value_ReleaseString(Val, str);
                        return Value_createFromError(std::string("Expected FiniteWord with size " + std::to_string(finiteWordSize) +
                                        ", but found FiniteWord with size " + std::to_string(FiniteWord_size(FiniteWordVal)) +
                                        ": " + s).c_str());
                    }
                    FiniteWordVals.push_back(FiniteWordVal);
                }
                else if (Val->tag == RationalWordTag) {
                    auto RationalWordVal = Val->rational;
                    auto FiniteWordVal = RationalWord_residue(RationalWordVal, finiteWordSize);
                    FiniteWordVals.push_back(FiniteWordVal);
                }
                else {
                    char *str;
                    Value_CreateString(Val, &str);
                    std::string s = std::string(str);
//                    Value_ReleaseString(Val, str);
                    return Value_createFromError(std::string("Invalid type: " + s).c_str());
                }
            }

            switch (Op) {
                case '+': {
                    FiniteWord *Lo;
                    FiniteWord *Hi;
                    FiniteWord_arrayPlus(&FiniteWordVals[0], FiniteWordVals.size(), &Hi, &Lo);
                    std::vector<TuppenceValue *> Vals;
                    Vals.push_back(Value_createFromFiniteWord(Lo));
                    Vals.push_back(Value_createFromFiniteWord(Hi));
                    return Value_createFromList(List_createFromVals(&Vals[0], Vals.size()));
                }
                case '*': {
                    FiniteWord *Lo;
                    FiniteWord *Hi;
                    FiniteWord_arrayTimes(&FiniteWordVals[0], FiniteWordVals.size(), &Hi, &Lo);
                    std::vector<TuppenceValue *> Vals;
                    Vals.push_back(Value_createFromFiniteWord(Lo));
                    Vals.push_back(Value_createFromFiniteWord(Hi));
                    return Value_createFromList(List_createFromVals(&Vals[0], Vals.size()));
                }
                case '|': return Value_createFromFiniteWord(FiniteWord_arrayOr(&FiniteWordVals[0], FiniteWordVals.size()));
                case '&': return Value_createFromFiniteWord(FiniteWord_arrayAnd(&FiniteWordVals[0], FiniteWordVals.size()));
                case '^': return Value_createFromFiniteWord(FiniteWord_arrayXor(&FiniteWordVals[0], FiniteWordVals.size()));
                default:
                    llvm_unreachable("fallthrough");
            }
        }
        else if (rationalWordIsPresent) {
            std::vector<RationalWord *> RationalWordVals;

            // ensure only RationalWords are present
            for (auto& Val : Vals) {
                if (Val->tag == RationalWordTag) {
                    auto RationalWordVal = Val->rational;
                    RationalWordVals.push_back(RationalWordVal);
                }
                else {
                    char *str;
                    Value_CreateString(Val, &str);
                    std::string s = std::string(str);
//                    Value_ReleaseString(Val, str);
                    return Value_createFromError(std::string("Invalid type: " + s).c_str());
                }
            }

            switch (Op) {
                case '+': return Value_createFromRationalWord(RationalWord_arrayPlus(&RationalWordVals[0], RationalWordVals.size()));
                case '*': return Value_createFromRationalWord(RationalWord_arrayTimes(&RationalWordVals[0], RationalWordVals.size()));
                case '|': return Value_createFromRationalWord(RationalWord_arrayOr(&RationalWordVals[0], RationalWordVals.size()));
                case '&': return Value_createFromRationalWord(RationalWord_arrayAnd(&RationalWordVals[0], RationalWordVals.size()));
                case '^': return Value_createFromRationalWord(RationalWord_arrayXor(&RationalWordVals[0], RationalWordVals.size()));
                default:
                    llvm_unreachable("fallthrough");
            }
        }
        else {
            return Value_createFromError(std::string("Cannot operate on values").c_str());
        }
    }

    return Value_createFromError((std::string("Infix operator not found: ") + stringFromToken(Op)).c_str());

}

std::string stringFromToken(char Op) {
    switch (Op) {

            // properly escape for printing
        case '\n': return "'\\n'";

        case tok_eof: return "tok_eof";
        case tok_error: return "tok_error";

        case tok_define: return "tok_define";

        case tok_identifier: return "tok_identifier";
        case tok_integerword: return "tok_integerword";
        case tok_finiteword: return "tok_finiteword";

        case tok_if: return "tok_if";
        case tok_else: return "tok_else";
            //        case tok_for: return "tok_for";
        case tok_while: return "tok_while";

        case tok_equal_equal: return "==";
        case tok_percent_percent: return "%%";
        case tok_greater_greater: return ">>";
        case tok_greater_percent: return ">%";
        case tok_dot_dot_dot: return "...";
        case tok_bang_equal: return "!=";
        case tok_star_star: return "**";
        case tok_slash_percent: return "/%";

        default:
            if (Op < 0) {
                llvm::errs() << "Add this token: " << static_cast<int>(Op) << "\n";
                assert(false && "Add this token");
            }
            return std::string("'") + Op + "'";
    }
}


text:
package eu.socialSensor.diverseImages2014;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import eu.socialSensor.diverseImages2014.utils.Normalizations;

/**
 *
 * @author Eleftherios Spyromitros-Xioufis
 *
 */
public class MEDI2014Features {

	/** name of this class used in reflection */
	public static String CLASS_NAME = "MEDI2014Features";

	protected double[] CM; // Global Colour Moments
	protected double[] CN; // Global Colour Naming Histogram
	protected double[] CSD; // Global Colour Structure Descriptor
	protected double[] GLRLM; // Global Statistics on Gray Level Run Length Matrix
	protected double[] HOG; // Global Histogram of Oriented Gradients
	protected double[] LBP; // Global Locally Binary Patterns
	protected double[] CM3x3; // Spatial pyramid representation of above
	protected double[] CN3x3; // Spatial pyramid representation of above
	protected double[] GLRLM3x3; // Spatial pyramid representation of above
	protected double[] LBP3x3; // Spatial pyramid representation of above
	protected double[] CNN;
	protected double[] VLAD;

	// textual
	protected double[] FRANK;
	protected double[] FRANKN;
	protected double[] VIEWS;
	protected double[] VIEWSN;
	protected double[] COMMENTS;
	protected double[] COMMENTSN;
	protected double[] DISTANCE;
	protected double[] DISTANCEN;
	protected double[] GEO;
	protected double[] BOW10K;

	/**
	 * Parse a CSV file of a named class of attributes (name must match a field of this object)
	 *
	 * @throws Exception
	 * @throws
	 */
	public static HashMap<Long, double[]> parseFile(String rootDir, String locationName, String featureName,
			String normalization) throws Exception {
		HashMap<Long, double[]> allImagesFeatures = new HashMap<Long, double[]>();
		String filename = rootDir + "descvis" + File.separator + "img" + File.separator + locationName;
		if (!featureName.startsWith("_")) {// add a " " before the feature name
			filename += " " + featureName + ".csv";
		} else {
			filename += featureName + ".csv";
		}

		BufferedReader reader = new BufferedReader(new FileReader(filename));
		String line = null;
		double[] attrVals = null;
		while ((line = reader.readLine()) != null) {
			String[] parts = line.split(",");
			long id = Long.parseLong(parts[0]);// the first element is always the image id
			attrVals = new double[parts.length - 1];
			for (int i = 1; i < parts.length; i++) {
				double d = Double.parseDouble(parts[i]);
				attrVals[i - 1] = d;
			}

			// apply the appropriate normalization if needed
			attrVals = Normalizations.normalize(attrVals, normalization);

			allImagesFeatures.put(id, attrVals);
		}
		reader.close();
		return allImagesFeatures;
	}

	public static ArrayList<double[]> parseFileWiki(String rootDir, String locationName, String featureName,
			String normalization) throws Exception {
		ArrayList<double[]> allImagesFeatures = new ArrayList<double[]>();
		String filename = rootDir + "descvis" + File.separator + "imgwiki" + File.separator + locationName;
		if (!featureName.startsWith("_")) {// add a " " in the feature name
			filename += " " + featureName + ".csv";
		} else {
			filename += featureName + ".csv";
		}

		BufferedReader reader = new BufferedReader(new FileReader(filename));
		String line = null;
		double[] attrVals = null;
		while ((line = reader.readLine()) != null) {
			// if the wiki image name contains a comma, the 2nd element will not be a number!
			// count the number of leading not a number parts
			String[] parts = line.split(",");
			int partsToSkip = 0;
			if (parts[0].equals("wiki")) { // this is a Wikipedia image indicator
				partsToSkip = 1;
			} else { // count parts to skip
				for (int i = 0; i < parts.length; i++) {
					try {
						Double.parseDouble(parts[i]);
					} catch (NumberFormatException e) {
						partsToSkip++;
						continue;
					}
					break;
				}
			}
			// the partsToSkip first elements compose the image id
			// long id = Long.parseLong(parts[0]+parts[1]+...+parts[partsToSkip-1]);
			// truncate the parts array to keep only the numeric elements
			parts = Arrays.copyOfRange(parts, partsToSkip, parts.length);

			attrVals = new double[parts.length];
			for (int i = 0; i < parts.length; i++) {
				double d = Double.parseDouble(parts[i]);
				attrVals[i] = d;
			}

			// apply the appropriate normalization if needed
			attrVals = Normalizations.normalize(attrVals, normalization);

			allImagesFeatures.add(attrVals);
		}
		reader.close();
		return allImagesFeatures;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Zoop\Shard\Test\Owner;

use Zoop\Shard\Manifest;
use Zoop\Shard\AccessControl\Events as Events;
use Zoop\Shard\Test\Owner\TestAsset\Document\OwnerDoc;
use Zoop\Shard\Test\BaseTest;
use Zoop\Shard\Test\TestAsset\RoleAwareUser;

class UpdateOwnerAllowTest extends BaseTest
{
    protected $calls = array();

    public function setUp()
    {
        $manifest = new Manifest(
            [
                'models' => [
                    __NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document'
                ],
                'extension_configs' => [
                    'extension.accesscontrol' => true,
                    'extension.owner' => true,
                    'extension.odmcore' => true
                ],
                'service_manager_config' => [
                    'factories' => [
                        'user' => function () {
                            $user = new RoleAwareUser();
                            $user->setUsername('toby');
                            $user->addRole('admin');

                            return $user;
                        }
                    ]
                ]
            ]
        );

        $this->documentManager = $manifest->getServiceManager()->get('modelmanager');
    }

    public function testOwnerUpdateAllow()
    {
        $this->calls = array();
        $documentManager = $this->documentManager;
        $eventManager = $documentManager->getEventManager();

        $eventManager->addEventListener(Events::UPDATE_DENIED, $this);

        $testDoc = new OwnerDoc();

        $documentManager->persist($testDoc);
        $documentManager->flush();
        $id = $testDoc->getId();

        $documentManager->clear();
        $repository = $documentManager->getRepository(get_class($testDoc));
        $testDoc = $repository->find($id);

        $testDoc->setOwner('bobby');
        $documentManager->flush();

        $this->assertFalse(isset($this->calls[Events::UPDATE_DENIED]));
    }

    public function __call($name, $arguments)
    {
        $this->calls[$name] = $arguments;
    }
}


text:
Cardo
=====

[![travis-ci build status](https://secure.travis-ci.org/highgroove/cardo.png)](http://travis-ci.org/highgroove/cardo)

Cardo is a DSL we created at Highgroove to create recurring stories in
Pivotal Tracker.

**It is currently the result of a spike, and doesn't quite function
exactly as you might expect. Furthermore, there are (as of yet) little
to no tests.**

Requirements
------------

* Ruby >= 1.9.x (developed with MRI 1.9.2)

Examples
--------

Given a file **highgroove.rb**:

```ruby
require 'rubygems'
require 'cardo'

Cardo.describe do
  WEEKLY_REVIEWER = 'Charles Brian Quinn'
  DEVELOPERS      = ['Andy Lindeman', 'Chris Kelly']
  BLOGGERS        = DEVELOPERS + ['Megan Key']

  # Tracker API key required
  # Can be copied from <https://www.pivotaltracker.com/profile>
  api_key ENV['API_KEY']

  # Retrieve from the last URL path from a Tracker project URL
  # e.g., https://www.pivotaltracker.com/projects/123456
  project_id 123456

  every_iteration do
    feature "Weekly Review", estimate: 1,
                             labels:   'weekly-review',
                             owned_by: WEEKLY_REVIEWER

    feature "Team Lunch", estimate: 1,
                          labels:   'team-lunch'

    feature "Demo Day", estimate: 1,
                        labels:   'demo-day'

    random_pairing "Code Review of %s", DEVELOPERS, estimate: 1,
                                                    labels: 'code-review'

    random_pairing "Pair with %s", DEVELOPERS, estimate: 1,
                                               labels:   'pairings'

    random "Blog Post", BLOGGERS, estimate: 1,
                                  labels:   'blog-post'
  end
end
```

Create the stories with:

```bash
API_KEY='abc123' ruby highgroove.rb
```


text:
package org.drip.sample.stretch;

import org.drip.function.r1tor1.QuadraticRationalShapeControl;
import org.drip.quant.common.FormatUtil;
import org.drip.spline.basis.PolynomialFunctionSetParams;
import org.drip.spline.params.*;
import org.drip.spline.stretch.*;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 * Copyright (C) 2014 Lakshmi Krishnamurthy
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * CurvatureRoughnessPenaltyFit demonstrates the setting up and the usage of the curvature and closeness of
 * 	fit penalizing spline. It illustrates in detail the following steps:
 * 	- Set up the X Predictor Ordinate and the Y Response Value Set.
 * 	- Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
 * 		weighted closeness of fit.
 * 	- Construct a rational shape controller with the desired shape controller tension parameters and Global
 * 		Scaling.
 * 	- Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order roughness
 * 		penalty derivative, and without constraint.
 * 	- Construct the base, the base + 1 degree segment builder control.
 * 	- Construct the base, the elevated, and the best fit basis spline stretches.
 * 	- Compute the segment-by-segment monotonicity for all the three stretches.
 * 	- Compute the Stretch Jacobian for all the three stretches.
 * 	- Compute the Base Stretch Curvature Penalty Estimate.
 * 	- Compute the Elevated Stretch Curvature Penalty Estimate.
 * 	- Compute the Best Fit Stretch Curvature Penalty Estimate.
 *
 * @author Lakshmi Krishnamurthy
 */

public class CurvatureRoughnessPenaltyFit {

	/*
	 * Build Polynomial Segment Control Parameters
	 *
	 * 	WARNING: Insufficient Error Checking, so use caution
	 */

	public static final SegmentCustomBuilderControl PolynomialSegmentControlParams (
		final int iNumBasis,
		final SegmentInelasticDesignControl sdic,
		final ResponseScalingShapeControl rssc)
		throws Exception
	{
		return new SegmentCustomBuilderControl (
			MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
			new PolynomialFunctionSetParams (iNumBasis),
			sdic,
			rssc,
			null
		);
	}

	/*
	 * Construct the Basis Spline Stretch Instance using the following inputs:
	 * 	- Array of Segment Builder Parameters - one per segment
	 *  - Construct a Calibrated Stretch instance
	 *
	 * 	WARNING: Insufficient Error Checking, so use caution
	 */

	public static final MultiSegmentSequence BasisSplineStretchTest (
		final double[] adblX,
		final double[] adblY,
		final SegmentCustomBuilderControl scbc,
		final StretchBestFitResponse sbfr)
		throws Exception
	{
		/*
		 * Array of Segment Builder Parameters - one per segment
		 */

		SegmentCustomBuilderControl[] aSCBC = new SegmentCustomBuilderControl[adblX.length - 1];

		for (int i = 0; i < adblX.length - 1; ++i)
			aSCBC[i] = scbc;

		/*
		 * Construct a Calibrated Stretch instance
		 */

		return MultiSegmentSequenceBuilder.CreateCalibratedStretchEstimator (
			"SPLINE_STRETCH",
			adblX, // predictors
			adblY, // responses
			aSCBC, // Basis Segment Builder parameters
			sbfr, // Stretch Fitness Weighted Response
			BoundarySettings.NaturalStandard(), // Boundary Condition - Natural
			MultiSegmentSequence.CALIBRATE // Calibrate the Stretch predictors to the responses
		);
	}

	/*
	 * Bring it all together in the Penalized Curvature Fit Test using the following steps:
	 * 	- Set up the X Predictor Ordinate and the Y Response Value Set.
	 * 	- Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
	 * 		weighted closeness of fit.
	 * 	- Construct a rational shape controller with the desired shape controller tension parameters and Global Scaling.
	 * 	- Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order
	 * 		roughness penalty derivative, and without constraint.
	 * 	- Construct the base, the base + 1 degree segment builder control.
	 * 	- Construct the base, the elevated, and the best fit basis spline stretches.
	 * 	- Compute the segment-by-segment monotonicity for all the three stretches.
	 * 	- Compute the Stretch Jacobian for all the three stretches.
	 * 	- Compute the Base Stretch Curvature Penalty Estimate.
	 * 	- Compute the Elevated Stretch Curvature Penalty Estimate.
	 * 	- Compute the Best Fit Stretch Curvature Penalty Estimate.
	 */

	public static final void PenalizedCurvatureFitTest()
		throws Exception
	{
		/*
		 * X predictors
		 */

		double[] adblX = new double[] { 1.00,  1.50,  2.00, 3.00, 4.00, 5.00, 6.50, 8.00, 10.00};

		/*
		 * Y responses
		 */

		double[] adblY = new double[] {25.00, 20.25, 16.00, 9.00, 4.00, 1.00, 0.25, 4.00, 16.00};

		/*
		 * Construct a set of Predictor Ordinates, their Responses, and corresponding Weights to serve as
		 *  weighted closeness of fit.
		 */

		StretchBestFitResponse sbfr = StretchBestFitResponse.Create (
			new double[] { 2.28,  2.52,  2.73, 3.00,  5.50, 8.44,  8.76,  9.08,  9.80,  9.92},
			new double[] {14.27, 12.36, 10.61, 9.25, -0.50, 7.92, 10.07, 12.23, 15.51, 16.36},
			new double[] { 1.09,  0.82,  1.34, 1.10,  0.50, 0.79,  0.65,  0.49,  0.24,  0.21}
		);

		/*
		 * Construct a rational shape controller with the shape controller tension of 1, and Global Scaling.
		 */

		double dblShapeControllerTension = 1.;

		ResponseScalingShapeControl rssc = new ResponseScalingShapeControl (
			false,
			new QuadraticRationalShapeControl (dblShapeControllerTension)
		);

		/*
		 * Construct the segment inelastic parameter that is C2 (iK = 2 sets it to C2), with 2nd order
		 * 	roughness penalty derivative, and without constraint
		 */

		int iK = 2;
		int iRoughnessPenaltyDerivativeOrder = 2;

		SegmentInelasticDesignControl sdic = SegmentInelasticDesignControl.Create (
			iK,
			iRoughnessPenaltyDerivativeOrder
		);

		System.out.println (" \n--------------------------------------------------------------------------------------------------");

		System.out.println (" \n         == ORIGINAL #1 ==      $$   == ORIGINAL #2 ==    $$   == BEST FIT ==    ");

		System.out.println (" \n--------------------------------------------------------------------------------------------------");

		int iPolyNumBasis = 4;

		/*
		 * Construct the base, the base + 1 degree segment builder control
		 */

		SegmentCustomBuilderControl scbc1 = PolynomialSegmentControlParams (
			iPolyNumBasis,
			sdic,
			rssc
		);

		SegmentCustomBuilderControl scbc2 = PolynomialSegmentControlParams (
			iPolyNumBasis + 1,
			sdic,
			rssc
		);

		/*
		 * Construct the base, the elevated, and the best fit basis spline stretches
		 */

		MultiSegmentSequence mssBase1 = BasisSplineStretchTest (
			adblX,
			adblY,
			scbc1,
			null
		);

		MultiSegmentSequence mssBase2 = BasisSplineStretchTest (
			adblX,
			adblY,
			scbc2,
			null
		);

		MultiSegmentSequence mssBestFit = BasisSplineStretchTest (
			adblX,
			adblY,
			scbc2,
			sbfr
		);

		/*
		 * Compute the segment-by-segment monotonicity for all the three stretches
		 */

		double dblX = mssBase1.getLeftPredictorOrdinateEdge();

		double dblXMax = mssBase1.getRightPredictorOrdinateEdge();

		while (dblX <= dblXMax) {
			System.out.println (
				"Y[" + FormatUtil.FormatDouble (dblX, 1, 2, 1.) + "] " +
				FormatUtil.FormatDouble (mssBase1.responseValue (dblX), 2, 2, 1.) + " | "
					+ mssBase1.monotoneType (dblX) + " $$ "
				+ FormatUtil.FormatDouble (mssBase2.responseValue (dblX), 2, 2, 1.) + " | "
					+ mssBase2.monotoneType (dblX) + " $$ "
				+ FormatUtil.FormatDouble (mssBestFit.responseValue (dblX), 2, 2, 1.) + " | "
					+ mssBestFit.monotoneType (dblX));

			dblX += 0.25;
		}

		/*
		 * Compute the Stretch Jacobian for all the three stretches
		 */

		dblX = mssBase1.getLeftPredictorOrdinateEdge();

		while (dblX <= dblXMax) {
			System.out.println (
				"\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
					mssBase1.jackDResponseDCalibrationInput (dblX, 1).displayString());

			System.out.println (
				"\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
					mssBase2.jackDResponseDCalibrationInput (dblX, 1).displayString());

			System.out.println (
				"\t\tJacobian Y[" + FormatUtil.FormatDouble (dblX, 2, 2, 1.) + "] => " +
					mssBestFit.jackDResponseDCalibrationInput (dblX, 1).displayString());

			System.out.println ("\t\t----\n\t\t----");

			dblX += 0.25;
		}

		/*
		 * Compute the Base Stretch Curvature Penalty Estimate
		 */

		System.out.println ("\tBASE #1  DPE: " + FormatUtil.FormatDouble (mssBase1.curvatureDPE(), 10, 0, 1.));

		/*
		 * Compute the Elevated Stretch Curvature Penalty Estimate
		 */

		System.out.println ("\tBASE #2  DPE: " + FormatUtil.FormatDouble (mssBase2.curvatureDPE(), 10, 0, 1.));

		/*
		 * Compute the Best Fit Stretch Curvature Penalty Estimate
		 */

		System.out.println ("\tBEST FIT DPE: " + FormatUtil.FormatDouble (mssBestFit.curvatureDPE(), 10, 0, 1.));
	}

	public static final void main (
		final String[] astrArgs)
		throws Exception
	{
		PenalizedCurvatureFitTest();
	}
}


text:
Functional-JSRx
===============

Proyecto programada de la UNA. Uso de JS RX, programación funcional reactiva.


text:
require 'date'
require 'fileutils'
require 'spec_helper'

describe FileUtils do
  before :each do
    MemFs::File.umask(0020)
    MemFs.activate!

    described_class.mkdir '/test'
  end

  after :each do
    MemFs.deactivate!
  end

  describe '.cd' do
    it 'changes the current working directory' do
      described_class.cd '/test'
      expect(described_class.pwd).to eq('/test')
    end

    it 'returns nil' do
      expect(described_class.cd('/test')).to be_nil
    end

    it "raises an error when the given path doesn't exist" do
      expect { described_class.cd('/nowhere') }.to raise_specific_error(Errno::ENOENT)
    end

    it 'raises an error when the given path is not a directory' do
      described_class.touch('/test-file')
      expect { described_class.cd('/test-file') }.to raise_specific_error(Errno::ENOTDIR)
    end

    context 'when called with a block' do
      it 'changes current working directory for the block execution' do
        described_class.cd '/test' do
          expect(described_class.pwd).to eq('/test')
        end
      end

      it 'resumes to the old working directory after the block execution finished' do
        described_class.cd '/'
        expect { described_class.cd('/test') {} }.to_not change { described_class.pwd }
      end
    end

    context 'when the destination is a symlink' do
      before :each do
        described_class.symlink('/test', '/test-link')
      end

      it 'changes directory to the last target of the link chain' do
        described_class.cd('/test-link')
        expect(described_class.pwd).to eq('/test')
      end

      it "raises an error if the last target of the link chain doesn't exist" do
        expect { described_class.cd('/nowhere-link') }.to raise_specific_error(Errno::ENOENT)
      end
    end
  end

  describe '.chmod' do
    it 'changes permission bits on the named file to the bit pattern represented by mode' do
      described_class.touch '/test-file'
      described_class.chmod 0777, '/test-file'
      expect(File.stat('/test-file').mode).to eq(0100777)
    end

    it 'changes permission bits on the named files (in list) to the bit pattern represented by mode' do
      described_class.touch ['/test-file', '/test-file2']
      described_class.chmod 0777, ['/test-file', '/test-file2']
      expect(File.stat('/test-file2').mode).to eq(0100777)
    end

    it 'returns an array containing the file names' do
      file_names = %w[/test-file /test-file2]
      described_class.touch file_names
      expect(described_class.chmod(0777, file_names)).to eq(file_names)
    end

    it 'raises an error if an entry does not exist' do
      expect { described_class.chmod(0777, '/test-file') }.to raise_specific_error(Errno::ENOENT)
    end

    context 'when the named file is a symlink' do
      before :each do
        described_class.touch '/test-file'
        described_class.symlink '/test-file', '/test-link'
      end

      context 'when File responds to lchmod' do
        it 'changes the mode on the link' do
          described_class.chmod(0777, '/test-link')
          expect(File.lstat('/test-link').mode).to eq(0100777)
        end

        it "doesn't change the mode of the link's target" do
          mode = File.lstat('/test-file').mode
          described_class.chmod(0777, '/test-link')
          expect(File.lstat('/test-file').mode).to eq(mode)
        end
      end

      context "when File doesn't respond to lchmod" do
        it 'does nothing' do
          allow_any_instance_of(described_class::Entry_).to \
            receive_messages(have_lchmod?: false)
          mode = File.lstat('/test-link').mode
          described_class.chmod(0777, '/test-link')
          expect(File.lstat('/test-link').mode).to eq(mode)
        end
      end
    end
  end

  describe '.chmod_R' do
    before :each do
      described_class.touch '/test/test-file'
    end

    it 'changes the permission bits on the named entry' do
      described_class.chmod_R(0777, '/test')
      expect(File.stat('/test').mode).to eq(0100777)
    end

    it 'changes the permission bits on any sub-directory of the named entry' do
      described_class.chmod_R(0777, '/')
      expect(File.stat('/test').mode).to eq(0100777)
    end

    it 'changes the permission bits on any descendant file of the named entry' do
      described_class.chmod_R(0777, '/')
      expect(File.stat('/test/test-file').mode).to eq(0100777)
    end
  end

  describe '.chown' do
    it 'changes owner on the named file' do
      described_class.chown(42, nil, '/test')
      expect(File.stat('/test').uid).to eq(42)
    end

    it 'changes owner on the named files (in list)' do
      described_class.touch('/test-file')
      described_class.chown(42, nil, ['/test', '/test-file'])
      expect(File.stat('/test-file').uid).to eq(42)
    end

    it 'changes group on the named entry' do
      described_class.chown(nil, 42, '/test')
      expect(File.stat('/test').gid).to eq(42)
    end

    it 'changes group on the named entries in list' do
      described_class.touch('/test-file')
      described_class.chown(nil, 42, ['/test', '/test-file'])
      expect(File.stat('/test-file').gid).to eq(42)
    end

    it "doesn't change user if user is nil" do
      described_class.chown(nil, 42, '/test')
      expect(File.stat('/test').uid).not_to be(42)
    end

    it "doesn't change group if group is nil" do
      described_class.chown(42, nil, '/test')
      expect(File.stat('/test').gid).not_to be(42)
    end

    context 'when the name entry is a symlink' do
      before :each do
        described_class.touch '/test-file'
        described_class.symlink '/test-file', '/test-link'
      end

      it 'changes the owner on the last target of the link chain' do
        described_class.chown(42, nil, '/test-link')
        expect(File.stat('/test-file').uid).to eq(42)
      end

      it 'changes the group on the last target of the link chain' do
        described_class.chown(nil, 42, '/test-link')
        expect(File.stat('/test-file').gid).to eq(42)
      end

      it "doesn't change the owner of the symlink" do
        described_class.chown(42, nil, '/test-link')
        expect(File.lstat('/test-link').uid).not_to be(42)
      end

      it "doesn't change the group of the symlink" do
        described_class.chown(nil, 42, '/test-link')
        expect(File.lstat('/test-link').gid).not_to be(42)
      end
    end
  end

  describe '.chown_R' do
    before :each do
      described_class.touch '/test/test-file'
    end

    it 'changes the owner on the named entry' do
      described_class.chown_R(42, nil, '/test')
      expect(File.stat('/test').uid).to eq(42)
    end

    it 'changes the group on the named entry' do
      described_class.chown_R(nil, 42, '/test')
      expect(File.stat('/test').gid).to eq(42)
    end

    it 'changes the owner on any sub-directory of the named entry' do
      described_class.chown_R(42, nil, '/')
      expect(File.stat('/test').uid).to eq(42)
    end

    it 'changes the group on any sub-directory of the named entry' do
      described_class.chown_R(nil, 42, '/')
      expect(File.stat('/test').gid).to eq(42)
    end

    it 'changes the owner on any descendant file of the named entry' do
      described_class.chown_R(42, nil, '/')
      expect(File.stat('/test/test-file').uid).to eq(42)
    end

    it 'changes the group on any descendant file of the named entry' do
      described_class.chown_R(nil, 42, '/')
      expect(File.stat('/test/test-file').gid).to eq(42)
    end
  end

  describe '.cmp' do
    it_behaves_like 'aliased method', :cmp, :compare_file
  end

  describe '.compare_file' do
    it 'returns true if the contents of a file A and a file B are identical' do
      File.open('/test-file', 'w')  { |f| f.puts 'this is a test' }
      File.open('/test-file2', 'w') { |f| f.puts 'this is a test' }

      expect(described_class.compare_file('/test-file', '/test-file2')).to be true
    end

    it 'returns false if the contents of a file A and a file B are not identical' do
      File.open('/test-file', 'w')  { |f| f.puts 'this is a test' }
      File.open('/test-file2', 'w') { |f| f.puts 'this is not a test' }

      expect(described_class.compare_file('/test-file', '/test-file2')).to be false
    end
  end

  describe '.compare_stream' do
    it 'returns true if the contents of a stream A and stream B are identical' do
      File.open('/test-file', 'w')  { |f| f.puts 'this is a test' }
      File.open('/test-file2', 'w') { |f| f.puts 'this is a test' }

      file1 = File.open('/test-file')
      file2 = File.open('/test-file2')

      expect(described_class.compare_stream(file1, file2)).to be true
    end

    it 'returns false if the contents of a stream A and stream B are not identical' do
      File.open('/test-file', 'w')  { |f| f.puts 'this is a test' }
      File.open('/test-file2', 'w') { |f| f.puts 'this is not a test' }

      file1 = File.open('/test-file')
      file2 = File.open('/test-file2')

      expect(described_class.compare_stream(file1, file2)).to be false
    end
  end

  describe '.copy' do
    it_behaves_like 'aliased method', :copy, :cp
  end

  describe '.copy_entry' do
    it 'copies a file system entry +src+ to +dest+' do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
      described_class.copy_entry('/test-file', '/test-copy')
      expect(File.read('/test-copy')).to eq("test\n")
    end

    it 'preserves file types' do
      described_class.touch('/test-file')
      described_class.symlink('/test-file', '/test-link')
      described_class.copy_entry('/test-link', '/test-copy')
      expect(File.symlink?('/test-copy')).to be true
    end

    context 'when +src+ does not exist' do
      it 'raises an exception' do
        expect {
          described_class.copy_entry('/test-file', '/test-copy')
        }.to raise_specific_error(RuntimeError)
      end
    end

    context 'when +preserve+ is true' do
      let(:time) { Date.parse('2013-01-01') }

      before :each do
        described_class.touch('/test-file')
        described_class.chown(1042, 1042, '/test-file')
        described_class.chmod(0777, '/test-file')
        _fs.find('/test-file').mtime = time
        described_class.copy_entry('/test-file', '/test-copy', true)
      end

      it 'preserves owner' do
        expect(File.stat('/test-copy').uid).to eq(1042)
      end

      it 'preserves group' do
        expect(File.stat('/test-copy').gid).to eq(1042)
      end

      it 'preserves permissions' do
        expect(File.stat('/test-copy').mode).to eq(0100777)
      end

      it 'preserves modified time' do
        expect(File.stat('/test-copy').mtime).to eq(time)
      end
    end

    context 'when +dest+ already exists' do
      it 'overwrite it' do
        File.open('/test-file', 'w') { |f| f.puts 'test' }
        described_class.touch('/test-copy')
        described_class.copy_entry('/test-file', '/test-copy')
        expect(File.read('/test-copy')).to eq("test\n")
      end
    end

    context 'when +remove_destination+ is true' do
      it 'removes each destination file before copy' do
        described_class.touch(['/test-file', '/test-copy'])
        expect(File).to receive(:unlink).with('/test-copy')
        described_class.copy_entry('/test-file', '/test-copy', false, false, true)
      end
    end

    context 'when +src+ is a directory' do
      it 'copies its contents recursively' do
        described_class.mkdir_p('/test-dir/test-sub-dir')
        described_class.copy_entry('/test-dir', '/test-copy')
        expect(Dir.exist?('/test-copy/test-sub-dir')).to be true
      end
    end
  end

  describe '.copy_file' do
    it 'copies file contents of src to dest' do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
      described_class.copy_file('/test-file', '/test-file2')
      expect(File.read('/test-file2')).to eq("test\n")
    end
  end

  describe '.copy_stream' do
    # This method is not implemented since it is delegated to the IO class.
  end

  describe '.cp' do
    before :each do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
    end

    it 'copies a file content +src+ to +dest+' do
      described_class.cp('/test-file', '/copy-file')
      expect(File.read('/copy-file')).to eq("test\n")
    end

    context 'when +src+ and +dest+ are the same file' do
      it 'raises an error' do
        expect {
          described_class.cp('/test-file', '/test-file')
        }.to raise_specific_error(ArgumentError)
      end
    end

    context 'when +dest+ is a directory' do
      it 'copies +src+ to +dest/src+' do
        described_class.mkdir('/dest')
        described_class.cp('/test-file', '/dest/copy-file')
        expect(File.read('/dest/copy-file')).to eq("test\n")
      end
    end

    context 'when src is a list of files' do
      context 'when +dest+ is not a directory' do
        it 'raises an error' do
          described_class.touch(['/dest', '/test-file2'])
          expect {
            described_class.cp(['/test-file', '/test-file2'], '/dest')
          }.to raise_specific_error(Errno::ENOTDIR)
        end
      end
    end
  end

  describe '.cp_r' do
    it 'copies +src+ to +dest+' do
      File.open('/test-file', 'w') { |f| f.puts 'test' }

      described_class.cp_r('/test-file', '/copy-file')
      expect(File.read('/copy-file')).to eq("test\n")
    end

    context 'when +src+ is a directory' do
      it 'copies all its contents recursively' do
        described_class.mkdir('/test/dir')
        described_class.touch('/test/dir/file')

        described_class.cp_r('/test', '/dest')
        expect(File.exist?('/dest/dir/file')).to be true
      end
    end

    context 'when +dest+ is a directory' do
      it 'copies +src+ to +dest/src+' do
        described_class.mkdir(['/test/dir', '/dest'])
        described_class.touch('/test/dir/file')

        described_class.cp_r('/test', '/dest')
        expect(File.exist?('/dest/test/dir/file')).to be true
      end
    end

    context 'when +src+ is a list of files' do
      it 'copies each of them in +dest+' do
        described_class.mkdir(['/test/dir', '/test/dir2', '/dest'])
        described_class.touch(['/test/dir/file', '/test/dir2/file'])

        described_class.cp_r(['/test/dir', '/test/dir2'], '/dest')
        expect(File.exist?('/dest/dir2/file')).to be true
      end
    end
  end

  describe '.getwd' do
    it_behaves_like 'aliased method', :getwd, :pwd
  end

  describe '.identical?' do
    it_behaves_like 'aliased method', :identical?, :compare_file
  end

  describe '.install' do
    before :each do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
    end

    it 'copies +src+ to +dest+' do
      described_class.install('/test-file', '/test-file2')
      expect(File.read('/test-file2')).to eq("test\n")
    end

    context 'when +:mode+ is set' do
      it 'changes the permission mode to +mode+' do
        expect(File).to receive(:chmod).with(0777, '/test-file2')
        described_class.install('/test-file', '/test-file2', mode: 0777)
      end
    end

    context 'when +src+ and +dest+ are the same file' do
      it 'raises an exception' do
        expect {
          described_class.install('/test-file', '/test-file')
        }.to raise_exception(ArgumentError)
      end
    end

    context 'when +dest+ already exists' do
      it 'removes destination before copy' do
        expect(File).to receive(:unlink).with('/test-file2')
        described_class.install('/test-file', '/test-file2')
      end

      context 'and +dest+ is a directory' do
        it 'installs +src+ in dest/src' do
          described_class.mkdir('/test-dir')
          described_class.install('/test-file', '/test-dir')
          expect(File.read('/test-dir/test-file')).to eq("test\n")
        end
      end
    end
  end

  describe '.link' do
    it_behaves_like 'aliased method', :link, :ln
  end

  describe '.ln' do
    before :each do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
    end

    it 'creates a hard link +dest+ which points to +src+' do
      described_class.ln('/test-file', '/test-file2')
      expect(File.read('/test-file2')).to eq(File.read('/test-file'))
    end

    it 'creates a hard link, not a symlink' do
      described_class.ln('/test-file', '/test-file2')
      expect(File.symlink?('/test-file2')).to be false
    end

    context 'when +dest+ already exists' do
      context 'and is a directory' do
        it 'creates a link dest/src' do
          described_class.mkdir('/test-dir')
          described_class.ln('/test-file', '/test-dir')
          expect(File.read('/test-dir/test-file')).to eq(File.read('/test-file'))
        end
      end

      context 'and it is not a directory' do
        it 'raises an exception' do
          described_class.touch('/test-file2')
          expect {
            described_class.ln('/test-file', '/test-file2')
          }.to raise_specific_error(SystemCallError)
        end

        context 'and +:force+ is set' do
          it 'overwrites +dest+' do
            described_class.touch('/test-file2')
            described_class.ln('/test-file', '/test-file2', force: true)
            expect(File.read('/test-file2')).to eq(File.read('/test-file'))
          end
        end
      end
    end

    context 'when passing a list of paths' do
      it 'creates a link for each path in +destdir+' do
        described_class.touch('/test-file2')
        described_class.mkdir('/test-dir')
        described_class.ln(['/test-file', '/test-file2'], '/test-dir')
      end

      context 'and +destdir+ is not a directory' do
        it 'raises an exception' do
          described_class.touch(['/test-file2', '/not-a-dir'])
          expect {
            described_class.ln(['/test-file', '/test-file2'], '/not-a-dir')
          }.to raise_specific_error(Errno::ENOTDIR)
        end
      end
    end
  end

  describe '.ln_s' do
    before :each do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
      described_class.touch('/not-a-dir')
      described_class.mkdir('/test-dir')
    end

    it 'creates a symbolic link +new+' do
      described_class.ln_s('/test-file', '/test-link')
      expect(File.symlink?('/test-link')).to be true
    end

    it 'creates a symbolic link which points to +old+' do
      described_class.ln_s('/test-file', '/test-link')
      expect(File.read('/test-link')).to eq(File.read('/test-file'))
    end

    context 'when +new+ already exists' do
      context 'and it is a directory' do
        it 'creates a symbolic link +new/old+' do
          described_class.ln_s('/test-file', '/test-dir')
          expect(File.symlink?('/test-dir/test-file')).to be true
        end
      end

      context 'and it is not a directory' do
        it 'raises an exeption' do
          expect {
            described_class.ln_s('/test-file', '/not-a-dir')
          }.to raise_specific_error(Errno::EEXIST)
        end

        context 'and +:force+ is set' do
          it 'overwrites +new+' do
            described_class.ln_s('/test-file', '/not-a-dir', force: true)
            expect(File.symlink?('/not-a-dir')).to be true
          end
        end
      end
    end

    context 'when passing a list of paths' do
      before :each do
        File.open('/test-file2', 'w') { |f| f.puts 'test2' }
      end

      it 'creates several symbolic links in +destdir+' do
        described_class.ln_s(['/test-file', '/test-file2'], '/test-dir')
        expect(File.exist?('/test-dir/test-file2')).to be true
      end

      it 'creates symbolic links pointing to each item in the list' do
        described_class.ln_s(['/test-file', '/test-file2'], '/test-dir')
        expect(File.read('/test-dir/test-file2')).to eq(File.read('/test-file2'))
      end

      context 'when +destdir+ is not a directory' do
        it 'raises an error' do
          expect {
            described_class.ln_s(['/test-file', '/test-file2'], '/not-a-dir')
          }.to raise_specific_error(Errno::ENOTDIR)
        end
      end
    end
  end

  describe '.ln_sf' do
    it 'calls ln_s with +:force+ set to true' do
      File.open('/test-file', 'w') { |f| f.puts 'test' }
      File.open('/test-file2', 'w') { |f| f.puts 'test2' }
      described_class.ln_sf('/test-file', '/test-file2')
      expect(File.read('/test-file2')).to eq(File.read('/test-file'))
    end
  end

  describe '.makedirs' do
    it_behaves_like 'aliased method', :makedirs, :mkdir_p
  end

  describe '.mkdir' do
    it 'creates one directory' do
      described_class.mkdir('/test-dir')
      expect(File.directory?('/test-dir')).to be true
    end

    context 'when passing a list of paths' do
      it 'creates several directories' do
        described_class.mkdir(['/test-dir', '/test-dir2'])
        expect(File.directory?('/test-dir2')).to be true
      end
    end

    context 'when passing options' do
      context 'when passing mode parameter' do
        it 'creates directory with specified permissions' do
          described_class.mkdir('/test-dir', :mode => 0654)
          expect(File.exist?('/test-dir')).to be true
          expect(File.stat('/test-dir').mode).to eq(0100654)
        end
      end

      context 'when passing noop parameter' do
        it 'does not create any directories' do
          described_class.mkdir(['/test-dir', '/another-dir'], :noop => true)
          expect(File.directory?('/test-dir')).to be false
          expect(File.directory?('/another-dir')).to be false
        end
      end
    end

  end

  describe '.mkdir_p' do
    it 'creates a directory' do
      described_class.mkdir_p('/test-dir')
      expect(File.directory?('/test-dir')).to be true
    end

    it 'creates all the parent directories' do
      described_class.mkdir_p('/path/to/some/test-dir')
      expect(File.directory?('/path/to/some')).to be true
    end

    context 'when passing a list of paths' do
      it 'creates each directory' do
        described_class.mkdir_p(['/test-dir', '/test-dir'])
        expect(File.directory?('/test-dir')).to be true
      end

      it "creates each directory's parents" do
        described_class.mkdir_p(['/test-dir', '/path/to/some/test-dir'])
        expect(File.directory?('/path/to/some')).to be true
      end
    end

    context 'when passing options' do
      context 'when passing mode parameter' do
        it 'creates directory with specified permissions' do
          described_class.mkdir_p('/test-dir', :mode => 0654)
          expect(File.exist?('/test-dir')).to be true
          expect(File.stat('/test-dir').mode).to eq(0100654)
        end
      end

      context 'when passing noop parameter' do
        it 'does not create any directories' do
          described_class.mkdir_p(['/test-dir', '/another-dir'], :noop => true)
          expect(File.directory?('/test-dir')).to be false
          expect(File.directory?('/another-dir')).to be false
        end
      end
    end
  end

  describe '.mkpath' do
    it_behaves_like 'aliased method', :mkpath, :mkdir_p
  end

  describe '.move' do
    it_behaves_like 'aliased method', :move, :mv
  end

  describe '.mv' do
    it 'moves +src+ to +dest+' do
      described_class.touch('/test-file')
      described_class.mv('/test-file', '/test-file2')
      expect(File.exist?('/test-file2')).to be true
    end

    it 'removes +src+' do
      described_class.touch('/test-file')
      described_class.mv('/test-file', '/test-file2')
      expect(File.exist?('/test-file')).to be false
    end

    context 'when +dest+ already exists' do
      context 'and is a directory' do
        it 'moves +src+ to dest/src' do
          described_class.touch('/test-file')
          described_class.mkdir('/test-dir')
          described_class.mv('/test-file', '/test-dir')
          expect(File.exist?('/test-dir/test-file')).to be true
        end
      end

      context 'and +dest+ is not a directory' do
        it 'it overwrites +dest+' do
          File.open('/test-file', 'w') { |f| f.puts 'test' }
          described_class.touch('/test-file2')
          described_class.mv('/test-file', '/test-file2')
          expect(File.read('/test-file2')).to eq("test\n")
        end
      end
    end
  end

  describe '.pwd' do
    it 'returns the name of the current directory' do
      described_class.cd '/test'
      expect(described_class.pwd).to eq('/test')
    end
  end

  describe '.remove' do
    it_behaves_like 'aliased method', :remove, :rm
  end

  describe '.remove_dir' do
    it 'removes the given directory +dir+' do
      described_class.mkdir('/test-dir')
      described_class.remove_dir('/test-dir')
      expect(File.exist?('/test-dir')).to be false
    end

    it 'removes the contents of the given directory +dir+' do
      described_class.mkdir_p('/test-dir/test-sub-dir')
      described_class.remove_dir('/test-dir')
      expect(File.exist?('/test-dir/test-sub-dir')).to be false
    end

    context 'when +force+ is set' do
      it 'ignores standard errors' do
        expect { described_class.remove_dir('/test-dir', true) }.not_to raise_error
      end
    end
  end

  describe '.remove_entry' do
    it 'removes a file system entry +path+' do
      described_class.touch('/test-file')
      described_class.remove_entry('/test-file')
      expect(File.exist?('/test-file')).to be false
    end

    context 'when +path+ is a directory' do
      it 'removes it recursively' do
        described_class.mkdir_p('/test-dir/test-sub-dir')
        described_class.remove_entry('/test-dir')
        expect(Dir.exist?('/test-dir')).to be false
      end
    end
  end

  describe '.remove_entry_secure' do
    before :each do
      described_class.mkdir_p('/test-dir/test-sub-dir')
    end

    it 'removes a file system entry +path+' do
      described_class.chmod(0755, '/')
      described_class.remove_entry_secure('/test-dir')
      expect(Dir.exist?('/test-dir')).to be false
    end

    context 'when +path+ is a directory' do
      it 'removes it recursively' do
        described_class.chmod(0755, '/')
        described_class.remove_entry_secure('/test-dir')
        expect(Dir.exist?('/test-dir/test-sub-dir')).to be false
      end

      context 'and is word writable' do
        it 'calls chown(2) on it' do
          described_class.chmod(01777, '/')
          directory = _fs.find('/test-dir')
          expect(directory).to receive(:uid=).at_least(:once)
          described_class.remove_entry_secure('/test-dir')
        end

        it 'calls chmod(2) on all sub directories' do
          described_class.chmod(01777, '/')
          directory = _fs.find('/test-dir')
          expect(directory).to receive(:mode=).at_least(:once)
          described_class.remove_entry_secure('/test-dir')
        end
      end
    end
  end

  describe '.remove_file' do
    it 'removes a file path' do
      described_class.touch('/test-file')
      described_class.remove_file('/test-file')
      expect(File.exist?('/test-file')).to be false
    end

    context 'when +force+ is set' do
      it 'ignores StandardError' do
        expect { described_class.remove_file('/no-file', true) }.not_to raise_error
      end
    end
  end

  describe '.rm' do
    it 'removes the specified file' do
      described_class.touch('/test-file')
      described_class.rm('/test-file')
      expect(File.exist?('/test-file')).to be false
    end

    it 'removes files specified in list' do
      described_class.touch(['/test-file', '/test-file2'])
      described_class.rm(['/test-file', '/test-file2'])
      expect(File.exist?('/test-file2')).to be false
    end

    it 'cannot remove a directory' do
      described_class.mkdir('/test-dir')
      expect { described_class.rm('/test-dir') }.to raise_specific_error(Errno::EPERM)
    end

    context 'when +:force+ is set' do
      it 'ignores StandardError' do
        described_class.mkdir('/test-dir')
        expect {
          described_class.rm('/test-dir', force: true)
        }.not_to raise_error
      end
    end
  end

  describe '.rm_f' do
    it 'calls rm with +:force+ set to true' do
      expect(described_class).to receive(:rm).with('test', force: true)
      described_class.rm_f('test')
    end
  end

  describe '.rm_r' do
    before :each do
      described_class.touch(['/test-file', '/test-file2'])
    end

    it 'removes a list of files' do
      described_class.rm_r(['/test-file', '/test-file2'])
      expect(File.exist?('/test-file2')).to be false
    end

    context 'when an item of the list is a directory' do
      it 'removes all its contents recursively' do
        described_class.mkdir('/test-dir')
        described_class.touch('/test-dir/test-file')
        described_class.rm_r(['/test-file', '/test-file2', '/test-dir'])
        expect(File.exist?('/test-dir/test-file')).to be false
      end
    end

    context 'when +:force+ is set' do
      it 'ignores StandardError' do
        expect {
          described_class.rm_r(['/no-file'], force: true)
        }.not_to raise_error
      end
    end
  end

  describe '.rm_rf' do
    it 'calls rm with +:force+ set to true' do
      expect(described_class).to receive(:rm_r).with('test', force: true)
      described_class.rm_rf('test')
    end
  end

  describe '.rmdir' do
    it 'Removes a directory' do
      described_class.mkdir('/test-dir')
      described_class.rmdir('/test-dir')
      expect(Dir.exist?('/test-dir')).to be false
    end

    it 'Removes a list of directories' do
      described_class.mkdir('/test-dir')
      described_class.mkdir('/test-dir2')
      described_class.rmdir(['/test-dir', '/test-dir2'])
      expect(Dir.exist?('/test-dir2')).to be false
    end

    context 'when a directory is not empty' do
      before :each do
        described_class.mkdir('/test-dir')
        described_class.touch('/test-dir/test-file')
      end

      it 'ignores errors' do
        expect { described_class.rmdir('/test-dir') }.not_to raise_error
      end

      it "doesn't remove the directory" do
        described_class.rmdir('/test-dir')
        expect(Dir.exist?('/test-dir')).to be true
      end
    end
  end

  describe '.rmtree' do
    it_behaves_like 'aliased method', :rmtree, :rm_rf
  end

  describe '.safe_unlink' do
    it_behaves_like 'aliased method', :safe_unlink, :rm_f
  end

  describe '.symlink' do
    it_behaves_like 'aliased method', :symlink, :ln_s
  end

  describe '.touch' do
    it "creates a file if it doesn't exist" do
      described_class.touch('/test-file')
      expect(_fs.find('/test-file')).not_to be_nil
    end

    it "creates a list of files if they don't exist" do
      described_class.touch(['/test-file', '/test-file2'])
      expect(_fs.find('/test-file2')).not_to be_nil
    end
  end

  describe '.uptodate?' do
    before :each do
      described_class.touch('/test-file')
      described_class.touch('/old-file')
      _fs.find!('/old-file').mtime = Time.now - 3600
    end

    it 'returns true if +newer+ is newer than all +old_list+' do
      expect(described_class.uptodate?('/test-file', ['/old-file'])).to be true
    end

    context 'when +newer+ does not exist' do
      it 'consideres it as older' do
        expect(described_class.uptodate?('/no-file', ['/old-file'])).to be false
      end
    end

    context 'when a item of +old_list+ does not exist' do
      it 'consideres it as older than +newer+' do
        uptodate = described_class.uptodate?('/test-file', ['/old-file', '/no-file'])
        expect(uptodate).to be true
      end
    end
  end
end


text:
using UnityEngine;

public class AIGridClickHandler : GridClickHandler {

    public override void ClickedAt(Vector2 clickPos) {
        if (gameLogic.WhoseTurn == AIScript.HumanType)
            base.ClickedAt(clickPos);
    }
}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55003711"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<note type="other">Probe Report<lb/></note>

	<docTitle>
	<titlePart>Title: Identification of activators for the M2 isoform of human pyruvate kinase Version 3<lb/></titlePart>
	</docTitle>

	<byline>
	<docAuthor>Authors: Matthew B. Boxer,<lb/> a<lb/> Jian-kang Jiang,<lb/> a<lb/> Matthew G. Vander Heiden,<lb/> b,c<lb/> Min Shen,<lb/> a<lb/> Henrike Veith,<lb/> a<lb/> Lewis C. Cantley,<lb/> d,e<lb/> Craig J. Thomas<lb/> a<lb/> </docAuthor>
	</byline>

	<byline>
	<affiliation>a)<lb/> NIH Chemical Genomics Center, National Human Genome Research Institute, National<lb/> Institutes of Health,</affiliation>
	</byline>

	<address>9800 Medical Center Drive, MSC 3370 Bethesda, Maryland 20850,<lb/></address>

	<byline>
	<affiliation>b)<lb/> Koch<lb/> Institute at MIT,</affiliation>
	</byline>

	<address>Cambridge, MA 02139, USA<lb/></address>

	<byline>
	<note type="other">c)<lb/></note>
	</byline>

	<byline>
	<affiliation>Dana Farber Cancer Institute,</affiliation>
	</byline>

	<address>Boston,<lb/> Massachusetts 02115,<lb/></address>

	<byline>
	<note type="other">d)<lb/></note>
	</byline>

	<byline>
	<affiliation>Department of Systems Biology, Harvard Medical School,</affiliation>
	</byline>

	<address>Boston,<lb/> Massachusetts 02115, and<lb/></address>

	<note type="other">e)<lb/></note>

	<byline>
	<affiliation>Division of Signal Transduction, Beth Israel Deaconess Medical<lb/> Center,</affiliation>
	</byline>

	<address>Boston, Massachusetts 02115<lb/></address>

	<note type="other">Assigned Assay Grant #: R03 MH085679<lb/> Screening Center Name & PI: NIH Chemical Genomics Center & Dr. Christopher P. Austin<lb/> Chemistry Center Name & PI: NIH Chemical Genomics Center & Dr. Christopher P. Austin<lb/> Assay Submitter & Institution: Dr. Matthew George Vander Heiden, Harvard<lb/> PubChem Summary Bioassay Identifier (AID): 2095<lb/></note>

Abstract:<lb/> The expression of human pyruvate kinase M2 (hPK-M2) in cancer cells appears to be critical for tumor<lb/> cell growth and proliferation in vivo. Because the PK-M2 isoform is expressed in all cancer cells studied,<lb/> it represents a target for drug development that could potentially enable tumor cells to return to a normal<lb/> state of metabolism. If this novel strategy for targeting malignancy were successful, it would be<lb/> applicable to diverse types of cancer. The probes ML203(CID-44543605), ML202 (CID-44246498), and<lb/> ML170 (CID-4547230) are members of a series of highly specific allosteric activators for the tumor-<lb/>specific isoform of human pyruvate kinase (M2 isoform). All three probes affect the cooperativity of<lb/> phosphoenolpyruvate (PEP) binding, with little affect on adenosine diphosphate (ADP) binding, in a<lb/> manner similar to FBP.

		</front>
	</text>
</tei>


text:
<?php
/**
     * Create a project map (similar to a sitemap) of project.
     *
     * The Reflection component is capable of analyzing one or more files into a hierarchy of objects representing the
     * structure of your project. It does this by analyzing the source code of each individual file using the
     * `analyze()` method in the Analyzer class.
     *
     * Because the Analyzer class requires a whole series of objects that interact together a factory method `create()`
     * is available. This method instantiates all objects and provides a reasonable default to start using the Analyzer.
     *
     * There is also a Service Provider (`\phpDocumentor\Descriptor\ServiceProvider`) that can be used with either Silex
     * or Cilex instead of using the factory method; this will make it easier to plug in your own features if you want to.
     */

// use Composer's autoloader to allow the application to automatically load all classes on request.
use phpDocumentor\Reflection\Php\Project;

include 'vendor/autoload.php';

// Create a new Analyzer with which we can analyze a PHP source file
$projectFactory = \phpDocumentor\Reflection\Php\ProjectFactory::createInstance();

// Create an array of files to analize.
$files = [ new \phpDocumentor\Reflection\File\LocalFile('tests/example.file.php') ];

//create a new project 'MyProject' containing all elements in the files.
/** @var Project $project */
$project = $projectFactory->create('MyProject', $files);

// As an example of what you can do, let's list all class names in the file 'tests/example.file.php'.
echo 'List all classes in the example source file: ' . PHP_EOL;

/** @var \phpDocumentor\Reflection\Php\Class_ $class */
foreach ($project->getFiles()['tests/example.file.php']->getClasses() as $class) {
    echo '- ' . $class->getFqsen() . PHP_EOL;
}