text:
#ifndef JIT_h
#define JIT_h

#if ENABLE(JIT)

// Verbose logging of code generation
#define ENABLE_JIT_VERBOSE 0
// Verbose logging for OSR-related code.
#define ENABLE_JIT_VERBOSE_OSR 0

// We've run into some problems where changing the size of the class JIT leads to
// performance fluctuations.  Try forcing alignment in an attempt to stabalize this.
#if COMPILER(GCC)
#define JIT_CLASS_ALIGNMENT __attribute__ ((aligned (32)))
#else
#define JIT_CLASS_ALIGNMENT
#endif

#define ASSERT_JIT_OFFSET(actual, expected) ASSERT_WITH_MESSAGE(actual == expected, "JIT Offset \"%s\" should be %d, not %d.\n", #expected, static_cast<int>(expected), static_cast<int>(actual));

#include "CodeBlock.h"
#include "CompactJITCodeMap.h"
#include "Interpreter.h"
#include "JITDisassembler.h"
#include "JSInterfaceJIT.h"
#include "LegacyProfiler.h"
#include "Opcode.h"
#include "ResultType.h"
#include "UnusedPointer.h"
#include <bytecode/SamplingTool.h>

namespace JSC {

    class CodeBlock;
    class FunctionExecutable;
    class JIT;
    class JSPropertyNameIterator;
    class Interpreter;
    class JSScope;
    class JSStack;
    class MarkedAllocator;
    class Register;
    class StructureChain;

    struct CallLinkInfo;
    struct Instruction;
    struct OperandTypes;
    struct PolymorphicAccessStructureList;
    struct SimpleJumpTable;
    struct StringJumpTable;
    struct StructureStubInfo;

    struct CallRecord {
        MacroAssembler::Call from;
        unsigned bytecodeOffset;
        void* to;

        CallRecord()
        {
        }

        CallRecord(MacroAssembler::Call from, unsigned bytecodeOffset, void* to = 0)
            : from(from)
            , bytecodeOffset(bytecodeOffset)
            , to(to)
        {
        }
    };

    struct JumpTable {
        MacroAssembler::Jump from;
        unsigned toBytecodeOffset;

        JumpTable(MacroAssembler::Jump f, unsigned t)
            : from(f)
            , toBytecodeOffset(t)
        {
        }
    };

    struct SlowCaseEntry {
        MacroAssembler::Jump from;
        unsigned to;
        unsigned hint;

        SlowCaseEntry(MacroAssembler::Jump f, unsigned t, unsigned h = 0)
            : from(f)
            , to(t)
            , hint(h)
        {
        }
    };

    struct SwitchRecord {
        enum Type {
            Immediate,
            Character,
            String
        };

        Type type;

        union {
            SimpleJumpTable* simpleJumpTable;
            StringJumpTable* stringJumpTable;
        } jumpTable;

        unsigned bytecodeOffset;
        unsigned defaultOffset;

        SwitchRecord(SimpleJumpTable* jumpTable, unsigned bytecodeOffset, unsigned defaultOffset, Type type)
            : type(type)
            , bytecodeOffset(bytecodeOffset)
            , defaultOffset(defaultOffset)
        {
            this->jumpTable.simpleJumpTable = jumpTable;
        }

        SwitchRecord(StringJumpTable* jumpTable, unsigned bytecodeOffset, unsigned defaultOffset)
            : type(String)
            , bytecodeOffset(bytecodeOffset)
            , defaultOffset(defaultOffset)
        {
            this->jumpTable.stringJumpTable = jumpTable;
        }
    };

    enum PropertyStubGetById_T { PropertyStubGetById };
    enum PropertyStubPutById_T { PropertyStubPutById };

    struct PropertyStubCompilationInfo {
        enum Type { GetById, PutById } m_type;

        unsigned bytecodeIndex;
        MacroAssembler::Call callReturnLocation;
        MacroAssembler::Label hotPathBegin;
        MacroAssembler::DataLabelPtr getStructureToCompare;
        MacroAssembler::PatchableJump getStructureCheck;
        MacroAssembler::ConvertibleLoadLabel propertyStorageLoad;
#if USE(JSVALUE64)
        MacroAssembler::DataLabelCompact getDisplacementLabel;
#else
        MacroAssembler::DataLabelCompact getDisplacementLabel1;
        MacroAssembler::DataLabelCompact getDisplacementLabel2;
#endif
        MacroAssembler::Label getPutResult;
        MacroAssembler::Label getColdPathBegin;
        MacroAssembler::DataLabelPtr putStructureToCompare;
#if USE(JSVALUE64)
        MacroAssembler::DataLabel32 putDisplacementLabel;
#else
        MacroAssembler::DataLabel32 putDisplacementLabel1;
        MacroAssembler::DataLabel32 putDisplacementLabel2;
#endif

#if !ASSERT_DISABLED
        PropertyStubCompilationInfo()
            : bytecodeIndex(std::numeric_limits<unsigned>::max())
        {
        }
#endif

        PropertyStubCompilationInfo(
            PropertyStubGetById_T, unsigned bytecodeIndex, MacroAssembler::Label hotPathBegin,
            MacroAssembler::DataLabelPtr structureToCompare,
            MacroAssembler::PatchableJump structureCheck,
            MacroAssembler::ConvertibleLoadLabel propertyStorageLoad,
#if USE(JSVALUE64)
            MacroAssembler::DataLabelCompact displacementLabel,
#else
            MacroAssembler::DataLabelCompact displacementLabel1,
            MacroAssembler::DataLabelCompact displacementLabel2,
#endif
            MacroAssembler::Label putResult)
            : m_type(GetById)
            , bytecodeIndex(bytecodeIndex)
            , hotPathBegin(hotPathBegin)
            , getStructureToCompare(structureToCompare)
            , getStructureCheck(structureCheck)
            , propertyStorageLoad(propertyStorageLoad)
#if USE(JSVALUE64)
            , getDisplacementLabel(displacementLabel)
#else
            , getDisplacementLabel1(displacementLabel1)
            , getDisplacementLabel2(displacementLabel2)
#endif
            , getPutResult(putResult)
        {
        }

        PropertyStubCompilationInfo(
            PropertyStubPutById_T, unsigned bytecodeIndex, MacroAssembler::Label hotPathBegin,
            MacroAssembler::DataLabelPtr structureToCompare,
            MacroAssembler::ConvertibleLoadLabel propertyStorageLoad,
#if USE(JSVALUE64)
            MacroAssembler::DataLabel32 displacementLabel
#else
            MacroAssembler::DataLabel32 displacementLabel1,
            MacroAssembler::DataLabel32 displacementLabel2
#endif
            )
            : m_type(PutById)
            , bytecodeIndex(bytecodeIndex)
            , hotPathBegin(hotPathBegin)
            , propertyStorageLoad(propertyStorageLoad)
            , putStructureToCompare(structureToCompare)
#if USE(JSVALUE64)
            , putDisplacementLabel(displacementLabel)
#else
            , putDisplacementLabel1(displacementLabel1)
            , putDisplacementLabel2(displacementLabel2)
#endif
        {
        }

        void slowCaseInfo(PropertyStubGetById_T, MacroAssembler::Label coldPathBegin, MacroAssembler::Call call)
        {
            ASSERT(m_type == GetById);
            callReturnLocation = call;
            getColdPathBegin = coldPathBegin;
        }

        void slowCaseInfo(PropertyStubPutById_T, MacroAssembler::Call call)
        {
            ASSERT(m_type == PutById);
            callReturnLocation = call;
        }

        void copyToStubInfo(StructureStubInfo& info, LinkBuffer &patchBuffer);
    };

    struct ByValCompilationInfo {
        ByValCompilationInfo() { }

        ByValCompilationInfo(unsigned bytecodeIndex, MacroAssembler::PatchableJump badTypeJump, JITArrayMode arrayMode, MacroAssembler::Label doneTarget)
            : bytecodeIndex(bytecodeIndex)
            , badTypeJump(badTypeJump)
            , arrayMode(arrayMode)
            , doneTarget(doneTarget)
        {
        }

        unsigned bytecodeIndex;
        MacroAssembler::PatchableJump badTypeJump;
        JITArrayMode arrayMode;
        MacroAssembler::Label doneTarget;
        MacroAssembler::Label slowPathTarget;
        MacroAssembler::Call returnAddress;
    };

    struct StructureStubCompilationInfo {
        MacroAssembler::DataLabelPtr hotPathBegin;
        MacroAssembler::Call hotPathOther;
        MacroAssembler::Call callReturnLocation;
        CallLinkInfo::CallType callType;
        unsigned bytecodeIndex;
    };

