text:
#include "config/full_system.hh"
#include "config/the_isa.hh"
#include "config/use_checker.hh"
#include "cpu/activity.hh"
#include "cpu/simple_thread.hh"
#include "cpu/thread_context.hh"
#include "cpu/o3lite/isa_specific.hh"
#include "cpu/o3lite/cpu.hh"
#include "cpu/o3lite/thread_context.hh"
#include "enums/MemoryMode.hh"
#include "sim/core.hh"
#include "sim/stat_control.hh"

#if FULL_SYSTEM
#include "cpu/quiesce_event.hh"
#include "sim/system.hh"
#else
#include "sim/process.hh"
#endif

#if USE_CHECKER
#include "cpu/checker/cpu.hh"
#endif

#if THE_ISA == ALPHA_ISA
#include "arch/alpha/osfpal.hh"
#endif

class BaseCPUParams;

using namespace TheISA;
using namespace std;

BaseO3liteCPU::BaseO3liteCPU(BaseCPUParams *params)
    : BaseCPU(params)
{
}

void
BaseO3liteCPU::regStats()
{
    BaseCPU::regStats();
}

template <class Impl>
FullO3liteCPU<Impl>::TickEvent::TickEvent(FullO3liteCPU<Impl> *c)
    : Event(CPU_Tick_Pri), cpu(c)
{
}

template <class Impl>
void
FullO3liteCPU<Impl>::TickEvent::process()
{
    cpu->tick();
}

template <class Impl>
const char *
FullO3liteCPU<Impl>::TickEvent::description() const
{
    return "FullO3liteCPU tick";
}

template <class Impl>
FullO3liteCPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
    : Event(CPU_Switch_Pri)
{
}

template <class Impl>
void
FullO3liteCPU<Impl>::ActivateThreadEvent::init(int thread_num,
                                           FullO3liteCPU<Impl> *thread_cpu)
{
    tid = thread_num;
    cpu = thread_cpu;
}

template <class Impl>
void
FullO3liteCPU<Impl>::ActivateThreadEvent::process()
{
    cpu->activateThread(tid);
}

template <class Impl>
const char *
FullO3liteCPU<Impl>::ActivateThreadEvent::description() const
{
    return "FullO3liteCPU \"Activate Thread\"";
}

template <class Impl>
FullO3liteCPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
    : Event(CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
{
}

template <class Impl>
void
FullO3liteCPU<Impl>::DeallocateContextEvent::init(int thread_num,
                                              FullO3liteCPU<Impl> *thread_cpu)
{
    tid = thread_num;
    cpu = thread_cpu;
    remove = false;
}

template <class Impl>
void
FullO3liteCPU<Impl>::DeallocateContextEvent::process()
{
    cpu->deactivateThread(tid);
    if (remove)
        cpu->removeThread(tid);
}

template <class Impl>
const char *
FullO3liteCPU<Impl>::DeallocateContextEvent::description() const
{
    return "FullO3liteCPU \"Deallocate Context\"";
}

template <class Impl>
FullO3liteCPU<Impl>::FullO3liteCPU(DerivO3liteCPUParams *params)
    : BaseO3liteCPU(params),
      itb(params->itb),
      dtb(params->dtb),
      tickEvent(this),
#ifndef NDEBUG
      instcount(0),
#endif
      removeInstsThisCycle(false),
      fetch(this, params),
      decode(this, params),
      rename(this, params),
      iew(this, params),
      commit(this, params),

      regFile(this, params->numPhysIntRegs,
              params->numPhysFloatRegs),

      freeList(params->numThreads,
               TheISA::NumIntRegs, params->numPhysIntRegs,
               TheISA::NumFloatRegs, params->numPhysFloatRegs),

      rob(this,
          params->numROBEntries, params->squashWidth,
          params->smtROBPolicy, params->smtROBThreshold,
          params->numThreads),

      scoreboard(params->numThreads,
                 TheISA::NumIntRegs, params->numPhysIntRegs,
                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
                 TheISA::NumMiscRegs * numThreads,
                 TheISA::ZeroReg),

      timeBuffer(params->backComSize, params->forwardComSize),
      fetchQueue(params->backComSize, params->forwardComSize),
      decodeQueue(params->backComSize, params->forwardComSize),
      renameQueue(params->backComSize, params->forwardComSize),
      iewQueue(params->backComSize, params->forwardComSize),
      activityRec(name(), NumStages,
                  params->backComSize + params->forwardComSize,
                  params->activity),

      globalSeqNum(1),
#if FULL_SYSTEM
      system(params->system),
#endif // FULL_SYSTEM
      drainCount(0),
      deferRegistration(params->defer_registration)
{
    if (!deferRegistration) {
        _status = Running;
    } else {
        _status = Idle;
    }

#if USE_CHECKER
    if (params->checker) {
        BaseCPU *temp_checker = params->checker;
        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
#if FULL_SYSTEM
        checker->setSystem(params->system);
#endif
    } else {
        checker = NULL;
    }
#endif // USE_CHECKER

#if !FULL_SYSTEM
    thread.resize(numThreads);
    tids.resize(numThreads);
#endif

    // The stages also need their CPU pointer setup.  However this
    // must be done at the upper level CPU because they have pointers
    // to the upper level CPU, and not this FullO3liteCPU.

    // Set up Pointers to the activeThreads list for each stage
    fetch.setActiveThreads(&activeThreads);
    decode.setActiveThreads(&activeThreads);
    rename.setActiveThreads(&activeThreads);
    iew.setActiveThreads(&activeThreads);
    commit.setActiveThreads(&activeThreads);

    // Give each of the stages the time buffer they will use.
    fetch.setTimeBuffer(&timeBuffer);
    decode.setTimeBuffer(&timeBuffer);
    rename.setTimeBuffer(&timeBuffer);
    iew.setTimeBuffer(&timeBuffer);
    commit.setTimeBuffer(&timeBuffer);

    // Also setup each of the stages' queues.
    fetch.setFetchQueue(&fetchQueue);
    decode.setFetchQueue(&fetchQueue);
    commit.setFetchQueue(&fetchQueue);
    decode.setDecodeQueue(&decodeQueue);
    rename.setDecodeQueue(&decodeQueue);
    rename.setRenameQueue(&renameQueue);
    iew.setRenameQueue(&renameQueue);
    iew.setIEWQueue(&iewQueue);
    commit.setIEWQueue(&iewQueue);
    commit.setRenameQueue(&renameQueue);

    commit.setIEWStage(&iew);
    rename.setIEWStage(&iew);
    rename.setCommitStage(&commit);

#if !FULL_SYSTEM
    ThreadID active_threads = params->workload.size();

    if (active_threads > Impl::MaxThreads) {
        panic("Workload Size too large. Increase the 'MaxThreads'"
              "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) or "
              "edit your workload size.");
    }
#else
    ThreadID active_threads = 1;
#endif

    //Make Sure That this a Valid Architeture
    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);

    rename.setScoreboard(&scoreboard);
    iew.setScoreboard(&scoreboard);

    // Setup the rename map for whichever stages need it.
    PhysRegIndex lreg_idx = 0;
    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs

    for (ThreadID tid = 0; tid < numThreads; tid++) {
        bool bindRegs = (tid <= active_threads - 1);

        commitRenameMap[tid].init(TheISA::NumIntRegs,
                                  params->numPhysIntRegs,
                                  lreg_idx,            //Index for Logical. Regs

                                  TheISA::NumFloatRegs,
                                  params->numPhysFloatRegs,
                                  freg_idx,            //Index for Float Regs

                                  TheISA::NumMiscRegs,

                                  TheISA::ZeroReg,
                                  TheISA::ZeroReg,

                                  tid,
                                  false);

        renameMap[tid].init(TheISA::NumIntRegs,
                            params->numPhysIntRegs,
                            lreg_idx,                  //Index for Logical. Regs

                            TheISA::NumFloatRegs,
                            params->numPhysFloatRegs,
                            freg_idx,                  //Index for Float Regs

                            TheISA::NumMiscRegs,

                            TheISA::ZeroReg,
                            TheISA::ZeroReg,

                            tid,
                            bindRegs);

        activateThreadEvent[tid].init(tid, this);
        deallocateContextEvent[tid].init(tid, this);
    }

    rename.setRenameMap(renameMap);
    commit.setRenameMap(commitRenameMap);

    // Give renameMap & rename stage access to the freeList;
    for (ThreadID tid = 0; tid < numThreads; tid++)
        renameMap[tid].setFreeList(&freeList);
    rename.setFreeList(&freeList);

    // Setup the ROB for whichever stages need it.
    commit.setROB(&rob);

    lastRunningCycle = curTick;

    lastActivatedCycle = -1;
#if 0
    // Give renameMap & rename stage access to the freeList;
    for (ThreadID tid = 0; tid < numThreads; tid++)
        globalSeqNum[tid] = 1;
#endif

    contextSwitch = false;
    DPRINTF(O3CPU, "Creating O3CPU object.\n");

    // Setup any thread state.
    this->thread.resize(this->numThreads);

    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
#if FULL_SYSTEM
        // SMT is not supported in FS mode yet.
        assert(this->numThreads == 1);
        this->thread[tid] = new Thread(this, 0);
#else
        if (tid < params->workload.size()) {
            DPRINTF(O3CPU, "Workload[%i] process is %#x",
                    tid, this->thread[tid]);
            this->thread[tid] = new typename FullO3liteCPU<Impl>::Thread(
                    (typename Impl::O3CPU *)(this),
                    tid, params->workload[tid]);

            //usedTids[tid] = true;
            //threadMap[tid] = tid;
        } else {
            //Allocate Empty thread so M5 can use later
            //when scheduling threads to CPU
            Process* dummy_proc = NULL;

            this->thread[tid] = new typename FullO3liteCPU<Impl>::Thread(
                    (typename Impl::O3CPU *)(this),
                    tid, dummy_proc);
            //usedTids[tid] = false;
        }
#endif // !FULL_SYSTEM

        ThreadContext *tc;

        // Setup the TC that will serve as the interface to the threads/CPU.
        O3liteThreadContext<Impl> *o3_tc = new O3liteThreadContext<Impl>;

        tc = o3_tc;

        // If we're using a checker, then the TC should be the
        // CheckerThreadContext.
#if USE_CHECKER
        if (params->checker) {
            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
                o3_tc, this->checker);
        }