    // Near calls can only be patched to other JIT code, regular calls can be patched to JIT code or relinked to stub functions.
    void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction);
    void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction);
    void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction);

    class JIT : private JSInterfaceJIT {
        friend class JITStubCall;
        friend struct PropertyStubCompilationInfo;

        using MacroAssembler::Jump;
        using MacroAssembler::JumpList;
        using MacroAssembler::Label;

        static const uintptr_t patchGetByIdDefaultStructure = unusedPointer;
        static const int patchGetByIdDefaultOffset = 0;
        // Magic number - initial offset cannot be representable as a signed 8bit value, or the X86Assembler
        // will compress the displacement, and we may not be able to fit a patched offset.
        static const int patchPutByIdDefaultOffset = 256;

    public:
        static JITCode compile(VM* vm, CodeBlock* codeBlock, JITCompilationEffort effort, CodePtr* functionEntryArityCheck = 0)
        {
            return JIT(vm, codeBlock).privateCompile(functionEntryArityCheck, effort);
        }

        static void compileClosureCall(VM* vm, CallLinkInfo* callLinkInfo, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, Structure* expectedStructure, ExecutableBase* expectedExecutable, MacroAssemblerCodePtr codePtr)
        {
            JIT jit(vm, callerCodeBlock);
            jit.m_bytecodeOffset = callLinkInfo->codeOrigin.bytecodeIndex;
            jit.privateCompileClosureCall(callLinkInfo, calleeCodeBlock, expectedStructure, expectedExecutable, codePtr);
        }

        static void compileGetByIdProto(VM* vm, CallFrame* callFrame, CodeBlock* codeBlock, StructureStubInfo* stubInfo, Structure* structure, Structure* prototypeStructure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompileGetByIdProto(stubInfo, structure, prototypeStructure, ident, slot, cachedOffset, returnAddress, callFrame);
        }

        static void compileGetByIdSelfList(VM* vm, CodeBlock* codeBlock, StructureStubInfo* stubInfo, PolymorphicAccessStructureList* polymorphicStructures, int currentIndex, Structure* structure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompileGetByIdSelfList(stubInfo, polymorphicStructures, currentIndex, structure, ident, slot, cachedOffset);
        }
        static void compileGetByIdProtoList(VM* vm, CallFrame* callFrame, CodeBlock* codeBlock, StructureStubInfo* stubInfo, PolymorphicAccessStructureList* prototypeStructureList, int currentIndex, Structure* structure, Structure* prototypeStructure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompileGetByIdProtoList(stubInfo, prototypeStructureList, currentIndex, structure, prototypeStructure, ident, slot, cachedOffset, callFrame);
        }
        static void compileGetByIdChainList(VM* vm, CallFrame* callFrame, CodeBlock* codeBlock, StructureStubInfo* stubInfo, PolymorphicAccessStructureList* prototypeStructureList, int currentIndex, Structure* structure, StructureChain* chain, size_t count, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompileGetByIdChainList(stubInfo, prototypeStructureList, currentIndex, structure, chain, count, ident, slot, cachedOffset, callFrame);
        }

        static void compileGetByIdChain(VM* vm, CallFrame* callFrame, CodeBlock* codeBlock, StructureStubInfo* stubInfo, Structure* structure, StructureChain* chain, size_t count, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompileGetByIdChain(stubInfo, structure, chain, count, ident, slot, cachedOffset, returnAddress, callFrame);
        }

        static void compilePutByIdTransition(VM* vm, CodeBlock* codeBlock, StructureStubInfo* stubInfo, Structure* oldStructure, Structure* newStructure, PropertyOffset cachedOffset, StructureChain* chain, ReturnAddressPtr returnAddress, bool direct)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = stubInfo->bytecodeIndex;
            jit.privateCompilePutByIdTransition(stubInfo, oldStructure, newStructure, cachedOffset, chain, returnAddress, direct);
        }

        static void compileGetByVal(VM* vm, CodeBlock* codeBlock, ByValInfo* byValInfo, ReturnAddressPtr returnAddress, JITArrayMode arrayMode)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = byValInfo->bytecodeIndex;
            jit.privateCompileGetByVal(byValInfo, returnAddress, arrayMode);
        }

        static void compilePutByVal(VM* vm, CodeBlock* codeBlock, ByValInfo* byValInfo, ReturnAddressPtr returnAddress, JITArrayMode arrayMode)
        {
            JIT jit(vm, codeBlock);
            jit.m_bytecodeOffset = byValInfo->bytecodeIndex;
            jit.privateCompilePutByVal(byValInfo, returnAddress, arrayMode);
        }

        static CodeRef compileCTINativeCall(VM* vm, NativeFunction func)
        {
            if (!vm->canUseJIT()) {
#if ENABLE(LLINT)
                return CodeRef::createLLIntCodeRef(llint_native_call_trampoline);
#else
                return CodeRef();
#endif
            }
            JIT jit(vm, 0);
            return jit.privateCompileCTINativeCall(vm, func);
        }

        static void resetPatchGetById(RepatchBuffer&, StructureStubInfo*);
        static void resetPatchPutById(RepatchBuffer&, StructureStubInfo*);
        static void patchGetByIdSelf(CodeBlock*, StructureStubInfo*, Structure*, PropertyOffset cachedOffset, ReturnAddressPtr);
        static void patchPutByIdReplace(CodeBlock*, StructureStubInfo*, Structure*, PropertyOffset cachedOffset, ReturnAddressPtr, bool direct);

        static void compilePatchGetArrayLength(VM* vm, CodeBlock* codeBlock, ReturnAddressPtr returnAddress)
        {
            JIT jit(vm, codeBlock);
#if ENABLE(DFG_JIT)
            // Force profiling to be enabled during stub generation.
            jit.m_canBeOptimized = true;
            jit.m_canBeOptimizedOrInlined = true;
            jit.m_shouldEmitProfiling = true;
#endif // ENABLE(DFG_JIT)
            return jit.privateCompilePatchGetArrayLength(returnAddress);
        }

        static void linkFor(JSFunction* callee, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, CodePtr, CallLinkInfo*, VM*, CodeSpecializationKind);
        static void linkSlowCall(CodeBlock* callerCodeBlock, CallLinkInfo*);

    private:
        JIT(VM*, CodeBlock* = 0);

        void privateCompileMainPass();
        void privateCompileLinkPass();
        void privateCompileSlowCases();
        JITCode privateCompile(CodePtr* functionEntryArityCheck, JITCompilationEffort);

        void privateCompileClosureCall(CallLinkInfo*, CodeBlock* calleeCodeBlock, Structure*, ExecutableBase*, MacroAssemblerCodePtr);

        void privateCompileGetByIdProto(StructureStubInfo*, Structure*, Structure* prototypeStructure, const Identifier&, const PropertySlot&, PropertyOffset cachedOffset, ReturnAddressPtr, CallFrame*);
        void privateCompileGetByIdSelfList(StructureStubInfo*, PolymorphicAccessStructureList*, int, Structure*, const Identifier&, const PropertySlot&, PropertyOffset cachedOffset);
        void privateCompileGetByIdProtoList(StructureStubInfo*, PolymorphicAccessStructureList*, int, Structure*, Structure* prototypeStructure, const Identifier&, const PropertySlot&, PropertyOffset cachedOffset, CallFrame*);
        void privateCompileGetByIdChainList(StructureStubInfo*, PolymorphicAccessStructureList*, int, Structure*, StructureChain*, size_t count, const Identifier&, const PropertySlot&, PropertyOffset cachedOffset, CallFrame*);
        void privateCompileGetByIdChain(StructureStubInfo*, Structure*, StructureChain*, size_t count, const Identifier&, const PropertySlot&, PropertyOffset cachedOffset, ReturnAddressPtr, CallFrame*);
        void privateCompilePutByIdTransition(StructureStubInfo*, Structure*, Structure*, PropertyOffset cachedOffset, StructureChain*, ReturnAddressPtr, bool direct);

        void privateCompileGetByVal(ByValInfo*, ReturnAddressPtr, JITArrayMode);
        void privateCompilePutByVal(ByValInfo*, ReturnAddressPtr, JITArrayMode);

        Label privateCompileCTINativeCall(VM*, bool isConstruct = false);
        CodeRef privateCompileCTINativeCall(VM*, NativeFunction);
        void privateCompilePatchGetArrayLength(ReturnAddressPtr returnAddress);

        static bool isDirectPutById(StructureStubInfo*);

        void addSlowCase(Jump);
        void addSlowCase(JumpList);
        void addSlowCase();
        void addJump(Jump, int);
        void emitJumpSlowToHot(Jump, int);

        void compileOpCall(OpcodeID, Instruction*, unsigned callLinkInfoIndex);
        void compileOpCallSlowCase(OpcodeID, Instruction*, Vector<SlowCaseEntry>::iterator&, unsigned callLinkInfoIndex);
        void compileLoadVarargs(Instruction*);
        void compileCallEval();
        void compileCallEvalSlowCase(Vector<SlowCaseEntry>::iterator&);

        enum CompileOpStrictEqType { OpStrictEq, OpNStrictEq };
        void compileOpStrictEq(Instruction* instruction, CompileOpStrictEqType type);
        bool isOperandConstantImmediateDouble(unsigned src);

        void emitLoadDouble(int index, FPRegisterID value);
        void emitLoadInt32ToDouble(int index, FPRegisterID value);
        Jump emitJumpIfNotObject(RegisterID structureReg);

        Jump addStructureTransitionCheck(JSCell*, Structure*, StructureStubInfo*, RegisterID scratch);
        void addStructureTransitionCheck(JSCell*, Structure*, StructureStubInfo*, JumpList& failureCases, RegisterID scratch);
        void testPrototype(JSValue, JumpList& failureCases, StructureStubInfo*);

        enum WriteBarrierMode { UnconditionalWriteBarrier, ShouldFilterImmediates };
        // value register in write barrier is used before any scratch registers
        // so may safely be the same as either of the scratch registers.
        void emitWriteBarrier(RegisterID owner, RegisterID valueTag, RegisterID scratch, RegisterID scratch2, WriteBarrierMode, WriteBarrierUseKind);
        void emitWriteBarrier(JSCell* owner, RegisterID value, RegisterID scratch, WriteBarrierMode, WriteBarrierUseKind);

        template<typename StructureType> // StructureType can be RegisterID or ImmPtr.
        void emitAllocateJSObject(RegisterID allocator, StructureType, RegisterID result, RegisterID scratch);

#if ENABLE(VALUE_PROFILER)
        // This assumes that the value to profile is in regT0 and that regT3 is available for
        // scratch.
        void emitValueProfilingSite(ValueProfile*);
        void emitValueProfilingSite(unsigned bytecodeOffset);
        void emitValueProfilingSite();
#else
        void emitValueProfilingSite(unsigned) { }
        void emitValueProfilingSite() { }
#endif
        void emitArrayProfilingSite(RegisterID structureAndIndexingType, RegisterID scratch, ArrayProfile*);
        void emitArrayProfilingSiteForBytecodeIndex(RegisterID structureAndIndexingType, RegisterID scratch, unsigned bytecodeIndex);
        void emitArrayProfileStoreToHoleSpecialCase(ArrayProfile*);
        void emitArrayProfileOutOfBoundsSpecialCase(ArrayProfile*);

        JITArrayMode chooseArrayMode(ArrayProfile*);

        // Property is in regT1, base is in regT0. regT2 contains indexing type.
        // Property is int-checked and zero extended. Base is cell checked.
        // Structure is already profiled. Returns the slow cases. Fall-through
        // case contains result in regT0, and it is not yet profiled.
        JumpList emitInt32GetByVal(Instruction* instruction, PatchableJump& badType) { return emitContiguousGetByVal(instruction, badType, Int32Shape); }
        JumpList emitDoubleGetByVal(Instruction*, PatchableJump& badType);
        JumpList emitContiguousGetByVal(Instruction*, PatchableJump& badType, IndexingType expectedShape = ContiguousShape);
        JumpList emitArrayStorageGetByVal(Instruction*, PatchableJump& badType);
        JumpList emitIntTypedArrayGetByVal(Instruction*, PatchableJump& badType, const TypedArrayDescriptor&, size_t elementSize, TypedArraySignedness);
        JumpList emitFloatTypedArrayGetByVal(Instruction*, PatchableJump& badType, const TypedArrayDescriptor&, size_t elementSize);

        // Property is in regT0, base is in regT0. regT2 contains indecing type.
        // The value to store is not yet loaded. Property is int-checked and
        // zero-extended. Base is cell checked. Structure is already profiled.
        // returns the slow cases.
        JumpList emitInt32PutByVal(Instruction* currentInstruction, PatchableJump& badType)
        {
            return emitGenericContiguousPutByVal(currentInstruction, badType, Int32Shape);
        }
        JumpList emitDoublePutByVal(Instruction* currentInstruction, PatchableJump& badType)
        {
            return emitGenericContiguousPutByVal(currentInstruction, badType, DoubleShape);
        }
        JumpList emitContiguousPutByVal(Instruction* currentInstruction, PatchableJump& badType)
        {
            return emitGenericContiguousPutByVal(currentInstruction, badType);
        }
        JumpList emitGenericContiguousPutByVal(Instruction*, PatchableJump& badType, IndexingType indexingShape = ContiguousShape);
        JumpList emitArrayStoragePutByVal(Instruction*, PatchableJump& badType);
        JumpList emitIntTypedArrayPutByVal(Instruction*, PatchableJump& badType, const TypedArrayDescriptor&, size_t elementSize, TypedArraySignedness, TypedArrayRounding);
        JumpList emitFloatTypedArrayPutByVal(Instruction*, PatchableJump& badType, const TypedArrayDescriptor&, size_t elementSize);

        enum FinalObjectMode { MayBeFinal, KnownNotFinal };