#endif

        o3_tc->cpu = (typename Impl::O3CPU *)(this);
        assert(o3_tc->cpu);
        o3_tc->thread = this->thread[tid];

#if FULL_SYSTEM
        // Setup quiesce event.
        this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
#endif
        // Give the thread the TC.
        this->thread[tid]->tc = tc;

        // Add the TC to the CPU's list of TC's.
        this->threadContexts.push_back(tc);
    }

    for (ThreadID tid = 0; tid < this->numThreads; tid++)
        this->thread[tid]->setFuncExeInst(0);

    lockAddr = 0;
    lockFlag = false;
}

template <class Impl>
FullO3liteCPU<Impl>::~FullO3liteCPU()
{
}

template <class Impl>
void
FullO3liteCPU<Impl>::regStats()
{
    BaseO3liteCPU::regStats();

    // Register any of the O3CPU's stats here.
    timesIdled
        .name(name() + ".timesIdled")
        .desc("Number of times that the entire CPU went into an idle state and"
              " unscheduled itself")
        .prereq(timesIdled);

    idleCycles
        .name(name() + ".idleCycles")
        .desc("Total number of cycles that the CPU has spent unscheduled due "
              "to idling")
        .prereq(idleCycles);

    // Number of Instructions simulated
    // --------------------------------
    // Should probably be in Base CPU but need templated
    // MaxThreads so put in here instead
    committedInsts
        .init(numThreads)
        .name(name() + ".committedInsts")
        .desc("Number of Instructions Simulated");

    totalCommittedInsts
        .name(name() + ".committedInsts_total")
        .desc("Number of Instructions Simulated");

    cpi
        .name(name() + ".cpi")
        .desc("CPI: Cycles Per Instruction")
        .precision(6);
    cpi = numCycles / committedInsts;

    totalCpi
        .name(name() + ".cpi_total")
        .desc("CPI: Total CPI of All Threads")
        .precision(6);
    totalCpi = numCycles / totalCommittedInsts;

    ipc
        .name(name() + ".ipc")
        .desc("IPC: Instructions Per Cycle")
        .precision(6);
    ipc =  committedInsts / numCycles;

    totalIpc
        .name(name() + ".ipc_total")
        .desc("IPC: Total IPC of All Threads")
        .precision(6);
    totalIpc =  totalCommittedInsts / numCycles;

    this->fetch.regStats();
    this->decode.regStats();
    this->rename.regStats();
    this->iew.regStats();
    this->commit.regStats();
}

template <class Impl>
Port *
FullO3liteCPU<Impl>::getPort(const std::string &if_name, int idx)
{
    if (if_name == "dcache_port")
        return iew.getDcachePort();
    else if (if_name == "icache_port")
        return fetch.getIcachePort();
    else
        panic("No Such Port\n");
}

template <class Impl>
void
FullO3liteCPU<Impl>::tick()
{
    DPRINTF(O3CPU, "\n\nFullO3liteCPU: Ticking main, FullO3liteCPU.\n");

    ++numCycles;

//    activity = false;

    //Tick each of the stages
    fetch.tick();

    decode.tick();

    rename.tick();

    iew.tick();

    commit.tick();

#if !FULL_SYSTEM
    doContextSwitch();
#endif

    // Now advance the time buffers
    timeBuffer.advance();

    fetchQueue.advance();
    decodeQueue.advance();
    renameQueue.advance();
    iewQueue.advance();

    activityRec.advance();

    if (removeInstsThisCycle) {
        cleanUpRemovedInsts();
    }

    if (!tickEvent.scheduled()) {
        if (_status == SwitchedOut ||
            getState() == SimObject::Drained) {
            DPRINTF(O3CPU, "Switched out!\n");
            // increment stat
            lastRunningCycle = curTick;
        } else if (!activityRec.active() || _status == Idle) {
            DPRINTF(O3CPU, "Idle!\n");
            lastRunningCycle = curTick;
            timesIdled++;
        } else {
            schedule(tickEvent, nextCycle(curTick + ticks(1)));
            DPRINTF(O3CPU, "Scheduling next tick!\n");
        }
    }

#if !FULL_SYSTEM
    updateThreadPriority();
#endif
}

template <class Impl>
void
FullO3liteCPU<Impl>::init()
{
    BaseCPU::init();

    // Set inSyscall so that the CPU doesn't squash when initially
    // setting up registers.
    for (ThreadID tid = 0; tid < numThreads; ++tid)
        thread[tid]->inSyscall = true;

#if FULL_SYSTEM
    for (ThreadID tid = 0; tid < numThreads; tid++) {
        ThreadContext *src_tc = threadContexts[tid];
        TheISA::initCPU(src_tc, src_tc->contextId());
    }
#endif

    // Clear inSyscall.
    for (int tid = 0; tid < numThreads; ++tid)
        thread[tid]->inSyscall = false;

    // Initialize stages.
    fetch.initStage();
    iew.initStage();
    rename.initStage();
    commit.initStage();

    commit.setThreads(thread);
}

template <class Impl>
void
FullO3liteCPU<Impl>::activateThread(ThreadID tid)
{
    list<ThreadID>::iterator isActive =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);

    if (isActive == activeThreads.end()) {
        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
                tid);

        activeThreads.push_back(tid);
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::deactivateThread(ThreadID tid)
{
    //Remove From Active List, if Active
    list<ThreadID>::iterator thread_it =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);

    if (thread_it != activeThreads.end()) {
        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
                tid);
        activeThreads.erase(thread_it);
    }
}

template <class Impl>
Counter
FullO3liteCPU<Impl>::totalInstructions() const
{
    Counter total(0);

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++)
        total += thread[i]->numInst;

    return total;
}

template <class Impl>
void
FullO3liteCPU<Impl>::activateContext(ThreadID tid, int delay)
{
    // Needs to set each stage to running as well.
    if (delay){
        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
                "on cycle %d\n", tid, curTick + ticks(delay));
        scheduleActivateThreadEvent(tid, delay);
    } else {
        activateThread(tid);
    }

    if (lastActivatedCycle < curTick) {
        scheduleTickEvent(delay);

        // Be sure to signal that there's some activity so the CPU doesn't
        // deschedule itself.
        activityRec.activity();
        fetch.wakeFromQuiesce();

        lastActivatedCycle = curTick;

        _status = Running;
    }
}