#if USE(JSVALUE32_64)
        bool getOperandConstantImmediateInt(unsigned op1, unsigned op2, unsigned& op, int32_t& constant);

        void emitLoadTag(int index, RegisterID tag);
        void emitLoadPayload(int index, RegisterID payload);

        void emitLoad(const JSValue& v, RegisterID tag, RegisterID payload);
        void emitLoad(int index, RegisterID tag, RegisterID payload, RegisterID base = callFrameRegister);
        void emitLoad2(int index1, RegisterID tag1, RegisterID payload1, int index2, RegisterID tag2, RegisterID payload2);

        void emitStore(int index, RegisterID tag, RegisterID payload, RegisterID base = callFrameRegister);
        void emitStore(int index, const JSValue constant, RegisterID base = callFrameRegister);
        void emitStoreInt32(int index, RegisterID payload, bool indexIsInt32 = false);
        void emitStoreInt32(int index, TrustedImm32 payload, bool indexIsInt32 = false);
        void emitStoreAndMapInt32(int index, RegisterID tag, RegisterID payload, bool indexIsInt32, size_t opcodeLength);
        void emitStoreCell(int index, RegisterID payload, bool indexIsCell = false);
        void emitStoreBool(int index, RegisterID payload, bool indexIsBool = false);
        void emitStoreDouble(int index, FPRegisterID value);

        bool isLabeled(unsigned bytecodeOffset);
        void map(unsigned bytecodeOffset, int virtualRegisterIndex, RegisterID tag, RegisterID payload);
        void unmap(RegisterID);
        void unmap();
        bool isMapped(int virtualRegisterIndex);
        bool getMappedPayload(int virtualRegisterIndex, RegisterID& payload);
        bool getMappedTag(int virtualRegisterIndex, RegisterID& tag);

        void emitJumpSlowCaseIfNotJSCell(int virtualRegisterIndex);
        void emitJumpSlowCaseIfNotJSCell(int virtualRegisterIndex, RegisterID tag);

        void compileGetByIdHotPath(Identifier*);
        void compileGetByIdSlowCase(int resultVReg, int baseVReg, Identifier*, Vector<SlowCaseEntry>::iterator&);
        void compileGetDirectOffset(RegisterID base, RegisterID resultTag, RegisterID resultPayload, PropertyOffset cachedOffset);
        void compileGetDirectOffset(JSObject* base, RegisterID resultTag, RegisterID resultPayload, PropertyOffset cachedOffset);
        void compileGetDirectOffset(RegisterID base, RegisterID resultTag, RegisterID resultPayload, RegisterID offset, FinalObjectMode = MayBeFinal);
        void compilePutDirectOffset(RegisterID base, RegisterID valueTag, RegisterID valuePayload, PropertyOffset cachedOffset);

        // Arithmetic opcode helpers
        void emitAdd32Constant(unsigned dst, unsigned op, int32_t constant, ResultType opType);
        void emitSub32Constant(unsigned dst, unsigned op, int32_t constant, ResultType opType);
        void emitBinaryDoubleOp(OpcodeID, unsigned dst, unsigned op1, unsigned op2, OperandTypes, JumpList& notInt32Op1, JumpList& notInt32Op2, bool op1IsInRegisters = true, bool op2IsInRegisters = true);

#if CPU(ARM_TRADITIONAL)
        // sequenceOpCall
        static const int sequenceOpCallInstructionSpace = 12;
        static const int sequenceOpCallConstantSpace = 2;
        // sequenceGetByIdHotPath
        static const int sequenceGetByIdHotPathInstructionSpace = 36;
        static const int sequenceGetByIdHotPathConstantSpace = 4;
        // sequenceGetByIdSlowCase
        static const int sequenceGetByIdSlowCaseInstructionSpace = 80;
        static const int sequenceGetByIdSlowCaseConstantSpace = 4;
        // sequencePutById
        static const int sequencePutByIdInstructionSpace = 36;
        static const int sequencePutByIdConstantSpace = 4;
#elif CPU(SH4)
        // sequenceOpCall
        static const int sequenceOpCallInstructionSpace = 12;
        static const int sequenceOpCallConstantSpace = 2;
        // sequenceGetByIdHotPath
        static const int sequenceGetByIdHotPathInstructionSpace = 36;
        static const int sequenceGetByIdHotPathConstantSpace = 5;
        // sequenceGetByIdSlowCase
        static const int sequenceGetByIdSlowCaseInstructionSpace = 38;
        static const int sequenceGetByIdSlowCaseConstantSpace = 4;
        // sequencePutById
        static const int sequencePutByIdInstructionSpace = 36;
        static const int sequencePutByIdConstantSpace = 5;
#endif

#else // USE(JSVALUE32_64)
        /* This function is deprecated. */
        void emitGetJITStubArg(unsigned argumentNumber, RegisterID dst);

        void emitGetVirtualRegister(int src, RegisterID dst);
        void emitGetVirtualRegisters(int src1, RegisterID dst1, int src2, RegisterID dst2);
        void emitPutVirtualRegister(unsigned dst, RegisterID from = regT0);
        void emitStoreCell(unsigned dst, RegisterID payload, bool /* only used in JSValue32_64 */ = false)
        {
            emitPutVirtualRegister(dst, payload);
        }

        int32_t getConstantOperandImmediateInt(unsigned src);

        void killLastResultRegister();

        Jump emitJumpIfJSCell(RegisterID);
        Jump emitJumpIfBothJSCells(RegisterID, RegisterID, RegisterID);
        void emitJumpSlowCaseIfJSCell(RegisterID);
        void emitJumpSlowCaseIfNotJSCell(RegisterID);
        void emitJumpSlowCaseIfNotJSCell(RegisterID, int VReg);
        Jump emitJumpIfImmediateInteger(RegisterID);
        Jump emitJumpIfNotImmediateInteger(RegisterID);
        Jump emitJumpIfNotImmediateIntegers(RegisterID, RegisterID, RegisterID);
        void emitJumpSlowCaseIfNotImmediateInteger(RegisterID);
        void emitJumpSlowCaseIfNotImmediateNumber(RegisterID);
        void emitJumpSlowCaseIfNotImmediateIntegers(RegisterID, RegisterID, RegisterID);

        void emitFastArithReTagImmediate(RegisterID src, RegisterID dest);

        void emitTagAsBoolImmediate(RegisterID reg);
        void compileBinaryArithOp(OpcodeID, unsigned dst, unsigned src1, unsigned src2, OperandTypes opi);
        void compileBinaryArithOpSlowCase(OpcodeID, Vector<SlowCaseEntry>::iterator&, unsigned dst, unsigned src1, unsigned src2, OperandTypes, bool op1HasImmediateIntFastCase, bool op2HasImmediateIntFastCase);

        void compileGetByIdHotPath(int baseVReg, Identifier*);
        void compileGetByIdSlowCase(int resultVReg, int baseVReg, Identifier*, Vector<SlowCaseEntry>::iterator&);
        void compileGetDirectOffset(RegisterID base, RegisterID result, PropertyOffset cachedOffset);
        void compileGetDirectOffset(JSObject* base, RegisterID result, PropertyOffset cachedOffset);
        void compileGetDirectOffset(RegisterID base, RegisterID result, RegisterID offset, RegisterID scratch, FinalObjectMode = MayBeFinal);
        void compilePutDirectOffset(RegisterID base, RegisterID value, PropertyOffset cachedOffset);

#endif // USE(JSVALUE32_64)

#if (defined(ASSEMBLER_HAS_CONSTANT_POOL) && ASSEMBLER_HAS_CONSTANT_POOL)
#define BEGIN_UNINTERRUPTED_SEQUENCE(name) do { beginUninterruptedSequence(name ## InstructionSpace, name ## ConstantSpace); } while (false)
#define END_UNINTERRUPTED_SEQUENCE_FOR_PUT(name, dst) do { endUninterruptedSequence(name ## InstructionSpace, name ## ConstantSpace, dst); } while (false)
#define END_UNINTERRUPTED_SEQUENCE(name) END_UNINTERRUPTED_SEQUENCE_FOR_PUT(name, 0)

        void beginUninterruptedSequence(int, int);
        void endUninterruptedSequence(int, int, int);

#else
#define BEGIN_UNINTERRUPTED_SEQUENCE(name)
#define END_UNINTERRUPTED_SEQUENCE(name)
#define END_UNINTERRUPTED_SEQUENCE_FOR_PUT(name, dst)
#endif

        void emit_compareAndJump(OpcodeID, unsigned op1, unsigned op2, unsigned target, RelationalCondition);
        void emit_compareAndJumpSlow(unsigned op1, unsigned op2, unsigned target, DoubleCondition, int (JIT_STUB *stub)(STUB_ARGS_DECLARATION), bool invert, Vector<SlowCaseEntry>::iterator&);

        void emit_op_add(Instruction*);
        void emit_op_bitand(Instruction*);
        void emit_op_bitor(Instruction*);
        void emit_op_bitxor(Instruction*);
        void emit_op_call(Instruction*);
        void emit_op_call_eval(Instruction*);
        void emit_op_call_varargs(Instruction*);
        void emit_op_call_put_result(Instruction*);
        void emit_op_catch(Instruction*);
        void emit_op_construct(Instruction*);
        void emit_op_get_callee(Instruction*);
        void emit_op_create_this(Instruction*);
        void emit_op_convert_this(Instruction*);
        void emit_op_create_arguments(Instruction*);
        void emit_op_debug(Instruction*);
        void emit_op_del_by_id(Instruction*);
        void emit_op_div(Instruction*);
        void emit_op_end(Instruction*);
        void emit_op_enter(Instruction*);
        void emit_op_create_activation(Instruction*);
        void emit_op_eq(Instruction*);
        void emit_op_eq_null(Instruction*);
        void emit_op_get_by_id(Instruction*);
        void emit_op_get_arguments_length(Instruction*);
        void emit_op_get_by_val(Instruction*);
        void emit_op_get_argument_by_val(Instruction*);
        void emit_op_get_by_pname(Instruction*);
        void emit_op_init_lazy_reg(Instruction*);
        void emit_op_check_has_instance(Instruction*);
        void emit_op_instanceof(Instruction*);
        void emit_op_is_undefined(Instruction*);
        void emit_op_is_boolean(Instruction*);
        void emit_op_is_number(Instruction*);
        void emit_op_is_string(Instruction*);
        void emit_op_jeq_null(Instruction*);
        void emit_op_jfalse(Instruction*);
        void emit_op_jmp(Instruction*);
        void emit_op_jneq_null(Instruction*);
        void emit_op_jneq_ptr(Instruction*);
        void emit_op_jless(Instruction*);
        void emit_op_jlesseq(Instruction*);
        void emit_op_jgreater(Instruction*);
        void emit_op_jgreatereq(Instruction*);
        void emit_op_jnless(Instruction*);
        void emit_op_jnlesseq(Instruction*);
        void emit_op_jngreater(Instruction*);
        void emit_op_jngreatereq(Instruction*);
        void emit_op_jtrue(Instruction*);
        void emit_op_loop_hint(Instruction*);
        void emit_op_lshift(Instruction*);
        void emit_op_mod(Instruction*);
        void emit_op_mov(Instruction*);
        void emit_op_mul(Instruction*);
        void emit_op_negate(Instruction*);
        void emit_op_neq(Instruction*);
        void emit_op_neq_null(Instruction*);
        void emit_op_new_array(Instruction*);
        void emit_op_new_array_with_size(Instruction*);
        void emit_op_new_array_buffer(Instruction*);
        void emit_op_new_func(Instruction*);
        void emit_op_new_func_exp(Instruction*);
        void emit_op_new_object(Instruction*);
        void emit_op_new_regexp(Instruction*);
        void emit_op_get_pnames(Instruction*);
        void emit_op_next_pname(Instruction*);
        void emit_op_not(Instruction*);
        void emit_op_nstricteq(Instruction*);
        void emit_op_pop_scope(Instruction*);
        void emit_op_dec(Instruction*);
        void emit_op_inc(Instruction*);
        void emit_op_profile_did_call(Instruction*);
        void emit_op_profile_will_call(Instruction*);
        void emit_op_push_name_scope(Instruction*);
        void emit_op_push_with_scope(Instruction*);
        void emit_op_put_by_id(Instruction*);
        void emit_op_put_by_index(Instruction*);
        void emit_op_put_by_val(Instruction*);
        void emit_op_put_getter_setter(Instruction*);
        void emit_op_init_global_const(Instruction*);
        void emit_op_init_global_const_check(Instruction*);
        void emit_resolve_operations(ResolveOperations*, const int* base, const int* value);
        void emitSlow_link_resolve_operations(ResolveOperations*, Vector<SlowCaseEntry>::iterator&);
        void emit_op_resolve(Instruction*);
        void emit_op_resolve_base(Instruction*);
        void emit_op_resolve_with_base(Instruction*);
        void emit_op_resolve_with_this(Instruction*);
        void emit_op_put_to_base(Instruction*);
        void emit_op_ret(Instruction*);
        void emit_op_ret_object_or_this(Instruction*);
        void emit_op_rshift(Instruction*);
        void emit_op_strcat(Instruction*);
        void emit_op_stricteq(Instruction*);
        void emit_op_sub(Instruction*);
        void emit_op_switch_char(Instruction*);
        void emit_op_switch_imm(Instruction*);
        void emit_op_switch_string(Instruction*);
        void emit_op_tear_off_activation(Instruction*);
        void emit_op_tear_off_arguments(Instruction*);
        void emit_op_throw(Instruction*);
        void emit_op_throw_static_error(Instruction*);
        void emit_op_to_number(Instruction*);
        void emit_op_to_primitive(Instruction*);
        void emit_op_unexpected_load(Instruction*);
        void emit_op_urshift(Instruction*);
        void emit_op_get_scoped_var(Instruction*);
        void emit_op_put_scoped_var(Instruction*);

        void emitSlow_op_add(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_bitand(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_bitor(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_bitxor(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_call(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_call_eval(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_call_varargs(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_construct(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_convert_this(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_create_this(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_div(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_eq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_get_by_id(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_get_arguments_length(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_get_by_val(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_get_argument_by_val(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_get_by_pname(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_check_has_instance(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_instanceof(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jfalse(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jless(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jlesseq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jgreater(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jgreatereq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jnless(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jnlesseq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jngreater(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jngreatereq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_jtrue(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_loop_hint(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_lshift(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_mod(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_mul(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_negate(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_neq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_new_object(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_not(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_nstricteq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_dec(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_inc(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_put_by_id(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_put_by_val(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_init_global_const_check(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_rshift(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_stricteq(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_sub(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_to_number(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_to_primitive(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_urshift(Instruction*, Vector<SlowCaseEntry>::iterator&);

        void emitSlow_op_resolve(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_resolve_base(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_resolve_with_base(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_resolve_with_this(Instruction*, Vector<SlowCaseEntry>::iterator&);
        void emitSlow_op_put_to_base(Instruction*, Vector<SlowCaseEntry>::iterator&);

        void emitRightShift(Instruction*, bool isUnsigned);
        void emitRightShiftSlowCase(Instruction*, Vector<SlowCaseEntry>::iterator&, bool isUnsigned);

        void emitInitRegister(unsigned dst);

        void emitPutIntToCallFrameHeader(RegisterID from, JSStack::CallFrameHeaderEntry);
        void emitGetFromCallFrameHeaderPtr(JSStack::CallFrameHeaderEntry, RegisterID to, RegisterID from = callFrameRegister);
        void emitGetFromCallFrameHeader32(JSStack::CallFrameHeaderEntry, RegisterID to, RegisterID from = callFrameRegister);
#if USE(JSVALUE64)
        void emitGetFromCallFrameHeader64(JSStack::CallFrameHeaderEntry, RegisterID to, RegisterID from = callFrameRegister);
#endif

        JSValue getConstantOperand(unsigned src);
        bool isOperandConstantImmediateInt(unsigned src);
        bool isOperandConstantImmediateChar(unsigned src);

        bool atJumpTarget();

        Jump getSlowCase(Vector<SlowCaseEntry>::iterator& iter)
        {
            return iter++->from;
        }
        void linkSlowCase(Vector<SlowCaseEntry>::iterator& iter)
        {
            iter->from.link(this);
            ++iter;
        }
        void linkDummySlowCase(Vector<SlowCaseEntry>::iterator& iter)
        {
            ASSERT(!iter->from.isSet());
            ++iter;
        }
        void linkSlowCaseIfNotJSCell(Vector<SlowCaseEntry>::iterator&, int virtualRegisterIndex);

        Jump checkStructure(RegisterID reg, Structure* structure);

        void restoreArgumentReferenceForTrampoline();
        void updateTopCallFrame();

        Call emitNakedCall(CodePtr function = CodePtr());

        // Loads the character value of a single character string into dst.
        void emitLoadCharacterString(RegisterID src, RegisterID dst, JumpList& failures);

#if ENABLE(DFG_JIT)
        void emitEnterOptimizationCheck();
#else
        void emitEnterOptimizationCheck() { }
#endif

#ifndef NDEBUG
        void printBytecodeOperandTypes(unsigned src1, unsigned src2);
#endif

#if ENABLE(SAMPLING_FLAGS)
        void setSamplingFlag(int32_t);
        void clearSamplingFlag(int32_t);
#endif

#if ENABLE(SAMPLING_COUNTERS)
        void emitCount(AbstractSamplingCounter&, int32_t = 1);
#endif

#if ENABLE(OPCODE_SAMPLING)
        void sampleInstruction(Instruction*, bool = false);
#endif

#if ENABLE(CODEBLOCK_SAMPLING)
        void sampleCodeBlock(CodeBlock*);
#else
        void sampleCodeBlock(CodeBlock*) {}
#endif

#if ENABLE(DFG_JIT)
        bool canBeOptimized() { return m_canBeOptimized; }
        bool canBeOptimizedOrInlined() { return m_canBeOptimizedOrInlined; }
        bool shouldEmitProfiling() { return m_shouldEmitProfiling; }
#else
        bool canBeOptimized() { return false; }
        bool canBeOptimizedOrInlined() { return false; }
        // Enables use of value profiler with tiered compilation turned off,
        // in which case all code gets profiled.
        bool shouldEmitProfiling() { return false; }
#endif

        Interpreter* m_interpreter;
        VM* m_vm;
        CodeBlock* m_codeBlock;

        Vector<CallRecord> m_calls;
        Vector<Label> m_labels;
        Vector<PropertyStubCompilationInfo> m_propertyAccessCompilationInfo;
        Vector<ByValCompilationInfo> m_byValCompilationInfo;
        Vector<StructureStubCompilationInfo> m_callStructureStubCompilationInfo;
        Vector<JumpTable> m_jmpTable;

        unsigned m_bytecodeOffset;
        Vector<SlowCaseEntry> m_slowCases;
        Vector<SwitchRecord> m_switches;

        unsigned m_propertyAccessInstructionIndex;
        unsigned m_byValInstructionIndex;
        unsigned m_globalResolveInfoIndex;
        unsigned m_callLinkInfoIndex;

#if USE(JSVALUE32_64)
        unsigned m_jumpTargetIndex;
        unsigned m_mappedBytecodeOffset;
        int m_mappedVirtualRegisterIndex;
        RegisterID m_mappedTag;
        RegisterID m_mappedPayload;
#else
        int m_lastResultBytecodeRegister;
#endif
        unsigned m_jumpTargetsPosition;

#ifndef NDEBUG
#if defined(ASSEMBLER_HAS_CONSTANT_POOL) && ASSEMBLER_HAS_CONSTANT_POOL
        Label m_uninterruptedInstructionSequenceBegin;
        int m_uninterruptedConstantSequenceBegin;
#endif
#endif
        OwnPtr<JITDisassembler> m_disassembler;
        RefPtr<Profiler::Compilation> m_compilation;
        WeakRandom m_randomGenerator;
        static CodeRef stringGetByValStubGenerator(VM*);

#if ENABLE(VALUE_PROFILER)
        bool m_canBeOptimized;
        bool m_canBeOptimizedOrInlined;
        bool m_shouldEmitProfiling;
#endif
    } JIT_CLASS_ALIGNMENT;

} // namespace JSC

#endif // ENABLE(JIT)

#endif // JIT_h


text:
'use strict';

var mongoose = require('mongoose'),
    LocalStrategy = require('passport-local').Strategy,
    // TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    // GitHubStrategy = require('passport-github').Strategy,
    // GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    // LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    config = require('./config');

module.exports = function(passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function(user, done) {
        console.log('serializeUser');
        done(null, user.id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function(id, done) {
        console.log('deserializeUser');
        User.findOne({
            _id: id
        }, '-salt -hashed_password', function(err, user) {
            console.log('err: ');
            console.log(err);
            console.log('user:');
            console.log(user);
            done(err, user);
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
            usernameField: 'email',
            passwordField: 'password'
        },
        function(email, password, done) {
            console.log('local strategy called.');
            User.findOne({
                email: email
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    return done(null, false, {
                        message: 'Unknown user'
                    });
                }
                if (!user.authenticate(password)) {
                    return done(null, false, {
                        message: 'Invalid password'
                    });
                }
                return done(null, user);
            });
        }
    ));

    // Use facebook strategy
    passport.use(new FacebookStrategy({
            clientID: config.facebook.clientID,
            clientSecret: config.facebook.clientSecret,
            callbackURL: config.facebook.callbackURL,
            profileFields: ['id', 'displayName', 'photos', 'emails']
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'facebook.id': profile.id
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.username || profile.emails[0].value.split('@')[0],
                        provider: 'facebook',
                        facebook: profile._json
                    });

                    var account = new Account();
                    user.save(function(err) {
                        if (err) console.log(err);
                        account.userEmail = user.email;
                        account.currentBalance = 0;
                        account.save(function (err) {
                          if (err) {
                            console.log(err);
                          }
                          // return res.status(200).send({user: user.toObject(), account: account});
                          return done(err, user);
                        });

                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // // Use twitter strategy
    // passport.use(new TwitterStrategy({
    //         consumerKey: config.twitter.clientID,
    //         consumerSecret: config.twitter.clientSecret,
    //         callbackURL: config.twitter.callbackURL
    //     },
    //     function(token, tokenSecret, profile, done) {
    //         User.findOne({
    //             'twitter.id_str': profile.id
    //         }, function(err, user) {
    //             if (err) {
    //                 return done(err);
    //             }
    //             if (!user) {
    //                 user = new User({
    //                     name: profile.displayName,
    //                     username: profile.username,
    //                     provider: 'twitter',
    //                     twitter: profile._json
    //                 });
    //                 user.save(function(err) {
    //                     if (err) console.log(err);
    //                     return done(err, user);
    //                 });
    //             } else {
    //                 return done(err, user);
    //             }
    //         });
    //     }
    // ));

    // // Use github strategy
    // passport.use(new GitHubStrategy({
    //         clientID: config.github.clientID,
    //         clientSecret: config.github.clientSecret,
    //         callbackURL: config.github.callbackURL
    //     },
    //     function(accessToken, refreshToken, profile, done) {
    //         User.findOne({
    //             'github.id': profile.id
    //         }, function(err, user) {
    //             if (!user) {
    //                 user = new User({
    //                     name: profile.displayName,
    //                     email: profile.emails[0].value,
    //                     username: profile.username,
    //                     provider: 'github',
    //                     github: profile._json
    //                 });
    //                 user.save(function(err) {
    //                     if (err) console.log(err);
    //                     return done(err, user);
    //                 });
    //             } else {
    //                 return done(err, user);
    //             }
    //         });
    //     }
    // ));

    // // Use google strategy
    // passport.use(new GoogleStrategy({
    //         clientID: config.google.clientID,
    //         clientSecret: config.google.clientSecret,
    //         callbackURL: config.google.callbackURL
    //     },
    //     function(accessToken, refreshToken, profile, done) {
    //         User.findOne({
    //             'google.id': profile.id
    //         }, function(err, user) {
    //             if (!user) {
    //                 user = new User({
    //                     name: profile.displayName,
    //                     email: profile.emails[0].value,
    //                     username: profile.emails[0].value,
    //                     provider: 'google',
    //                     google: profile._json
    //                 });
    //                 user.save(function(err) {
    //                     if (err) console.log(err);
    //                     return done(err, user);
    //                 });
    //             } else {
    //                 return done(err, user);
    //             }
    //         });
    //     }
    // ));

    // // use linkedin strategy
    // passport.use(new LinkedinStrategy({
    //         consumerKey: config.linkedin.clientID,
    //         consumerSecret: config.linkedin.clientSecret,
    //         callbackURL: config.linkedin.callbackURL,
    //         profileFields: ['id', 'first-name', 'last-name', 'email-address']
    //     },
    //     function(accessToken, refreshToken, profile, done) {
    //         User.findOne({
    //             'linkedin.id': profile.id
    //         }, function(err, user) {
    //             if (!user) {
    //                 user = new User({
    //                     name: profile.displayName,
    //                     email: profile.emails[0].value,
    //                     username: profile.emails[0].value,
    //                     provider: 'linkedin'
    //                 });
    //                 user.save(function(err) {
    //                     if (err) console.log(err);
    //                     return done(err, user);
    //                 });
    //             } else {
    //                 return done(err, user);
    //             }
    //         });
    //     }
    // ));
};

redpajama_set_name: RedPajamaGithub


text:
import supybot.conf as conf
import supybot.registry as registry

def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('ChannelLogger', True)

ChannelLogger = conf.registerPlugin('ChannelLogger')
conf.registerChannelValue(ChannelLogger, 'enable',
    registry.Boolean(True, """Determines whether logging is enabled."""))
conf.registerGlobalValue(ChannelLogger, 'flushImmediately',
    registry.Boolean(False, """Determines whether channel logfiles will be
    flushed anytime they're written to, rather than being buffered by the
    operating system."""))
conf.registerChannelValue(ChannelLogger, 'stripFormatting',
    registry.Boolean(True, """Determines whether formatting characters (such
    as bolding, color, etc.) are removed when writing the logs to disk."""))
conf.registerChannelValue(ChannelLogger, 'timestamp',
    registry.Boolean(True, """Determines whether the logs for this channel are
    timestamped with the timestamp in supybot.log.timestampFormat."""))
conf.registerChannelValue(ChannelLogger, 'noLogPrefix',
    registry.String('[nolog]', """Determines what string a message should be
    prefixed with in order not to be logged.  If you don't want any such
    prefix, just set it to the empty string."""))
conf.registerChannelValue(ChannelLogger, 'rotateLogs',
    registry.Boolean(False, """Determines whether the bot will automatically
    rotate the logs for this channel.  The bot will rotate logs when the
    timestamp for the log changes.  The timestamp is set according to
    the 'filenameTimestamp' configuration variable."""))
conf.registerChannelValue(ChannelLogger, 'filenameTimestamp',
    registry.String('%Y-%m-%d', """Determines how to represent the timestamp
    used for the filename in rotated logs.  When this timestamp changes, the
    old logfiles will be closed and a new one started. The format characters
    for the timestamp are in the time.strftime docs at python.org.  In order
    for your logs to be rotated, you'll also have to enable
    supybot.plugins.ChannelLogger.rotateLogs."""))

conf.registerGlobalValue(ChannelLogger, 'directories',
    registry.Boolean(True, """Determines whether the bot will partition its
    channel logs into separate directories based on different criteria."""))
conf.registerGlobalValue(ChannelLogger.directories, 'network',
    registry.Boolean(True, """Determines whether the bot will use a network
    directory if using directories."""))
conf.registerGlobalValue(ChannelLogger.directories, 'channel',
    registry.Boolean(True, """Determines whether the bot will use a channel
    directory if using directories."""))
conf.registerGlobalValue(ChannelLogger.directories, 'timestamp',
    registry.Boolean(False, """Determines whether the bot will use a timestamp
    (determined by supybot.plugins.ChannelLogger.directories.timestamp.format)
    if using directories."""))
conf.registerGlobalValue(ChannelLogger.directories.timestamp, 'format',
    registry.String('%B', """Determines what timestamp format will be used in
    the directory stucture for channel logs if
    supybot.plugins.ChannelLogger.directories.timestamp is True."""))

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:


text:
/* Interface between ESBMC C parsing foo and pcc's cpp */

void record_define(const char *value); /* IE, cmdline -D, "bees=dangerous"; */
void record_include(const char *value); /* Similar, include path name */
void record_builtin_macros(); /* Insert builtin macros into sym table */
int open_output_file(const char *name); /* Obvious */
void fin(); /* Flushes buffers and closes file */
int pushfile(char *name);
int pushfile2(const char *fname, const char *fn, int idx, void *incs);
void fastscan();

void cpp_clear(void); // Clear some memory; doesn't free it though.


text:
define(["knockout", "crossroads", "hasher", "sitemap", "mylib", "./extentions/knockout.subscribable.subscribeboth"], function (ko, crossroads, hasher, sitemap, lib) {
	function Router(config) {
		var componentView1 = this.componentView1 = ko.observable({component: 'blank-page'});
		var componentView2 = this.componentView2 = ko.observable({component: 'blank-page'});
		var preloadData = this.preloadData = ko.observable();
		var viewToggle = this.viewToggle = ko.observable(true);
		var currentRoute = this.currentRoute = ko.pureComputed(function() { return viewToggle() ? componentView1() : componentView2(); });
		viewToggle.toggle = function() {
			viewToggle(!viewToggle.peek());
		};

		preloadData.subscribeBoth(function (data, oldData) {
			if(data == oldData)
			{ return; }
			var href = data.href;
			var pageToPreload;
			if (href.hash)
			{ pageToPreload = href.hash.substr(1); }
			else
			{ pageToPreload = href.substr(href.indexOf('#') + 1); }
			crossroads.parse('preload' + pageToPreload);
		});

		var displayedView = ko.pureComputed(function() {
			if(viewToggle())
			{ return componentView1(); }
			else
			{ return componentView2(); }
		});

		var getViews = function() {
			if(viewToggle.peek())
				return {
					currentView: componentView1,
					preloadedView: componentView2
				};
			else
				return {
					currentView: componentView2,
					preloadedView: componentView1
				};
		};

		ko.utils.arrayForEach(config.routes, function (route) {
			if(route.url !== undefined) {
				crossroads.addRoute(route.url, function (requestParams) {
					console.log(route.url || 'home-page');
					var views = getViews();

					if(views.preloadedView.peek() == route && lib.memberwiseEqual(route.params, requestParams)) {
						//View is Preloaded, no preprocessing necessary
					}
					else {
						route.params = requestParams;
						views.preloadedView(route);
					}
					viewToggle.toggle();
					views.currentView({component: 'blank-page'});
				});
				if(route.options && route.options.preloadable) {
					crossroads.addRoute('preload/' + route.url, function (requestParams) {
						console.log('preload/' + (route.url || 'home-page'));
						route.params = requestParams;
						getViews().preloadedView(route);
					});
				}
			}
		});

		activateCrossroads();
	}

	function activateCrossroads() {
		function parseHash(newHash, oldHash) { crossroads.parse(newHash); }
		crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
		//Handle Initial Page
		hasher.initialized.add(function (newHash, oldHash) {
			parseHash(newHash, oldHash);
		});
		hasher.changed.add(parseHash);
		hasher.init();
	}

	var flattenedSitemap = [];
	lib.recurseStructure(
		sitemap.pages,
		function (object) {
			flattenedSitemap.push(object);
			return object.pages;
		}
	);

	return new Router({
		routes: flattenedSitemap
	});
});


text:
<?xml version="1.0" encoding="latin1" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>1999</year><year>2011</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.

      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.

    </legalnotice>

    <title>cosEvent Release Notes</title>
    <prepared></prepared>
    <responsible></responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date>99-02-12</date>
    <rev>A</rev>
    <file>notes.xml</file>

<title>cosEvent 2.1.12</title>

<title>Improvements and New Features</title>
      <list>
        <item>

Erlang/OTP can now be built using parallel make if you
	    limit the number of jobs, for instance using '<c>make
	    -j6</c>' or '<c>make -j10</c>'. '<c>make -j</c>' does not
	    work at the moment because of some missing
	    dependencies.

	    Own Id: OTP-9451

        </item>
      </list>

    <title>cosEvent 2.1.11</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

            Removed superfluous usage of shy in the documentation since it can cause problem if
            a buggy tool is used.

            Own Id: OTP-9319 Aux Id:

        </item>
      </list>

    <title>cosEvent 2.1.10</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

            Eliminated Dialyzer warnings when using exit or throw.

            Own Id: OTP-9050 Aux Id:

        </item>
      </list>

    <title>cosEvent 2.1.9</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

            Test suites published.

            Own Id: OTP-8543 Aux Id:

        </item>
      </list>

    <title>cosEvent 2.1.8</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

            Removed the usage of the codeinclude tag in the documentation.

            Own Id: OTP-8409 Aux Id:

        </item>
      </list>

    <title>cosEvent 2.1.7</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

            The documentation is now built with open source tools (xsltproc and fop)
            that exists on most platforms. One visible change is that the frames are removed.

            Own Id: OTP-8201 Aux Id:

        </item>
      </list>

    <title>cosEvent 2.1.6</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Obsolete guards, e.g. record vs is_record, has been changed
             to avoid compiler warnings.

Own id: OTP-7987

        </item>
      </list>

    <title>cosEvent 2.1.5</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Updated file headers.

Own id: OTP-7837

        </item>
      </list>

    <title>cosEvent 2.1.4</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Documentation source included in open source releases.

Own id: OTP-7595

        </item>
      </list>

    <title>cosEvent 2.1.3</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Updated file headers.

Own id: OTP-7011

        </item>
      </list>

    <title>cosEvent 2.1.2</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

The documentation source has been converted from SGML to XML.

Own id: OTP-6754

        </item>
      </list>

    <title>cosEvent 2.1.1</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

Minor Makefile changes.

Own id: OTP-6701

        </item>
      </list>

    <title>cosEvent 2.1</title>

      <title>Improvements and New Features</title>
      <list type="bulleted">
        <item>

The stub/skeleton-files generated by IC have been improved,
            i.e., depending on the IDL-files, reduced the size of the
            erl- and beam-files and decreased dependencies off Orber's
            Interface Repository. It is necessary to re-compile all IDL-files
            and use COS-applications, including Orber, compiled with
            IC-4.2.

Own id: OTP-4576

        </item>
      </list>

    <title>cosEvent 2.0</title>

      <title>Fixed Bugs and Malfunctions</title>
      <list type="bulleted">
        <item>

This version is a completely new version of the cosEvent
            application; older versions was not compliant with the OMG
            specification. The <c><![CDATA[look and feel]]></c> have been changed
            to be more uniform with the other COS-services.

        </item>
      </list>

</chapter>


text:
require 'nokogiri'
require 'json'
require "active_support"
require 'active_support/core_ext'
require 'uri'
require 'httpclient'
require 'csv_parser'

# version
require 'tatami/version'

# constants
require 'tatami/constants/header_names'
require 'tatami/constants/parser_type'

# error
require 'tatami/wrong_file_format_error'

# models
require 'tatami/models/model_base'
require 'tatami/models/arrange'
require 'tatami/models/arranges'
require 'tatami/models/http_request'
require 'tatami/models/http_response'
require 'tatami/models/assertions/assertion_base'
require 'tatami/models/assertions/content_assertion_item'
require 'tatami/models/assertions/cookie_assertion'
require 'tatami/models/assertions/text_assertion'
require 'tatami/models/assertions/datetime_assertion'
require 'tatami/models/assertions/header_assertion'
require 'tatami/models/assertions/uri_assertion'
require 'tatami/models/assertions/status_code_assertion'
require 'tatami/models/assertions/xsd_assertion'
require 'tatami/models/test_case'
require 'tatami/models/test_cases'
require 'tatami/models/csv/header'

# services
require 'tatami/services/http_request_service'

# parsers
require 'tatami/parsers/mappings/mapping_parser'
require 'tatami/parsers/documents/xml_parser'
require 'tatami/parsers/documents/html_parser'
require 'tatami/parsers/documents/json_parser'
require 'tatami/parsers/documents/text_parser'
require 'tatami/parsers/csv/assertions/content_assertion_parser'
require 'tatami/parsers/csv/assertions/headers_assertion_parser'
require 'tatami/parsers/csv/assertions/cookies_assertion_parser'
require 'tatami/parsers/csv/assertions/text_assertion_parser'
require 'tatami/parsers/csv/assertions/datetime_assertion_parser'
require 'tatami/parsers/csv/assertions/xsd_assertion_parser'
require 'tatami/parsers/csv/assertions/uri_assertion_parser'
require 'tatami/parsers/csv/assertions/status_code_assertion_parser'
require 'tatami/parsers/csv/assertions/assertions_parser'
require 'tatami/parsers/csv/http_request_parser'
require 'tatami/parsers/csv/arranges_parser'
require 'tatami/parsers/csv/header_parser'
require 'tatami/parsers/csv/test_case_parser'
require 'tatami/parsers/csv/test_cases_parser'

# validator
require 'tatami/validators/csv/header_validator'

# executor
require 'tatami/test_executor'


text:
package com.libreworks.stellarbase.security.acl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AclService;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid;

import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;

/**
 * Base ACL Service just to make implementing easier.
 *
 * @author Jonathan Hawk
 */
public abstract class AbstractAclService implements AclService
{
	/**
	 * Implementation that always returns an empty List.
	 *
	 * <p>While the interface for the service states that if no children are
	 * found, null should be returned, who really likes null? I sure don't.
	 *
     * @param parentIdentity to locate children of
     * @return always an empty List
	 */
	public List<ObjectIdentity> findChildren(ObjectIdentity arg0)
	{
		return ImmutableList.of();
	}

	public Acl readAclById(ObjectIdentity object) throws NotFoundException
	{
		return readAclById(object, null);
	}

	public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException
	{
		Map<ObjectIdentity,Acl> map = readAclsById(Arrays.asList(object), sids);
		// to safeguard poor implementations
		Verify.verify(map.containsKey(object), "There should have been an Acl entry for ObjectIdentity %s", new Object[]{object});
		return map.get(object);
	}

	public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException
	{
		return readAclsById(objects, null);
	}
}


text:
function handler = FeatureNormalization()
    handler.NormalizeAllFaces = @NormalizeAllFaces;
    handler.NormalizeDataInFolder = @NormalizeDataInFolder;
    handler.CalculateBestTransformation = @CalculateBestTransformation;
    handler.ProcessImage = @ProcessImage;
    handler.CalculateAffineTransform = @CalculateAffineTransform;
    handler.CreateFeatureMatrix = @CreateFeatureMatrix;
end

function NormalizeAllFaces()
    clc;
    clear all;
    close all;

    figure(),
    hold on
    [~, images, fileNames] = NormalizeDataInFolder();
    hold off

    for k = 1 : length(images)
        fileName = fileNames{k};
        fileName = upper(fileName(1:length(fileName)-4));

        if (mod(k, 5) < 3)
            imwrite(images{k}, strcat('training_images/', fileName, '.pgm'));
        else
            imwrite(images{k}, strcat('test_images/', fileName, '.pgm'));
        end
    end
end

function [features, images, fileNames] = NormalizeDataInFolder()
    % Reference:
    % http://www.mathworks.com/matlabcentral/answers/109068-how-to-load-files-identified-by-the-matlab-function-of-dir

    folder = 'all_faces/';
    if ~isdir(folder)
        display('Unable to locate folder')
        return;
    end

    featurePattern = fullfile(folder, '*.txt');
    featureFiles = dir(featurePattern);
    features = zeros(length(featureFiles), 10);
    fileNames = cell(length(featureFiles), 1);

    for k = 1 : length(featureFiles)
        fullFileName = fullfile(folder, featureFiles(k).name);
        fprintf(1, 'Now reading %s\n', fullFileName);
        featuresMatrix = load(fullFileName)';
        features(k, :) = featuresMatrix(:);
        display(size(featureFiles(k).name))
    end

    % Fixed facial features positions to be considered
    P1 = [13; 20];
    P2 = [50; 20];
    P3 = [34; 34];
    P4 = [16; 50];
    P5 = [48; 50];

    % Initial vector b to be used in Ax = b for feature normalization
    b0 = [P1; P2; P3; P4; P5];

    % Fixed image size
    blockSize = 64;

    % Calculate the affine transformation
    F = CalculateBestTransformation(features, b0, 0.01);

    imageFiles = dir(fullfile(folder, '*.jpg'));
    images = cell(length(imageFiles), 1);

    for k = 1 : length(imageFiles)
        fullFileName = fullfile(folder, imageFiles(k).name);
        fprintf(1, 'Now reading %s\n', fullFileName);
        I = im2double(rgb2gray(imread(fullFileName)));
        fileNames{k} = imageFiles(k).name;

        processedImage = ProcessImage(I, features(k, :), F, blockSize);
        images{k} = processedImage;
        %D(k, :) = processedImage(:)';
    end
end

function [Favg] = CalculateBestTransformation(features, b0, threshold)
    N = size(features, 2);
    Favg = features(1, :)';
    Fprev = Favg;

    repeat = true;
    iter = 0;
    while repeat
        FM = CreateFeatureMatrix(Favg);

        Favg = FM * CalculateAffineTransform(FM, b0);
        tmp = Favg;

        for i = 2 : N
            FM = CreateFeatureMatrix(features(i, :)');
            tmp = tmp + FM * CalculateAffineTransform(FM, Favg);
        end

        Favg = tmp ./ N;

        if ((abs(Favg - Fprev) < threshold))
            repeat = false;
        end

        Fprev = Favg;
        iter = iter + 1;
    end
end

function processedImage = ProcessImage(image, feature, F, blockSize)
    % Creating the spatial transformation structure
    % Reference :
    % http://www.mathworks.com/help/images/ref/imtransform.html
    % http://blogs.mathworks.com/steve/2006/02/14/spatial-transformations-maketform-tformfwd-and-tforminv/
    FM = CreateFeatureMatrix(feature);
    transfMatrix = CalculateAffineTransform(FM, F);

    FEATURE = (FM * transfMatrix);
    plot(FEATURE(1), FEATURE(2), 'ok')
    plot(FEATURE(3), FEATURE(4), 'oy')
    plot(FEATURE(5), FEATURE(6), 'or')
    plot(FEATURE(7), FEATURE(8), 'ob')
    plot(FEATURE(9), FEATURE(10), 'oc')

    A = [transfMatrix(1) transfMatrix(2); transfMatrix(3) transfMatrix(4)];
    b = [transfMatrix(5) transfMatrix(6)];
    Ainv = pinv(A);

    newImage = zeros(blockSize, blockSize);
    for i = 1:size(newImage, 1)
        for j = 1:size(newImage, 2)
            p = Ainv * ([i j] - b)';
            x = floor(p(1));
            y = floor(p(2));

            if x > 0 && x <= size(image, 2) && y > 0 && y <= size(image, 1)
                newImage(j, i) = image(y, x);
            end
        end
    end

    processedImage = newImage;
end

function [x] = CalculateAffineTransform(A, b)
    % Solving the system Ax = b to get the transformation matrix
    x = pinv(A) * b;
end

function A = CreateFeatureMatrix(features)
    % Determine the affine transformation matrix (A)
    A = zeros(10, 6);
    for i = 1:length(features)/2
        pos = 2*i - 1;
        A(pos, :) = [features(pos) features(pos + 1) 0 0 1 0];
        A(pos + 1, :) = [0 0 features(pos) features(pos + 1) 0 1];
    end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Analisis2
{
    public partial class Registro : Form
    {
        public Registro()
        {
            InitializeComponent();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripComboBox1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void administrarClienteToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

    }
}


text:
<databaseChangeLog
     xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
     http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

  <property name="table.tablespace" value=""/>
  <property name="index.tablespace" value=""/>

  <include file="base-schema-changelog.xml"/>
  <include file="migrate-schema-changelog.xml"/>
  <include file="transient-schema-changelog.xml"/>

</databaseChangeLog>


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Namespace Application\Models | Phalcon REST API</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						Application

						Aware

						Helpers

						Models

						Modules

						Rest

						Aware

						Controllers

						DTO

						Events

						BeforeDispatchLoop

						BeforeException

						BeforeExecuteRoute

						Exceptions

						Services

						Validators

						Services

						Advanced

						Cache

						Database

						Develop

						Mail

						Mappers

						Security

						PHP

Classes

Banners

Categories

Currency

Engines

Errors

ItemAttributes

ItemAttributeValues

Items

Logs

Pages

Prices

Subscribers

UserAccess

UserRoles

Users

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

Namespace

Class

				Tree

						Deprecated

						Todo

				Download

Namespace Application\Models

Classes summary

	Banners
	Class Banners banners

	Categories
	Class Categories categories

	Currency
	Class Currency currency

	Engines
	Class Engines engines

	Errors
	Class Errors errors

	ItemAttributes
	Class ItemAttributes item_attributes

	ItemAttributeValues
	Class ItemAttributeValues item_attribute_values

	Items
	Class Items items

	Logs
	Class Logs logs

	Pages
	Class Pages pages

	Prices
	Class Prices prices

	Subscribers
	Class Subscribers subscribers

	UserAccess
	Class UserAccess user_access

	UserRoles
	Class UserRoles user_roles

	Users
	Class Users users

		Phalcon REST API API documentation generated by ApiGen


text:
import sqlalchemy as sa

import ibis
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
from ibis.backends.base.sql.alchemy import (
    AlchemyCompiler,
    AlchemyExprTranslator,
)

from .registry import operation_registry

class SQLiteExprTranslator(AlchemyExprTranslator):
    _registry = operation_registry
    _rewrites = AlchemyExprTranslator._rewrites.copy()
    _type_map = AlchemyExprTranslator._type_map.copy()
    _type_map.update({dt.Double: sa.types.REAL, dt.Float: sa.types.REAL})

rewrites = SQLiteExprTranslator.rewrites

@rewrites(ops.DayOfWeekIndex)
def day_of_week_index(expr):
    return ((expr.op().arg.strftime('%w').cast(dt.int16) + 6) % 7).cast(
        dt.int16
    )

@rewrites(ops.DayOfWeekName)
def day_of_week_name(expr):
    return (
        expr.op()
        .arg.day_of_week.index()
        .case()
        .when(0, 'Monday')
        .when(1, 'Tuesday')
        .when(2, 'Wednesday')
        .when(3, 'Thursday')
        .when(4, 'Friday')
        .when(5, 'Saturday')
        .when(6, 'Sunday')
        .else_(ibis.NA)
        .end()
    )

class SQLiteCompiler(AlchemyCompiler):
    translator_class = SQLiteExprTranslator


text:
angular.module( 'aboutModule', [
  'ui.router',
  'ui.bootstrap'
])

.config(function config( $stateProvider ) {
  $stateProvider.state( 'about', {
    url: '/about',
    views: {
      "main": {
        controller: 'AboutCtrl',
        templateUrl: 'about/about.tpl.html'
      }
    },
    data:{ pageTitle: 'About' }
  });
})

.controller( 'AboutCtrl', function AboutCtrl( $scope ) {
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package us.vicentini.hackerrank.algorithms;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

/**
 * https://www.hackerrank.com/challenges/missing-numbers
 *
 * @author Shulander
 */
public class MissingNumbers {

    public static void main(String[] args) {
        Scanner myScan = new Scanner(System.in);
        int nValues = myScan.nextInt();
        int[] arrayValuesA = new int[nValues];

        for (int i = 0; i < nValues; i++) {
            arrayValuesA[i] = myScan.nextInt();
        }
        nValues = myScan.nextInt();
        int[] arrayValuesB = new int[nValues];

        for (int i = 0; i < nValues; i++) {
            arrayValuesB[i] = myScan.nextInt();
        }
        System.out.println(findMissingValues(arrayValuesA, arrayValuesB));
    }

    private static String findMissingValues(int[] arrayValuesA, int[] arrayValuesB) {
        Map<Integer, Integer> subMap = new TreeMap<>();

        for (int tmp : arrayValuesA) {
            if (subMap.containsKey(tmp)) {
                subMap.put(tmp, subMap.get(tmp) + 1);
            } else {
                subMap.put(tmp, 1);
            }
        }

        for (int tmp : arrayValuesB) {
            if (subMap.containsKey(tmp)) {
                subMap.put(tmp, subMap.get(tmp) - 1);
            } else {
                subMap.put(tmp, -1);
            }
        }

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Integer, Integer> keySet : subMap.entrySet()) {
            if (keySet.getValue() != 0) {
                sb.append(keySet.getKey()).append(" ");
            }
        }
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 1);
        }

        return sb.toString();
    }
}


text:
typedef blargg_long nes_time_t; // clock cycle count
typedef unsigned nes_addr_t; // 16-bit address
enum { future_nes_time = INT_MAX / 2 + 1 };

class Nes_Cpu {
public:
	typedef BOOST::uint8_t uint8_t;

	// Clear registers, map low memory and its three mirrors to address 0,
	// and mirror unmapped_page in remaining memory
	void reset( void const* unmapped_page = 0 );

	// Map code memory (memory accessed via the program counter). Start and size
	// must be multiple of page_size. If mirror is true, repeats code page
	// throughout address range.
	enum { page_size = 0x800 };
	void map_code( nes_addr_t start, unsigned size, void const* code, bool mirror = false );

	// Access emulated memory as CPU does
	uint8_t const* get_code( nes_addr_t );

	// 2KB of RAM at address 0
	uint8_t low_mem [0x800];

	// NES 6502 registers. Not kept updated during a call to run().
	struct registers_t {
		BOOST::uint16_t pc;
		BOOST::uint8_t a;
		BOOST::uint8_t x;
		BOOST::uint8_t y;
		BOOST::uint8_t status;
		BOOST::uint8_t sp;
	};
	registers_t r;

	// Set end_time and run CPU from current time. Returns true if execution
	// stopped due to encountering bad_opcode.
	bool run( nes_time_t end_time );

	// Time of beginning of next instruction to be executed
	nes_time_t time() const             { return state->time + state->base; }
	void set_time( nes_time_t t )       { state->time = t - state->base; }
	void adjust_time( int delta )       { state->time += delta; }

	nes_time_t irq_time() const         { return irq_time_; }
	void set_irq_time( nes_time_t );

	nes_time_t end_time() const         { return end_time_; }
	void set_end_time( nes_time_t );

	// Number of undefined instructions encountered and skipped
	void clear_error_count()            { error_count_ = 0; }
	unsigned long error_count() const   { return error_count_; }

	// CPU invokes bad opcode handler if it encounters this
	enum { bad_opcode = 0xF2 };

public:
	Nes_Cpu() { state = &state_; }
	enum { page_bits = 11 };
	enum { page_count = 0x10000 >> page_bits };
	enum { irq_inhibit = 0x04 };
private:
	struct state_t {
		uint8_t const* code_map [page_count + 1];
		nes_time_t base;
		int time;
	};
	state_t* state; // points to state_ or a local copy within run()
	state_t state_;
	nes_time_t irq_time_;
	nes_time_t end_time_;
	unsigned long error_count_;

	void set_code_page( int, void const* );
	inline int update_end_time( nes_time_t end, nes_time_t irq );
};

inline BOOST::uint8_t const* Nes_Cpu::get_code( nes_addr_t addr )
{
	return state->code_map [addr >> page_bits] + addr
	#if !BLARGG_NONPORTABLE
		% (unsigned) page_size
	#endif
	;
}

inline int Nes_Cpu::update_end_time( nes_time_t t, nes_time_t irq )
{
	if ( irq < t && !(r.status & irq_inhibit) ) t = irq;
	int delta = state->base - t;
	state->base = t;
	return delta;
}

inline void Nes_Cpu::set_irq_time( nes_time_t t )
{
	state->time += update_end_time( end_time_, (irq_time_ = t) );
}

inline void Nes_Cpu::set_end_time( nes_time_t t )
{
	state->time += update_end_time( (end_time_ = t), irq_time_ );
}

#endif


text:
import {Component, OnInit, Input, ViewContainerRef} from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import 'rxjs/add/operator/switchMap';
import {UsuarioService} from '../user/user.service';
import {Usuario} from "../user/Usuario";
import {Location} from '@angular/common';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {Mensagem} from "../Mensagem";
@Component({
    selector: 'usuario-detalhes',
    moduleId: module.id,
    templateUrl: 'usuario-detalhes.component.html',
    providers: [UsuarioService]
})

export class UsuarioDetalhesComponent implements OnInit {
    private formulario: FormGroup;
    private usuario: Usuario;
    private usuarioSelecionado;
    private tiposUsuario;
    private descricaoTipoUsuario;
    private descricaoStatus;
    public events: any[] = [];
    public mensagem:Mensagem;
    public cardMensagem: boolean;

    constructor(private usuarioService: UsuarioService,
                private route: ActivatedRoute,
                private location: Location,
                ) {
        this.usuario = null;
        this.usuarioSelecionado = this.routerParams(this.location.path());
        this.tiposUsuario;
        this.cardMensagem = false;
        this.mensagem = new Mensagem();
    };

    ngOnInit() {
        if (this.usuarioSelecionado != 0) {
            this.route.params
                .switchMap((params: Params) => this.usuarioService.getUsuario(+params['id']))
                .subscribe(usuario => this.usuario = usuario);
        }
        else {
            this.usuario = new Usuario();
        }
        this.formulario = new FormGroup({
            nome: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
            cpf: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
            telefone: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
            usuario: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]),
            senha: new FormControl('', [<any>Validators.minLength(8)]),
            id_tipo_usuario: new FormControl(''),
            status: new FormControl('')
        });
        this.buscarTiposUsuarios();
    }

    goBack(): void {
        this.location.back();
    }

    salvarUsuario(usuario: Usuario, isValid: boolean): void {
        usuario = this.setTipoUsuario(usuario);
        if (isValid) {
            this.usuarioService.salvarUsuario(usuario).then((data) => {
                    this.mensagem = data;
                    this.cardMensagem = true;
            });
        }
    }

    buscarTiposUsuarios() {
        this.usuarioService.buscarTiposUsuario().then((data) => {
            this.tiposUsuario = data;
            this.descricaoTipoUsuario = this.tiposUsuario[this.usuario.id_tipo_usuario];
            if (this.usuario.status) {
                this.descricaoStatus = 'Ativo'
            }
            else {
                this.descricaoStatus = 'Inativo'
            }
        });
    }

    setTipoUsuario(usuario) {
        usuario.id = this.usuario.id;
        usuario.id_usuarioadm = this.usuario.id_usuarioadm;
        usuario.id_fornecedor = this.usuario.id_fornecedor;
        if (usuario.id_tipo_usuario == "") {
            usuario.id_tipo_usuario = this.usuario.id_tipo_usuario;
        } else {
            usuario.id_tipo_usuario = this.tiposUsuario.indexOf(usuario.id_tipo_usuario) + 1;
        }
        if(usuario.status == ""){
            usuario.status = this.usuario.status;
        } else{
            if (usuario.status == "Ativo" ) {
                usuario.status = 1;
            }
            else {
                usuario.status = 0;
            }
        }
        return usuario;
    }

    routerParams(params: string): string {
        var parametros = params.split("/");
        var parametro = parametros[3];
        return parametro;
    }

    blurCardMensagem(){
        this.cardMensagem = false;
    }

}


text:
{% include 'navbar.html' %}

{% block content %}

                Export Info
                Name
                Last Name
                Birth Date
                Phone
                Status
                P
                P
                Primary Hospital

                Export Info
                Name
                Last Name
                Birth Date
                Phone
                Status
                P
                P
                Primary Hospital

            {% for patient in patients %}

                    <button type="button" onClick="location.href = '/exportUser/' + '{{patient.pk}}'" class="btn-block btn-primary" value="Export ">Export</button>

                    {{ patient.first_name }} {{ patient.last_name }}
                    {{ patient.last_name }}
                    {{ patient.birthdate }}
                    {{ patient.phone }}
                    {{ patient.status }}
                    {{ patient.username }}
                    {{ patient.sex }}
                    {{ patient.preferred_hospital }}
                    {{ patient.pk }}
                    {{ patient.primary_physician }}
                    {{ patient.last_physical }}
                    {{ patient.health_history }}

            {% endfor %}

                    <button type="button" class="close" data-dismiss="modal">×</button>

                <form id="patientform" action="/admitpatient/" method="POST">

                                    Username
                                    {{ user.username }}

                                    Birthdate
                                    {{ user.birthdate }}

                                    Sex
                                    {{ user.sex }}

                                    Phone Number
                                    {{ user.phone }}

                                    Primary Physician
                                    {{ form.u_primary_physician }}

                                    Last Physical
                                    {{ form.u_last_physical }}

                                    Primary Hospital
                                    {{ form.u_preferred_hospital }}

                                    Health History
                                    {{ form.u_health_history }}

                        {% csrf_token %}
                        <input type="submit" onclick="setSave()" class="btn-lg btn-primary" value="Save">

                        <input id="admitbtn" type="submit" class="btn-lg btn-primary" value="Admit Patient">
                        <button type="button" class="btn-lg btn-danger" data-dismiss="modal">Close</button>

                </form>

{% endblock %}

{% block javascript %}

{% endblock %}


text:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import *  # NOQA
from future import standard_library
standard_library.install_aliases()  # NOQA

import chainer
from chainer import functions as F

from chainerrl.agents import pal

class DoublePAL(pal.PAL):

    def _compute_y_and_t(self, exp_batch):

        batch_state = exp_batch['state']
        batch_size = len(exp_batch['reward'])

        if self.recurrent:
            qout, _ = self.model.n_step_forward(
                batch_state, exp_batch['recurrent_state'],
                output_mode='concat')
        else:
            qout = self.model(batch_state)

        batch_actions = exp_batch['action']
        batch_q = qout.evaluate_actions(batch_actions)

        # Compute target values

        with chainer.no_backprop_mode():
            batch_next_state = exp_batch['next_state']
            if self.recurrent:
                next_qout, _ = self.model.n_step_forward(
                    batch_next_state, exp_batch['next_recurrent_state'],
                    output_mode='concat')
                target_qout, _ = self.target_model.n_step_forward(
                    batch_state, exp_batch['recurrent_state'],
                    output_mode='concat')
                target_next_qout, _ = self.target_model.n_step_forward(
                    batch_next_state, exp_batch['next_recurrent_state'],
                    output_mode='concat')
            else:
                next_qout = self.model(batch_next_state)
                target_qout = self.target_model(batch_state)
                target_next_qout = self.target_model(batch_next_state)

            next_q_max = F.reshape(target_next_qout.evaluate_actions(
                next_qout.greedy_actions), (batch_size,))

            batch_rewards = exp_batch['reward']
            batch_terminal = exp_batch['is_state_terminal']

            # T Q: Bellman operator
            t_q = batch_rewards + exp_batch['discount'] * \
                (1.0 - batch_terminal) * next_q_max

            # T_PAL Q: persistent advantage learning operator
            cur_advantage = F.reshape(
                target_qout.compute_advantage(batch_actions), (batch_size,))
            next_advantage = F.reshape(
                target_next_qout.compute_advantage(batch_actions),
                (batch_size,))
            tpal_q = t_q + self.alpha * \
                F.maximum(cur_advantage, next_advantage)

        return batch_q, tpal_q


text:
package kafka

import (
	"testing"

	"github.com/funkygao/assert"
)

func TestParseDSN(t *testing.T) {
	dsn := "kafka:prod://trade/orders"
	zone, cluster, topic, partitionID, err := ParseDSN(dsn)
	assert.Equal(t, nil, err)
	assert.Equal(t, "prod", zone)
	assert.Equal(t, "trade", cluster)
	assert.Equal(t, "orders", topic)
	assert.Equal(t, InvalidPartitionID, partitionID)

	dsn = "kafka:prod://trade/orders#"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, nil, err)
	assert.Equal(t, "prod", zone)
	assert.Equal(t, "trade", cluster)
	assert.Equal(t, "orders", topic)
	assert.Equal(t, int32(-1), partitionID)

	dsn = "kafka:prod://trade/orders#1"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, nil, err)
	assert.Equal(t, "prod", zone)
	assert.Equal(t, "trade", cluster)
	assert.Equal(t, "orders", topic)
	assert.Equal(t, int32(1), partitionID)

	dsn = "kafka:prod://trade/orders#0"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, nil, err)
	assert.Equal(t, "prod", zone)
	assert.Equal(t, "trade", cluster)
	assert.Equal(t, "orders", topic)
	assert.Equal(t, int32(0), partitionID)

	dsn = "kafka:prod://trade/orders#invalid"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, InvalidPartitionID, partitionID)
	assert.Equal(t, true, err != nil)

	dsn = "kafka:prod://trade/orders#-9"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, InvalidPartitionID, partitionID)
	assert.Equal(t, true, err != nil)

	// empty zone raises err
	dsn = "kafka:trade/orders"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, false, err == nil)

	// empty cluster raises err
	dsn = "kafka:uat:///orders"
	zone, cluster, topic, partitionID, err = ParseDSN(dsn)
	assert.Equal(t, "uat", zone)
	assert.Equal(t, "", cluster)
	assert.Equal(t, "orders", topic)
	assert.Equal(t, false, err == nil)
	assert.Equal(t, int32(-1), partitionID)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2014 CyberVision, Inc.

  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.
-->
<resources>

     <declare-styleable name="Thermostat">
        <attr name="thumb" format="reference" />
        <attr name="thumbOffset" format="dimension" />
        <attr name="max" format="integer" />
        <attr name="progressWidth" format="dimension" />
        <attr name="arcWidth" format="dimension" />
        <attr name="progress" format="integer" />
        <attr name="rotation" format="integer" />
        <attr name="startAngle" format="integer" />
        <attr name="sweepAngle" format="integer" />
        <attr name="roundEdges" format="boolean" />
        <attr name="touchInside" format="boolean" />
        <attr name="clockwise" format="boolean" />
        <attr name="enableBlur" format="boolean" />
        <attr name="tempMin" format="integer" />
        <attr name="tempMax" format="integer" />
        <attr name="coolingText" format="string" />
        <attr name="heatingText" format="string" />
        <attr name="arcColorCold" format="color" />
        <attr name="progressColorCold" format="color" />
        <attr name="backgroundColorCold" format="color" />
        <attr name="arcColor" format="color" />
        <attr name="progressColor" format="color" />
        <attr name="backgroundColor" format="color" />
        <attr name="arcColorHeat" format="color" />
        <attr name="progressColorHeat" format="color" />
        <attr name="backgroundColorHeat" format="color" />
        <attr name="thumbsColor" format="color" />
        <attr name="thumbsGlowColor" format="color" />
        <attr name="controlsColor" format="color" />
    </declare-styleable>

    <declare-styleable name="ThermostatTheme">
        <attr name="thermostatStyle" format="reference"></attr>
    </declare-styleable>

    <declare-styleable name="TextViewPlus">
        <attr name="customFont" format="string"/>
    </declare-styleable>

</resources>