template <class Impl>
bool
FullO3liteCPU<Impl>::deallocateContext(ThreadID tid, bool remove, int delay)
{
    // Schedule removal of thread data from CPU
    if (delay){
        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
                "on cycle %d\n", tid, curTick + ticks(delay));
        scheduleDeallocateContextEvent(tid, remove, delay);
        return false;
    } else {
        deactivateThread(tid);
        if (remove)
            removeThread(tid);
        return true;
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::suspendContext(ThreadID tid)
{
    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
    bool deallocated = deallocateContext(tid, false, 1);
    // If this was the last thread then unschedule the tick event.
    if ((activeThreads.size() == 1 && !deallocated) ||
        activeThreads.size() == 0)
        unscheduleTickEvent();
    _status = Idle;
}

template <class Impl>
void
FullO3liteCPU<Impl>::haltContext(ThreadID tid)
{
    //For now, this is the same as deallocate
    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
    deallocateContext(tid, true, 1);
}

template <class Impl>
void
FullO3liteCPU<Impl>::insertThread(ThreadID tid)
{
    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
    // Will change now that the PC and thread state is internal to the CPU
    // and not in the ThreadContext.
#if FULL_SYSTEM
    ThreadContext *src_tc = system->threadContexts[tid];
#else
    ThreadContext *src_tc = tcBase(tid);
#endif

    //Bind Int Regs to Rename Map
    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
        PhysRegIndex phys_reg = freeList.getIntReg();

        renameMap[tid].setEntry(ireg,phys_reg);
        scoreboard.setReg(phys_reg);
    }

    //Bind Float Regs to Rename Map
    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
        PhysRegIndex phys_reg = freeList.getFloatReg();

        renameMap[tid].setEntry(freg,phys_reg);
        scoreboard.setReg(phys_reg);
    }

    //Copy Thread Data Into RegFile
    //this->copyFromTC(tid);

    //Set PC/NPC/NNPC
    setPC(src_tc->readPC(), tid);
    setNextPC(src_tc->readNextPC(), tid);
    setNextNPC(src_tc->readNextNPC(), tid);

    src_tc->setStatus(ThreadContext::Active);

    activateContext(tid,1);

    //Reset ROB/IQ/LSQ Entries
    commit.rob->resetEntries();
    iew.resetEntries();
}

template <class Impl>
void
FullO3liteCPU<Impl>::removeThread(ThreadID tid)
{
    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);

    // Copy Thread Data From RegFile
    // If thread is suspended, it might be re-allocated
    // this->copyToTC(tid);

    // @todo: 2-27-2008: Fix how we free up rename mappings
    // here to alleviate the case for double-freeing registers
    // in SMT workloads.

    // Unbind Int Regs from Rename Map
    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);

        scoreboard.unsetReg(phys_reg);
        freeList.addReg(phys_reg);
    }

    // Unbind Float Regs from Rename Map
    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);

        scoreboard.unsetReg(phys_reg);
        freeList.addReg(phys_reg);
    }

    // Squash Throughout Pipeline
    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
    fetch.squash(0, sizeof(TheISA::MachInst), 0, squash_seq_num, tid);
    decode.squash(tid);
    rename.squash(squash_seq_num, tid);
    iew.squash(tid);
    iew.ldstQueue.squash(squash_seq_num, tid);
    commit.rob->squash(squash_seq_num, tid);

    assert(iew.instQueue.getCount(tid) == 0);
    assert(iew.ldstQueue.getCount(tid) == 0);

    // Reset ROB/IQ/LSQ Entries

    // Commented out for now.  This should be possible to do by
    // telling all the pipeline stages to drain first, and then
    // checking until the drain completes.  Once the pipeline is
    // drained, call resetEntries(). - 10-09-06 ktlim
/*
    if (activeThreads.size() >= 1) {
        commit.rob->resetEntries();
        iew.resetEntries();
    }
*/
}

template <class Impl>
void
FullO3liteCPU<Impl>::activateWhenReady(ThreadID tid)
{
    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
            tid);

    bool ready = true;

    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
                "Phys. Int. Regs.\n",
                tid);
        ready = false;
    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
                "Phys. Float. Regs.\n",
                tid);
        ready = false;
    } else if (commit.rob->numFreeEntries() >=
               commit.rob->entryAmount(activeThreads.size() + 1)) {
        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
                "ROB entries.\n",
                tid);
        ready = false;
    } else if (iew.instQueue.numFreeEntries() >=
               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
                "IQ entries.\n",
                tid);
        ready = false;
    } else if (iew.ldstQueue.numFreeEntries() >=
               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
                "LSQ entries.\n",
                tid);
        ready = false;
    }

    if (ready) {
        insertThread(tid);

        contextSwitch = false;

        cpuWaitList.remove(tid);
    } else {
        suspendContext(tid);

        //blocks fetch
        contextSwitch = true;

        //@todo: dont always add to waitlist
        //do waitlist
        cpuWaitList.push_back(tid);
    }
}

#if FULL_SYSTEM
template <class Impl>
Fault
FullO3liteCPU<Impl>::hwrei(ThreadID tid)
{
#if THE_ISA == ALPHA_ISA
    // Need to clear the lock flag upon returning from an interrupt.
    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);

    this->thread[tid]->kernelStats->hwrei();

    // FIXME: XXX check for interrupts? XXX
#endif
    return NoFault;
}

template <class Impl>
bool
FullO3liteCPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
{
#if THE_ISA == ALPHA_ISA
    if (this->thread[tid]->kernelStats)
        this->thread[tid]->kernelStats->callpal(palFunc,
                                                this->threadContexts[tid]);

    switch (palFunc) {
      case PAL::halt:
        halt();
        if (--System::numSystemsRunning == 0)
            exitSimLoop("all cpus halted");
        break;

      case PAL::bpt:
      case PAL::bugchk:
        if (this->system->breakpoint())
            return false;
        break;
    }
#endif
    return true;
}

template <class Impl>
Fault
FullO3liteCPU<Impl>::getInterrupts()
{
    // Check if there are any outstanding interrupts
    return this->interrupts->getInterrupt(this->threadContexts[0]);
}

template <class Impl>
void
FullO3liteCPU<Impl>::processInterrupts(Fault interrupt)
{
    // Check for interrupts here.  For now can copy the code that
    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
    // is the one that handles the interrupts.
    // @todo: Possibly consolidate the interrupt checking code.
    // @todo: Allow other threads to handle interrupts.

    assert(interrupt != NoFault);
    this->interrupts->updateIntrInfo(this->threadContexts[0]);

    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
    this->trap(interrupt, 0);
}

template <class Impl>
void
FullO3liteCPU<Impl>::updateMemPorts()
{
    // Update all ThreadContext's memory ports (Functional/Virtual
    // Ports)
    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; ++i)
        thread[i]->connectMemPorts(thread[i]->getTC());
}
#endif

template <class Impl>
void
FullO3liteCPU<Impl>::trap(Fault fault, ThreadID tid)
{
    // Pass the thread's TC into the invoke method.
    fault->invoke(this->threadContexts[tid]);
}

#if !FULL_SYSTEM

template <class Impl>
void
FullO3liteCPU<Impl>::syscall(int64_t callnum, ThreadID tid)
{
    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);

    DPRINTF(Activity,"Activity: syscall() called.\n");

    // Temporarily increase this by one to account for the syscall
    // instruction.
    ++(this->thread[tid]->funcExeInst);

    // Execute the actual syscall.
    this->thread[tid]->syscall(callnum);

    // Decrease funcExeInst by one as the normal commit will handle
    // incrementing it.
    --(this->thread[tid]->funcExeInst);
}

#endif

template <class Impl>
void
FullO3liteCPU<Impl>::serialize(std::ostream &os)
{
    SimObject::State so_state = SimObject::getState();
    SERIALIZE_ENUM(so_state);
    BaseCPU::serialize(os);
    nameOut(os, csprintf("%s.tickEvent", name()));
    tickEvent.serialize(os);

    // Use SimpleThread's ability to checkpoint to make it easier to
    // write out the registers.  Also make this static so it doesn't
    // get instantiated multiple times (causes a panic in statistics).
    static SimpleThread temp;

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++) {
        nameOut(os, csprintf("%s.xc.%i", name(), i));
        temp.copyTC(thread[i]->getTC());
        temp.serialize(os);
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
{
    SimObject::State so_state;
    UNSERIALIZE_ENUM(so_state);
    BaseCPU::unserialize(cp, section);
    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));

    // Use SimpleThread's ability to checkpoint to make it easier to
    // read in the registers.  Also make this static so it doesn't
    // get instantiated multiple times (causes a panic in statistics).
    static SimpleThread temp;

    ThreadID size = thread.size();
    for (ThreadID i = 0; i < size; i++) {
        temp.copyTC(thread[i]->getTC());
        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
        thread[i]->getTC()->copyArchRegs(temp.getTC());
    }
}

template <class Impl>
unsigned int
FullO3liteCPU<Impl>::drain(Event *drain_event)
{
    DPRINTF(O3CPU, "Switching out\n");

    // If the CPU isn't doing anything, then return immediately.
    if (_status == Idle || _status == SwitchedOut) {
        return 0;
    }

    drainCount = 0;
    fetch.drain();
    decode.drain();
    rename.drain();
    iew.drain();
    commit.drain();

    // Wake the CPU and record activity so everything can drain out if
    // the CPU was not able to immediately drain.
    if (getState() != SimObject::Drained) {
        // A bit of a hack...set the drainEvent after all the drain()
        // calls have been made, that way if all of the stages drain
        // immediately, the signalDrained() function knows not to call
        // process on the drain event.
        drainEvent = drain_event;

        wakeCPU();
        activityRec.activity();

        return 1;
    } else {
        return 0;
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::resume()
{
    fetch.resume();
    decode.resume();
    rename.resume();
    iew.resume();
    commit.resume();

    changeState(SimObject::Running);

    if (_status == SwitchedOut || _status == Idle)
        return;

#if FULL_SYSTEM
    assert(system->getMemoryMode() == Enums::timing);
#endif

    if (!tickEvent.scheduled())
        schedule(tickEvent, nextCycle());
    _status = Running;
}

template <class Impl>
void
FullO3liteCPU<Impl>::signalDrained()
{
    if (++drainCount == NumStages) {
        if (tickEvent.scheduled())
            tickEvent.squash();

        changeState(SimObject::Drained);

        BaseCPU::switchOut();

        if (drainEvent) {
            drainEvent->process();
            drainEvent = NULL;
        }
    }
    assert(drainCount <= 5);
}

template <class Impl>
void
FullO3liteCPU<Impl>::switchOut()
{
    fetch.switchOut();
    rename.switchOut();
    iew.switchOut();
    commit.switchOut();
    instList.clear();
    while (!removeList.empty()) {
        removeList.pop();
    }

    _status = SwitchedOut;
#if USE_CHECKER
    if (checker)
        checker->switchOut();
#endif
    if (tickEvent.scheduled())
        tickEvent.squash();
}

template <class Impl>
void
FullO3liteCPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
{
    // Flush out any old data from the time buffers.
    for (int i = 0; i < timeBuffer.getSize(); ++i) {
        timeBuffer.advance();
        fetchQueue.advance();
        decodeQueue.advance();
        renameQueue.advance();
        iewQueue.advance();
    }

    activityRec.reset();

    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());

    fetch.takeOverFrom();
    decode.takeOverFrom();
    rename.takeOverFrom();
    iew.takeOverFrom();
    commit.takeOverFrom();

    assert(!tickEvent.scheduled());

    // @todo: Figure out how to properly select the tid to put onto
    // the active threads list.
    ThreadID tid = 0;

    list<ThreadID>::iterator isActive =
        std::find(activeThreads.begin(), activeThreads.end(), tid);

    if (isActive == activeThreads.end()) {
        //May Need to Re-code this if the delay variable is the delay
        //needed for thread to activate
        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
                tid);

        activeThreads.push_back(tid);
    }

    // Set all statuses to active, schedule the CPU's tick event.
    // @todo: Fix up statuses so this is handled properly
    ThreadID size = threadContexts.size();
    for (ThreadID i = 0; i < size; ++i) {
        ThreadContext *tc = threadContexts[i];
        if (tc->status() == ThreadContext::Active && _status != Running) {
            _status = Running;
            schedule(tickEvent, nextCycle());
        }
    }
    if (!tickEvent.scheduled())
        schedule(tickEvent, nextCycle());
}

template <class Impl>
TheISA::MiscReg
FullO3liteCPU<Impl>::readMiscRegNoEffect(int misc_reg, ThreadID tid)
{
    return this->isa[tid].readMiscRegNoEffect(misc_reg);
}

template <class Impl>
TheISA::MiscReg
FullO3liteCPU<Impl>::readMiscReg(int misc_reg, ThreadID tid)
{
    return this->isa[tid].readMiscReg(misc_reg, tcBase(tid));
}

template <class Impl>
void
FullO3liteCPU<Impl>::setMiscRegNoEffect(int misc_reg,
        const TheISA::MiscReg &val, ThreadID tid)
{
    this->isa[tid].setMiscRegNoEffect(misc_reg, val);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setMiscReg(int misc_reg,
        const TheISA::MiscReg &val, ThreadID tid)
{
    this->isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readIntReg(int reg_idx)
{
    return regFile.readIntReg(reg_idx);
}

template <class Impl>
FloatReg
FullO3liteCPU<Impl>::readFloatReg(int reg_idx)
{
    return regFile.readFloatReg(reg_idx);
}

template <class Impl>
FloatRegBits
FullO3liteCPU<Impl>::readFloatRegBits(int reg_idx)
{
    return regFile.readFloatRegBits(reg_idx);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setIntReg(int reg_idx, uint64_t val)
{
    regFile.setIntReg(reg_idx, val);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
{
    regFile.setFloatReg(reg_idx, val);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
{
    regFile.setFloatRegBits(reg_idx, val);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readArchIntReg(int reg_idx, ThreadID tid)
{
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);

    return regFile.readIntReg(phys_reg);
}

template <class Impl>
float
FullO3liteCPU<Impl>::readArchFloatReg(int reg_idx, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);

    return regFile.readFloatReg(phys_reg);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readArchFloatRegInt(int reg_idx, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);

    return regFile.readFloatRegBits(phys_reg);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, ThreadID tid)
{
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);

    regFile.setIntReg(phys_reg, val);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setArchFloatReg(int reg_idx, float val, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);

    regFile.setFloatReg(phys_reg, val);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid)
{
    int idx = reg_idx + TheISA::NumIntRegs;
    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);

    regFile.setFloatRegBits(phys_reg, val);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readPC(ThreadID tid)
{
    return commit.readPC(tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setPC(Addr new_PC, ThreadID tid)
{
    commit.setPC(new_PC, tid);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readMicroPC(ThreadID tid)
{
    return commit.readMicroPC(tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setMicroPC(Addr new_PC, ThreadID tid)
{
    commit.setMicroPC(new_PC, tid);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readNextPC(ThreadID tid)
{
    return commit.readNextPC(tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setNextPC(uint64_t val, ThreadID tid)
{
    commit.setNextPC(val, tid);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readNextNPC(ThreadID tid)
{
    return commit.readNextNPC(tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setNextNPC(uint64_t val, ThreadID tid)
{
    commit.setNextNPC(val, tid);
}

template <class Impl>
uint64_t
FullO3liteCPU<Impl>::readNextMicroPC(ThreadID tid)
{
    return commit.readNextMicroPC(tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::setNextMicroPC(Addr new_PC, ThreadID tid)
{
    commit.setNextMicroPC(new_PC, tid);
}

template <class Impl>
void
FullO3liteCPU<Impl>::squashFromTC(ThreadID tid)
{
    this->thread[tid]->inSyscall = true;
    this->commit.generateTCEvent(tid);
}

template <class Impl>
typename FullO3liteCPU<Impl>::ListIt
FullO3liteCPU<Impl>::addInst(DynInstPtr &inst)
{
    instList.push_back(inst);

    return --(instList.end());
}

template <class Impl>
void
FullO3liteCPU<Impl>::instDone(ThreadID tid)
{
    // Keep an instruction count.
    thread[tid]->numInst++;
    thread[tid]->numInsts++;
    committedInsts[tid]++;
    totalCommittedInsts++;

    // Check for instruction-count-based events.
    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
}

template <class Impl>
void
FullO3liteCPU<Impl>::addToRemoveList(DynInstPtr &inst)
{
    removeInstsThisCycle = true;

    removeList.push(inst->getInstListIt());
}

template <class Impl>
void
FullO3liteCPU<Impl>::removeFrontInst(DynInstPtr &inst)
{
    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
            "[sn:%lli]\n",
            inst->threadNumber, inst->readPC(), inst->seqNum);

    removeInstsThisCycle = true;

    // Remove the front instruction.
    removeList.push(inst->getInstListIt());
}

template <class Impl>
void
FullO3liteCPU<Impl>::removeInstsNotInROB(ThreadID tid)
{
    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
            " list.\n", tid);

    ListIt end_it;

    bool rob_empty = false;

    if (instList.empty()) {
        return;
    } else if (rob.isEmpty(/*tid*/)) {
        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
        end_it = instList.begin();
        rob_empty = true;
    } else {
        end_it = (rob.readTailInst(tid))->getInstListIt();
        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
    }

    removeInstsThisCycle = true;

    ListIt inst_it = instList.end();

    inst_it--;

    // Walk through the instruction list, removing any instructions
    // that were inserted after the given instruction iterator, end_it.
    while (inst_it != end_it) {
        assert(!instList.empty());

        squashInstIt(inst_it, tid);

        inst_it--;
    }

    // If the ROB was empty, then we actually need to remove the first
    // instruction as well.
    if (rob_empty) {
        squashInstIt(inst_it, tid);
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
{
    assert(!instList.empty());

    removeInstsThisCycle = true;

    ListIt inst_iter = instList.end();

    inst_iter--;

    DPRINTF(O3CPU, "Deleting instructions from instruction "
            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
            tid, seq_num, (*inst_iter)->seqNum);

    while ((*inst_iter)->seqNum > seq_num) {

        bool break_loop = (inst_iter == instList.begin());

        squashInstIt(inst_iter, tid);

        inst_iter--;

        if (break_loop)
            break;
    }
}

template <class Impl>
inline void
FullO3liteCPU<Impl>::squashInstIt(const ListIt &instIt, ThreadID tid)
{
    if ((*instIt)->threadNumber == tid) {
        DPRINTF(O3CPU, "Squashing instruction, "
                "[tid:%i] [sn:%lli] PC %#x\n",
                (*instIt)->threadNumber,
                (*instIt)->seqNum,
                (*instIt)->readPC());

        // Mark it as squashed.
        (*instIt)->setSquashed();

        // @todo: Formulate a consistent method for deleting
        // instructions from the instruction list
        // Remove the instruction from the list.
        removeList.push(instIt);
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::cleanUpRemovedInsts()
{
    while (!removeList.empty()) {
        DPRINTF(O3CPU, "Removing instruction, "
                "[tid:%i] [sn:%lli] PC %#x\n",
                (*removeList.front())->threadNumber,
                (*removeList.front())->seqNum,
                (*removeList.front())->readPC());

        instList.erase(removeList.front());

        removeList.pop();
    }

    removeInstsThisCycle = false;
}
/*
template <class Impl>
void
FullO3liteCPU<Impl>::removeAllInsts()
{
    instList.clear();
}
*/
template <class Impl>
void
FullO3liteCPU<Impl>::dumpInsts()
{
    int num = 0;

    ListIt inst_list_it = instList.begin();

    cprintf("Dumping Instruction List\n");

    while (inst_list_it != instList.end()) {
        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
                "Squashed:%i\n\n",
                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
                (*inst_list_it)->isSquashed());
        inst_list_it++;
        ++num;
    }
}
/*
template <class Impl>
void
FullO3liteCPU<Impl>::wakeDependents(DynInstPtr &inst)
{
    iew.wakeDependents(inst);
}
*/
template <class Impl>
void
FullO3liteCPU<Impl>::wakeCPU()
{
    if (activityRec.active() || tickEvent.scheduled()) {
        DPRINTF(Activity, "CPU already running.\n");
        return;
    }

    DPRINTF(Activity, "Waking up CPU\n");

    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);

    schedule(tickEvent, nextCycle());
}

#if FULL_SYSTEM
template <class Impl>
void
FullO3liteCPU<Impl>::wakeup()
{
    if (this->thread[0]->status() != ThreadContext::Suspended)
        return;

    this->wakeCPU();

    DPRINTF(Quiesce, "Suspended Processor woken\n");
    this->threadContexts[0]->activate();
}
#endif

template <class Impl>
ThreadID
FullO3liteCPU<Impl>::getFreeTid()
{
    for (ThreadID tid = 0; tid < numThreads; tid++) {
        if (!tids[tid]) {
            tids[tid] = true;
            return tid;
        }
    }

    return InvalidThreadID;
}

template <class Impl>
void
FullO3liteCPU<Impl>::doContextSwitch()
{
    if (contextSwitch) {

        //ADD CODE TO DEACTIVE THREAD HERE (???)

        ThreadID size = cpuWaitList.size();
        for (ThreadID tid = 0; tid < size; tid++) {
            activateWhenReady(tid);
        }

        if (cpuWaitList.size() == 0)
            contextSwitch = true;
    }
}

template <class Impl>
void
FullO3liteCPU<Impl>::updateThreadPriority()
{
    if (activeThreads.size() > 1) {
        //DEFAULT TO ROUND ROBIN SCHEME
        //e.g. Move highest priority to end of thread list
        list<ThreadID>::iterator list_begin = activeThreads.begin();
        list<ThreadID>::iterator list_end   = activeThreads.end();

        unsigned high_thread = *list_begin;

        activeThreads.erase(list_begin);

        activeThreads.push_back(high_thread);
    }
}

// Forward declaration of FullO3liteCPU.
template class FullO3liteCPU<O3liteCPUImpl>;


text:
'use strict';

var grunt = require('grunt');

// Parse options printed by fixtures/Gruntfile-cli into an object.
var optionValueRe = /###(.*?)###/;
function getOptionValues(str) {
  var matches = str.match(optionValueRe);
  return matches ? JSON.parse(matches[1]) : {};
}

exports['cli'] = {
  '--debug taskname': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', '--debug', 'debug', 'finalize'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {debug: 1}, 'Options should parse correctly.');
      test.done();
    });
  },
  'taskname --debug': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', 'debug', '--debug', 'finalize'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {debug: 1}, 'Options should parse correctly.');
      test.done();
    });
  },
  '--debug --verbose': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', '--debug', '--verbose', 'debug', 'verbose', 'finalize'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {debug: 1, verbose: true}, 'Options should parse correctly.');
      test.done();
    });
  },
  '--verbose --debug': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', '--verbose', '--debug', 'debug', 'verbose', 'finalize'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {debug: 1, verbose: true}, 'Options should parse correctly.');
      test.done();
    });
  },
  '--once --no-watch': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', 'print-option:once', 'print-option:no-watch', 'finalize', '--once', '--no-watch'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {once: true, 'no-watch': true}, 'Options should parse correctly.');
      test.done();
    });
  },
  '--once --no-watch flags': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', 'print-option:watch', 'print-option:no-watch', 'finalize', '--once', '--no-watch'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {'no-watch': true, watch: false}, 'Options should parse correctly.');
      test.done();
    });
  },
  '--ver=1.10': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', 'test/fixtures/Gruntfile-cli-fix.js', 'print-option:ver', 'finalize', '--ver=1.10'],
    }, function(err, result) {
      test.deepEqual(getOptionValues(result.stdout), {ver: '1.10'}, 'Option should parse as number.');
      test.done();
    });
  },
};

redpajama_set_name: RedPajamaGithub


text:
angular.module('dataGoMain')
        .controller('UserController', UserController);

    function UserController($http, $auth, $rootScope, $state) {

    }


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>
javax.crypto.spec Class Hierarchy (GNU cryptographic primitives and tools)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes

Hierarchy For Package javax.crypto.spec

Package Hierarchies:
All Packages

Class Hierarchy

class java.lang.Object

class javax.crypto.spec.DESedeKeySpec (implements java.security.spec.KeySpec)

class javax.crypto.spec.DESKeySpec (implements java.security.spec.KeySpec)

class javax.crypto.spec.DHGenParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.DHParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.DHPrivateKeySpec (implements java.security.spec.KeySpec)

class javax.crypto.spec.DHPublicKeySpec (implements java.security.spec.KeySpec)

class javax.crypto.spec.IvParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.PBEKeySpec (implements java.security.spec.KeySpec)

class javax.crypto.spec.PBEParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.RC2ParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.RC5ParameterSpec (implements java.security.spec.AlgorithmParameterSpec)

class javax.crypto.spec.SecretKeySpec (implements java.security.spec.KeySpec, javax.crypto.SecretKey)

      Overview
      Package
      Class
    Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV
 NEXT

  FRAMES
 NO FRAMES

All Classes

Copyright © 2001, 2002, 2003, 2004 Free Software Foundation, Inc.


text:
""" Module with various calculators """
from dynamic_dynamodb.log_handler import LOGGER as logger
from dynamic_dynamodb.config_handler import get_table_option

def get_min_provisioned_reads(current_provisioning, key_name):
    """ Returns the minimum provisioned reads

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type key_name: str
    :param key_name: Name of the key
    :returns: int -- Minimum provisioned reads
    """
    if get_table_option(key_name, 'min_provisioned_reads'):
        return int(min(
            get_table_option(key_name, 'min_provisioned_reads'),
            (current_provisioning * 2)))

    return int(current_provisioning * 2)

def get_min_provisioned_writes(current_provisioning, key_name):
    """ Returns the minimum provisioned writes

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :returns: int -- Minimum provisioned writes
    :type key_name: str
    :param key_name: Name of the key
    """
    if get_table_option(key_name, 'min_provisioned_writes'):
        return int(min(
            get_table_option(key_name, 'min_provisioned_writes'),
            (current_provisioning * 2)))

    return int(current_provisioning * 2)

def decrease_reads_in_percent(current_provisioning, percent, key_name):
    """ Decrease the current_provisioning with percent %

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type percent: int
    :param percent: How many percent should we decrease with
    :type key_name: str
    :param key_name: Name of the key
    :returns: int -- New provisioning value
    """
    decrease = int(float(current_provisioning)*(float(percent)/100))
    updated_provisioning = current_provisioning - decrease
    logger.debug(
        'Read provisioning will be decreased to {0:d} units'.format(
            updated_provisioning))

    min_provisioned_reads = get_min_provisioned_reads(
        current_provisioning,
        key_name)

    if min_provisioned_reads > 0:
        if updated_provisioning < min_provisioned_reads:
            logger.info('Reached provisioned reads min limit: {0:d}'.format(
                min_provisioned_reads))

            return min_provisioned_reads

    return updated_provisioning

def increase_reads_in_percent(current_provisioning, percent, key_name):
    """ Increase the current_provisioning with percent %

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type percent: int
    :param percent: How many percent should we increase with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    increase = int(float(current_provisioning)*(float(percent)/100))
    updated_provisioning = current_provisioning + increase
    logger.debug(
        'Read provisioning will be increased to {0:d} units'.format(
            updated_provisioning))

    if get_table_option(key_name, 'max_provisioned_reads') > 0:
        if (updated_provisioning >
                get_table_option(key_name, 'max_provisioned_reads')):

            logger.info('Reached provisioned reads max limit: {0:d}'.format(
                int(get_table_option(key_name, 'max_provisioned_reads'))))

            return get_table_option(key_name, 'max_provisioned_reads')

    return updated_provisioning

def decrease_writes_in_percent(current_provisioning, percent, key_name):
    """ Decrease the current_provisioning with percent %

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type percent: int
    :param percent: How many percent should we decrease with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    decrease = int(float(current_provisioning)*(float(percent)/100))
    updated_provisioning = current_provisioning - decrease
    logger.debug(
        'Write provisioning will be decreased to {0:d} units'.format(
            updated_provisioning))

    min_provisioned_writes = get_min_provisioned_writes(
        current_provisioning,
        key_name)

    if min_provisioned_writes > 0:
        if updated_provisioning < min_provisioned_writes:
            logger.info('Reached provisioned writes min limit: {0:d}'.format(
                min_provisioned_writes))

            return min_provisioned_writes

    return updated_provisioning

def increase_writes_in_percent(current_provisioning, percent, key_name):
    """ Increase the current_provisioning with percent %

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type percent: int
    :param percent: How many percent should we increase with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    increase = int(float(current_provisioning)*(float(percent)/100))
    updated_provisioning = current_provisioning + increase
    logger.debug(
        'Write provisioning will be increased to {0:d} units'.format(
            updated_provisioning))

    if get_table_option(key_name, 'max_provisioned_writes') > 0:
        if (updated_provisioning >
                get_table_option(key_name, 'max_provisioned_writes')):

            logger.info('Reached provisioned writes max limit: {0:d}'.format(
                int(get_table_option(key_name, 'max_provisioned_writes'))))

            return get_table_option(key_name, 'max_provisioned_writes')

    return updated_provisioning

def decrease_reads_in_units(current_provisioning, units, key_name):
    """ Decrease the current_provisioning with units units

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type units: int
    :param units: How many units should we decrease with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    updated_provisioning = int(current_provisioning) - int(units)
    logger.debug(
        'Read provisioning will be decreased to {0:d} units'.format(
            updated_provisioning))

    min_provisioned_reads = get_min_provisioned_reads(
        current_provisioning,
        key_name)

    if min_provisioned_reads > 0:
        if updated_provisioning < min_provisioned_reads:
            logger.info('Reached provisioned reads min limit: {0:d}'.format(
                min_provisioned_reads))

            return min_provisioned_reads

    return updated_provisioning

def increase_reads_in_units(current_provisioning, units, key_name):
    """ Increase the current_provisioning with units units

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type units: int
    :param units: How many units should we increase with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    updated_provisioning = 0
    if int(units) > int(current_provisioning):
        updated_provisioning = 2 * int(current_provisioning)
    else:
        updated_provisioning = int(current_provisioning) + int(units)

    logger.debug(
        'Read provisioning will be increased to {0:d} units'.format(
            updated_provisioning))

    if get_table_option(key_name, 'max_provisioned_reads') > 0:
        if (updated_provisioning >
                get_table_option(key_name, 'max_provisioned_reads')):

            logger.info('Reached provisioned reads max limit: {0:d}'.format(
                int(get_table_option(key_name, 'max_provisioned_reads'))))

            return get_table_option(key_name, 'max_provisioned_reads')

    return updated_provisioning

def decrease_writes_in_units(current_provisioning, units, key_name):
    """ Decrease the current_provisioning with units units

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type units: int
    :param units: How many units should we decrease with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    updated_provisioning = int(current_provisioning) - int(units)
    logger.debug(
        'Write provisioning will be decreased to {0:d} units'.format(
            updated_provisioning))

    min_provisioned_writes = get_min_provisioned_writes(
        current_provisioning,
        key_name)

    if min_provisioned_writes > 0:
        if updated_provisioning < min_provisioned_writes:
            logger.info('Reached provisioned writes min limit: {0:d}'.format(
                min_provisioned_writes))

            return min_provisioned_writes

    return updated_provisioning

def increase_writes_in_units(current_provisioning, units, key_name):
    """ Increase the current_provisioning with units units

    :type current_provisioning: int
    :param current_provisioning: The current provisioning
    :type units: int
    :param units: How many units should we increase with
    :returns: int -- New provisioning value
    :type key_name: str
    :param key_name: Name of the key
    """
    updated_provisioning = 0
    if int(units) > int(current_provisioning):
        updated_provisioning = 2 * int(current_provisioning)
    else:
        updated_provisioning = int(current_provisioning) + int(units)

    logger.debug(
        'Write provisioning will be increased to {0:d} units'.format(
            updated_provisioning))

    if get_table_option(key_name, 'max_provisioned_writes') > 0:
        if (updated_provisioning >
                get_table_option(key_name, 'max_provisioned_writes')):

            logger.info('Reached provisioned writes max limit: {0:d}'.format(
                int(get_table_option(key_name, 'max_provisioned_writes'))))

            return get_table_option(key_name, 'max_provisioned_writes')

    return updated_provisioning


text:
/*	$OpenBSD: fdopen.c,v 1.5 2005/08/08 08:05:36 espie Exp $ */
/*-
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Chris Torek.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include "local.h"

FILE *
fdopen(int fd, const char *mode)
{
	FILE *fp;
	int flags, oflags, fdflags, tmp;

	if ((flags = __sflags(mode, &oflags)) == 0)
		return (NULL);

	/* Make sure the mode the user wants is a subset of the actual mode. */
	if ((fdflags = fcntl(fd, F_GETFL, 0)) < 0)
		return (NULL);
	tmp = fdflags & O_ACCMODE;
	if (tmp != O_RDWR && (tmp != (oflags & O_ACCMODE))) {
		errno = EINVAL;
		return (NULL);
	}

	if ((fp = __sfp()) == NULL)
		return (NULL);
	fp->_flags = flags;
	/*
	 * If opened for appending, but underlying descriptor does not have
	 * O_APPEND bit set, assert __SAPP so that __swrite() will lseek to
	 * end before each write.
	 */
	if ((oflags & O_APPEND) && !(fdflags & O_APPEND))
		fp->_flags |= __SAPP;
	fp->_file = fd;
	fp->_cookie = fp;
	fp->_read = __sread;
	fp->_write = __swrite;
	fp->_seek = __sseek;
	fp->_close = __sclose;
	return (fp);
}


text:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded" actionBarHidden="true">
  <StackLayout>
    <Label text="Main Menu" class="title"/>
    <Button text="START" tap="onStartBtnTapped" id="startBtn" />
    <Button text="LEADERBOARD" tap="onLeaderboardBtnTapped" id="leaderboardBtn"/>
    <Button text="YOUR SCORES" tap="onLocalScoresBtnTapped" id="localScoresBtn"/>
    <Button text="ABOUT" tap="onAboutBtnTapped" id="aboutBtn" />
  </StackLayout>
</Page>


text:
layout: page
title: Code Guide and Tips
subtitle: Tips in MXNet codebase for reviewers and contributors.
action: Contribute
action_url: /community/index
permalink: /community/code_guide
---
<!--- Licensed to the Apache Software Foundation (ASF) under one -->
<!--- or more contributor license agreements.  See the NOTICE file -->
<!--- distributed with this work for additional information -->
<!--- regarding copyright ownership.  The ASF licenses this file -->
<!--- to you 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. -->

Code Guide and Tips
===================

This is a document used to record tips in MXNet codebase for reviewers and
contributors. Most of them are summarized through lessons during the
contributing and process.

C++ Code Styles
---------------

-   Use the [clang-format]({% link pages/community/clang_format_guide.md %}) to reformat your code.
-   The public facing functions are documented in [doxygen](https://www.doxygen.nl/manual/docblocks.html) format.
-   Favor concrete type declaration over `auto` as long as it is short.
-   Favor passing by const reference (e.g. `const Expr&`) over passing
    by value. Except when the function consumes the value by copy
    constructor or move, pass by value is better than pass by const
    reference in such cases.
-   Favor `const` member function when possible.
-   Use [RAII](https://en.cppreference.com/w/cpp/language/raii) to manage resources, including smart pointers like shared_ptr and unique_ptr as well as allocating in constructors and deallocating in destructors. Avoid explicit calls to new and delete when possible. Use make_shared and make_unique instead.

We use [`cpplint`](https://github.com/cpplint/cpplint) to enforce the code style. Because
different version of `cpplint` might change by its version, it is
recommended to use the same version of the `cpplint` as the master.
You can also use the following command via docker.

```bash
ci/build.py -R --docker-registry mxnetci --platform ubuntu_cpu --docker-build-retries 3 --shm-size 500m /work/runtime_functions.sh sanity_cpp
```

`cpplint` is also not perfect, when necessary, you can use disable
`cpplint` on certain code regions.

Python Code Styles
------------------

-   The functions and classes are documented in
    [numpydoc](https://numpydoc.readthedocs.io/en/latest/) format.
-   Check your code style using `make pylint`
-   Stick to language features as in `python 3.6` and above.

Testing
-------

Our tests are maintained in the [/tests](https://github.com/apache/incubator-mxnet/tree/master/tests) folder. We use the following testing tools:
-   For Python, we use [pytest](https://pytest.org).
    -   An example of setting up and running tests (tested on MacOS with Python 3.6):
        -   follow the [build from source](https://mxnet.apache.org/get_started/build_from_source) guide to build MXNet
        -   install python libraries
            ```
            python3 -m pip install opencv-python
            python3 -m pip install -r ci/docker/install/requirements
            ```
        -   install MXNet Python bindings:
            ```
            python3 -m pip install -e ./python
            ```
        -   run tests in a specific module
            ```
            python3 -m pytest tests/python/unittest/test_smoke.py
            ```
        -   or run a specific test in a module
            ```
            python3 -m pytest tests/python/unittest/test_smoke.py::test_18927
            ```
        -   or run all the Python unittests
            ```
            python3 -m pytest tests/python/unittest/
            ```
-   For C++, we use [gtest](https://github.com/google/googletest).

Our CI pipelines check for a wide variety of configuration on all platforms. To locate and reproduce
a test issue in PR, you can refer to the process described in [#18723](https://github.com/apache/incubator-mxnet/issues/18723)

<script async defer src="https://buttons.github.io/buttons.js"></script>
<script src="https://apis.google.com/js/platform.js"></script>


text:
package com.eouw0o83hf.eouw0o83hface;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

import junit.framework.TestCase;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static com.eouw0o83hf.eouw0o83hface.DeterministicStateManager.VisualState.*;

public class DeterministicStateManagerTests extends TestCase {

    private class Context {
        public List<TestBackgroundShape> BackgroundShapes = Arrays.asList(
                new TestBackgroundShape(),
                new TestBackgroundShape()
        );

        public CheaterDeterministicStateManager Sut = new CheaterDeterministicStateManager(BackgroundShapes);
    }

    private class CheaterDeterministicStateManager extends DeterministicStateManager {
        public CheaterDeterministicStateManager(Collection<TestBackgroundShape> background) {
            super(new TestBackgroundManager(background));
        }

        public void ChangeState(VisualState state) {
            super.ChangeModeTo(state);
        }
    }

    private class TestBackgroundShape implements BackgroundShape {

        @Override
        public void Render(Canvas canvas, Paint sharedPaint) { }

        public boolean IsActive = true;

        @Override
        public boolean GetActive() {
            return IsActive;
        }
    }

    private class TestBackgroundManager implements BackgroundShapeManager {

        private final Collection<TestBackgroundShape> _background;

        public TestBackgroundManager(Collection<TestBackgroundShape> background) {
            _background = background;
        }

        @Override
        public Collection<? extends BackgroundShape> getBackgroundShapes() {
            return _background;
        }

        @Override
        public void initialize(Rect bounds) { }

        @Override
        public void randomize() { }

        @Override
        public boolean turnOnOrOff() { return false; }

        @Override
        public void incrementState(StateChangeStatus changeStatus) { }
    }

    public void test_state_defaultsToInteractive() {
        Context context = new Context();
        assertEquals(Interactive, context.Sut.GetState());
    }

    public void test_ambientModeChanged_fromAmbient_movesToLeavingInteractive() {
        Context context = new Context();
        context.Sut.AmbientModeChanged(true);
        assertEquals(LeavingInteractive, context.Sut.GetState());
    }

    public void test_ambientModeChanged_fromActive_movesToEnteringInteractive() {
        Context context = new Context();
        context.Sut.AmbientModeChanged(false);
        assertEquals(EnteringInteractive, context.Sut.GetState());
    }

    public void test_refreshStateFromBackground_fromInteractive_doesNotChange() {
        Context context = new Context();
        context.Sut.RefreshStateFromBackground();
        assertEquals(Interactive, context.Sut.GetState());
    }

    public void test_refreshStateFromBackground_fromAmbient_doesNotChange() {
        Context context = new Context();
        context.Sut.ChangeState(Ambient);
        context.Sut.RefreshStateFromBackground();
        assertEquals(Ambient, context.Sut.GetState());
    }

    public void test_refreshStateFromBackground_fromIntermediateState_givenNonMatchingShapes_doesntChange() {
        Context context = new Context();
        context.BackgroundShapes.get(0).IsActive = false;
        context.Sut.ChangeState(EnteringInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(EnteringInteractive, context.Sut.GetState());

        context.Sut.ChangeState(LeavingInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(LeavingInteractive, context.Sut.GetState());
    }

    public void test_refreshStateFromBackground_fromIntermediateState_givenActiveShapes_becomesInteractive() {
        Context context = new Context();
        context.Sut.ChangeState(EnteringInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(Interactive, context.Sut.GetState());

        context.Sut.ChangeState(LeavingInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(Interactive, context.Sut.GetState());
    }

    public void test_refreshStateFromBackground_fromIntermediateState_givenInactiveShapes_becomesAmbient() {
        Context context = new Context();
        for (TestBackgroundShape backgroundShape : context.BackgroundShapes) {
            backgroundShape.IsActive = false;
        }
        context.Sut.ChangeState(LeavingInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(Ambient, context.Sut.GetState());

        context.Sut.ChangeState(EnteringInteractive);
        context.Sut.RefreshStateFromBackground();
        assertEquals(Ambient, context.Sut.GetState());
    }
}


text:
package de.itsvs.cwtrpc.controller.config;

import org.junit.Ignore;

/**
 * @author Volker Schmidt
 * @since 0.9
 */
@Ignore
public class TestService20Impl implements TestService20 {
	public String service20(String value) {
		return "20" + value;
	}
}


text:
import "test-setup";
import { consts } from "../core.consts";

import { LoggerService } from "./logger.service";
import { LogType } from "./logger.model";

beforeEach(JasminePromiseMatchers.install);
afterEach(JasminePromiseMatchers.uninstall);

describe("LoggerServiceSpecs", () => {

	let SUT: LoggerService;
	let $log: ng.ILogService;

	beforeEach(angular.mock.module(consts.moduleName));

	beforeEach(inject((
		_loggerService_: LoggerService,
		_$log_: ng.ILogService
	) => {

		SUT = _loggerService_;
		$log = _$log_;

	}));

	describe("given a simple task", () => {

		it("should fail", () => {
			expect(1 + 1).toBe(3);
		});

		it("should be sucessful", () => {
			expect(1 + 1).toBe(2);
		});
	});

	describe("given logType warn", () => {

		it("should invoke warn method", () => {
			spyOn($log, "warn");

			SUT.log(LogType.Warning, "yo querro");

			expect($log.warn).toHaveBeenCalled();
		});
	});

	describe("given logType error", () => {

		it("should invoke error method", () => {
			spyOn($log, "error");

			SUT.log(LogType.Error, "yo querro");

			expect($log.error).toHaveBeenCalled();
		});
	});

});


text:
package com.dianping.cat.report.page.database;

import java.util.List;

import com.dianping.cat.Cat;
import com.dianping.cat.consumer.metric.model.entity.MetricItem;
import com.dianping.cat.consumer.metric.model.entity.MetricReport;
import com.dianping.cat.consumer.metric.model.entity.Segment;
import com.dianping.cat.consumer.metric.model.transform.BaseVisitor;

public class DatabaseReportFilter extends BaseVisitor {

	private MetricReport m_report;

	private List<String> m_keys;

	public DatabaseReportFilter(List<String> keys) {
		m_keys = keys;
	}

	public MetricReport getReport() {
		return m_report;
	}

	public void mergeMetricItem(MetricItem to, MetricItem from) {
		for (Segment temp : from.getSegments().values()) {
			Segment target = to.findOrCreateSegment(temp.getId());

			mergeSegment(target, temp);
		}
	}

	protected void mergeSegment(Segment to, Segment from) {
		to.setCount(from.getCount());
		to.setSum(from.getSum());
		to.setAvg(from.getAvg());
	}

	public void setReport(MetricReport report) {
		m_report = report;
	}

	private boolean validate(String id) {
		try {
			if (m_keys != null && !m_keys.isEmpty()) {
				int index = id.indexOf(":", id.indexOf(":") + 1);
				String realKey = id.substring(index + 1);

				return m_keys.contains(realKey);
			} else {
				return true;
			}
		} catch (Exception e) {
			Cat.logError(e);
			return true;
		}
	}

	@Override
	public void visitMetricItem(MetricItem metricItem) {
		String id = metricItem.getId();

		if (validate(id)) {
			MetricItem item = m_report.findOrCreateMetricItem(id);

			item.setType(metricItem.getType());
			mergeMetricItem(item, metricItem);
		}
	}

	@Override
	public void visitMetricReport(MetricReport metricReport) {
		m_report = new MetricReport(metricReport.getProduct());

		m_report.setStartTime(metricReport.getStartTime());
		m_report.setEndTime(metricReport.getEndTime());
		super.visitMetricReport(metricReport);
	}

}


text:
using System;
using Orchard.ContentManagement.Records;

namespace Orchard.Indexing.Models {
    public class IndexingTaskRecord {

        public const int Update = 0;
        public const int Delete = 1;

        public virtual int Id { get; set; }
        public virtual int Action { get; set; }
        public virtual DateTime? CreatedUtc { get; set; }
        public virtual ContentItemRecord ContentItemRecord { get; set; }
    }
}


text:
require 'spec_helper'

describe Ci::Status do
  describe '.get_status' do
    subject { described_class.get_status(statuses) }

    shared_examples 'build status summary' do
      context 'all successful' do
        let(:statuses) { Array.new(2) { create(type, status: :success) } }
        it { is_expected.to eq 'success' }
      end

      context 'at least one failed' do
        let(:statuses) do
          [create(type, status: :success), create(type, status: :failed)]
        end

        it { is_expected.to eq 'failed' }
      end

      context 'at least one running' do
        let(:statuses) do
          [create(type, status: :success), create(type, status: :running)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'at least one pending' do
        let(:statuses) do
          [create(type, status: :success), create(type, status: :pending)]
        end

        it { is_expected.to eq 'running' }
      end

      context 'success and failed but allowed to fail' do
        let(:statuses) do
          [create(type, status: :success),
           create(type, status: :failed, allow_failure: true)]
        end

        it { is_expected.to eq 'success' }
      end

      context 'one failed but allowed to fail' do
        let(:statuses) { [create(type, status: :failed, allow_failure: true)] }
        it { is_expected.to eq 'success' }
      end

      context 'success and canceled' do
        let(:statuses) do
          [create(type, status: :success), create(type, status: :canceled)]
        end
        it { is_expected.to eq 'failed' }
      end

      context 'all canceled' do
        let(:statuses) do
          [create(type, status: :canceled), create(type, status: :canceled)]
        end
        it { is_expected.to eq 'canceled' }
      end

      context 'success and canceled but allowed to fail' do
        let(:statuses) do
          [create(type, status: :success),
           create(type, status: :canceled, allow_failure: true)]
        end

        it { is_expected.to eq 'success' }
      end

      context 'one finished and second running but allowed to fail' do
        let(:statuses) do
          [create(type, status: :success),
           create(type, status: :running, allow_failure: true)]
        end

        it { is_expected.to eq 'running' }
      end
    end

    context 'ci build statuses' do
      let(:type) { :ci_build }
      it_behaves_like 'build status summary'
    end

    context 'generic commit statuses' do
      let(:type) { :generic_commit_status }
      it_behaves_like 'build status summary'
    end
  end
end


text:
from db_Dao import init_db

init_db()


text:
package org.finra.herd.model.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * A global attribute definition entity.
 */
@Table(name = GlobalAttributeDefinitionEntity.TABLE_NAME)
@Entity
public class GlobalAttributeDefinitionEntity extends AuditableEntity
{
    /**
     * The table name.
     */
    public static final String TABLE_NAME = "glbl_atrbt_dfntn";

    @Id
    @Column(name = TABLE_NAME + "_id")
    @GeneratedValue(generator = TABLE_NAME + "_seq")
    @SequenceGenerator(name = TABLE_NAME + "_seq", sequenceName = TABLE_NAME + "_seq", allocationSize = 1)
    private Long id;

    /**
     * The global attribute definition level.
     */
    @ManyToOne
    @JoinColumn(name = "glbl_atrbt_dfntn_level_cd", referencedColumnName = "glbl_atrbt_dfntn_level_cd", nullable = false)
    private GlobalAttributeDefinitionLevelEntity globalAttributeDefinitionLevel;

    /**
     * The attribute value list.
     */
    @ManyToOne
    @JoinColumn(name = "atrbt_value_list_id", referencedColumnName = "atrbt_value_list_id", nullable = true)
    private AttributeValueListEntity attributeValueList;

    /**
     * The  global attribute definition name.
     */
    @Column(name = TABLE_NAME + "_name_tx", nullable = false)
    private String globalAttributeDefinitionName;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public GlobalAttributeDefinitionLevelEntity getGlobalAttributeDefinitionLevel()
    {
        return globalAttributeDefinitionLevel;
    }

    public void setGlobalAttributeDefinitionLevel(GlobalAttributeDefinitionLevelEntity globalAttributeDefinitionLevel)
    {
        this.globalAttributeDefinitionLevel = globalAttributeDefinitionLevel;
    }

    public String getGlobalAttributeDefinitionName()
    {
        return globalAttributeDefinitionName;
    }

    public void setGlobalAttributeDefinitionName(String globalAttributeDefinitionName)
    {
        this.globalAttributeDefinitionName = globalAttributeDefinitionName;
    }

    public AttributeValueListEntity getAttributeValueList()
    {
        return attributeValueList;
    }

    public void setAttributeValueList(AttributeValueListEntity attributeValueList)
    {
        this.attributeValueList = attributeValueList;
    }
}


text:
import * as React from 'react';
import { spy } from 'sinon';
import { expect } from 'chai';
import { getClasses, createMount, fireEvent, screen, describeConformance } from 'test/utils';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import MonthPicker from '@material-ui/lab/MonthPicker';
import { adapterToUse, createPickerRender } from '../internal/pickers/test-utils';

describe('<MonthPicker />', () => {
  const mount = createMount();
  const render = createPickerRender();
  let classes: Record<string, string>;

  const localizedMount = (node: React.ReactNode) => {
    return mount(<LocalizationProvider dateAdapter={AdapterDateFns}>{node}</LocalizationProvider>);
  };

  before(() => {
    classes = getClasses(
      <MonthPicker
        minDate={adapterToUse.date('2019-01-01T00:00:00.000')}
        maxDate={adapterToUse.date('2029-01-01T00:00:00.000')}
        date={adapterToUse.date()}
        onChange={() => {}}
      />,
    );
  });

  describeConformance(
    <MonthPicker
      minDate={adapterToUse.date('2019-01-01T00:00:00.000')}
      maxDate={adapterToUse.date('2029-01-01T00:00:00.000')}
      date={adapterToUse.date()}
      onChange={() => {}}
    />,
    () => ({
      classes,
      inheritComponent: 'div',
      render,
      mount: localizedMount,
      refInstanceof: window.HTMLDivElement,
      // cannot test reactTestRenderer because of required context
      skip: ['componentProp', 'propsSpread', 'reactTestRenderer'],
    }),
  );

  it('allows to pick year standalone', () => {
    const onChangeMock = spy();
    render(
      <MonthPicker
        minDate={adapterToUse.date('2019-01-01T00:00:00.000')}
        maxDate={adapterToUse.date('2029-01-01T00:00:00.000')}
        date={adapterToUse.date('2019-02-02T00:00:00.000')}
        onChange={onChangeMock}
      />,
    );

    fireEvent.click(screen.getByText('May', { selector: 'button' }));
    expect((onChangeMock.args[0][0] as Date).getMonth()).to.equal(4); // month index starting from 0
  });

  it('does not allow to pick months out of range', () => {
    const onChangeMock = spy();
    render(
      <MonthPicker
        minDate={adapterToUse.date('2020-04-01T00:00:00.000')}
        maxDate={adapterToUse.date('2020-06-01T00:00:00.000')}
        date={adapterToUse.date('2020-04-02T00:00:00.000')}
        onChange={onChangeMock}
      />,
    );

    fireEvent.click(screen.getByText('Mar', { selector: 'button' }));
    expect(onChangeMock.callCount).to.equal(0);

    fireEvent.click(screen.getByText('Apr', { selector: 'button' }));
    expect(onChangeMock.callCount).to.equal(1);
    expect((onChangeMock.args[0][0] as Date).getMonth()).to.equal(3); // month index starting from 0

    fireEvent.click(screen.getByText('Jul', { selector: 'button' }));
    expect(onChangeMock.callCount).to.equal(1);
  });
});