text:
using namespace llvm;

#define DEBUG_TYPE "si-load-store-opt"

namespace {

class SILoadStoreOptimizer : public MachineFunctionPass {
  enum InstClassEnum {
    DS_READ_WRITE,
    S_BUFFER_LOAD_IMM,
    BUFFER_LOAD_OFFEN,
    BUFFER_LOAD_OFFSET,
    BUFFER_STORE_OFFEN,
    BUFFER_STORE_OFFSET,
  };

  struct CombineInfo {
    MachineBasicBlock::iterator I;
    MachineBasicBlock::iterator Paired;
    unsigned EltSize;
    unsigned Offset0;
    unsigned Offset1;
    unsigned BaseOff;
    InstClassEnum InstClass;
    bool GLC0;
    bool GLC1;
    bool SLC0;
    bool SLC1;
    bool UseST64;
    bool IsX2;
    SmallVector<MachineInstr*, 8> InstsToMove;
   };

private:
  const GCNSubtarget *STM = nullptr;
  const SIInstrInfo *TII = nullptr;
  const SIRegisterInfo *TRI = nullptr;
  MachineRegisterInfo *MRI = nullptr;
  AliasAnalysis *AA = nullptr;
  unsigned CreatedX2;

  static bool offsetsCanBeCombined(CombineInfo &CI);

  bool findMatchingInst(CombineInfo &CI);

  unsigned read2Opcode(unsigned EltSize) const;
  unsigned read2ST64Opcode(unsigned EltSize) const;
  MachineBasicBlock::iterator mergeRead2Pair(CombineInfo &CI);

  unsigned write2Opcode(unsigned EltSize) const;
  unsigned write2ST64Opcode(unsigned EltSize) const;
  MachineBasicBlock::iterator mergeWrite2Pair(CombineInfo &CI);
  MachineBasicBlock::iterator mergeSBufferLoadImmPair(CombineInfo &CI);
  MachineBasicBlock::iterator mergeBufferLoadPair(CombineInfo &CI);
  unsigned promoteBufferStoreOpcode(const MachineInstr &I, bool &IsX2,
                                    bool &IsOffen) const;
  MachineBasicBlock::iterator mergeBufferStorePair(CombineInfo &CI);

public:
  static char ID;

  SILoadStoreOptimizer() : MachineFunctionPass(ID) {
    initializeSILoadStoreOptimizerPass(*PassRegistry::getPassRegistry());
  }

  bool optimizeBlock(MachineBasicBlock &MBB);

  bool runOnMachineFunction(MachineFunction &MF) override;

  StringRef getPassName() const override { return "SI Load Store Optimizer"; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesCFG();
    AU.addRequired<AAResultsWrapperPass>();

    MachineFunctionPass::getAnalysisUsage(AU);
  }
};

} // end anonymous namespace.

INITIALIZE_PASS_BEGIN(SILoadStoreOptimizer, DEBUG_TYPE,
                      "SI Load Store Optimizer", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(SILoadStoreOptimizer, DEBUG_TYPE,
                    "SI Load Store Optimizer", false, false)

char SILoadStoreOptimizer::ID = 0;

char &llvm::SILoadStoreOptimizerID = SILoadStoreOptimizer::ID;

FunctionPass *llvm::createSILoadStoreOptimizerPass() {
  return new SILoadStoreOptimizer();
}

static void moveInstsAfter(MachineBasicBlock::iterator I,
                           ArrayRef<MachineInstr*> InstsToMove) {
  MachineBasicBlock *MBB = I->getParent();
  ++I;
  for (MachineInstr *MI : InstsToMove) {
    MI->removeFromParent();
    MBB->insert(I, MI);
  }
}

static void addDefsUsesToList(const MachineInstr &MI,
                              DenseSet<unsigned> &RegDefs,
                              DenseSet<unsigned> &PhysRegUses) {
  for (const MachineOperand &Op : MI.operands()) {
    if (Op.isReg()) {
      if (Op.isDef())
        RegDefs.insert(Op.getReg());
      else if (Op.readsReg() &&
               TargetRegisterInfo::isPhysicalRegister(Op.getReg()))
        PhysRegUses.insert(Op.getReg());
    }
  }
}

static bool memAccessesCanBeReordered(MachineBasicBlock::iterator A,
                                      MachineBasicBlock::iterator B,
                                      const SIInstrInfo *TII,
                                      AliasAnalysis * AA) {
  // RAW or WAR - cannot reorder
  // WAW - cannot reorder
  // RAR - safe to reorder
  return !(A->mayStore() || B->mayStore()) ||
    TII->areMemAccessesTriviallyDisjoint(*A, *B, AA);
}

// Add MI and its defs to the lists if MI reads one of the defs that are
// already in the list. Returns true in that case.
static bool
addToListsIfDependent(MachineInstr &MI,
                      DenseSet<unsigned> &RegDefs,
                      DenseSet<unsigned> &PhysRegUses,
                      SmallVectorImpl<MachineInstr*> &Insts) {
  for (MachineOperand &Use : MI.operands()) {
    // If one of the defs is read, then there is a use of Def between I and the
    // instruction that I will potentially be merged with. We will need to move
    // this instruction after the merged instructions.
    //
    // Similarly, if there is a def which is read by an instruction that is to
    // be moved for merging, then we need to move the def-instruction as well.
    // This can only happen for physical registers such as M0; virtual
    // registers are in SSA form.
    if (Use.isReg() &&
        ((Use.readsReg() && RegDefs.count(Use.getReg())) ||
         (Use.isDef() && TargetRegisterInfo::isPhysicalRegister(Use.getReg()) &&
          PhysRegUses.count(Use.getReg())))) {
      Insts.push_back(&MI);
      addDefsUsesToList(MI, RegDefs, PhysRegUses);
      return true;
    }
  }

  return false;
}

static bool
canMoveInstsAcrossMemOp(MachineInstr &MemOp,
                        ArrayRef<MachineInstr*> InstsToMove,
                        const SIInstrInfo *TII,
                        AliasAnalysis *AA) {
  assert(MemOp.mayLoadOrStore());

  for (MachineInstr *InstToMove : InstsToMove) {
    if (!InstToMove->mayLoadOrStore())
      continue;
    if (!memAccessesCanBeReordered(MemOp, *InstToMove, TII, AA))
        return false;
  }
  return true;
}

bool SILoadStoreOptimizer::offsetsCanBeCombined(CombineInfo &CI) {
  // XXX - Would the same offset be OK? Is there any reason this would happen or
  // be useful?
  if (CI.Offset0 == CI.Offset1)
    return false;

  // This won't be valid if the offset isn't aligned.
  if ((CI.Offset0 % CI.EltSize != 0) || (CI.Offset1 % CI.EltSize != 0))
    return false;

  unsigned EltOffset0 = CI.Offset0 / CI.EltSize;
  unsigned EltOffset1 = CI.Offset1 / CI.EltSize;
  CI.UseST64 = false;
  CI.BaseOff = 0;

  // Handle SMEM and VMEM instructions.
  if (CI.InstClass != DS_READ_WRITE) {
    unsigned Diff = CI.IsX2 ? 2 : 1;
    return (EltOffset0 + Diff == EltOffset1 ||
            EltOffset1 + Diff == EltOffset0) &&
           CI.GLC0 == CI.GLC1 &&
           (CI.InstClass == S_BUFFER_LOAD_IMM || CI.SLC0 == CI.SLC1);
  }

  // If the offset in elements doesn't fit in 8-bits, we might be able to use
  // the stride 64 versions.
  if ((EltOffset0 % 64 == 0) && (EltOffset1 % 64) == 0 &&
      isUInt<8>(EltOffset0 / 64) && isUInt<8>(EltOffset1 / 64)) {
    CI.Offset0 = EltOffset0 / 64;
    CI.Offset1 = EltOffset1 / 64;
    CI.UseST64 = true;
    return true;
  }

  // Check if the new offsets fit in the reduced 8-bit range.
  if (isUInt<8>(EltOffset0) && isUInt<8>(EltOffset1)) {
    CI.Offset0 = EltOffset0;
    CI.Offset1 = EltOffset1;
    return true;
  }

  // Try to shift base address to decrease offsets.
  unsigned OffsetDiff = std::abs((int)EltOffset1 - (int)EltOffset0);
  CI.BaseOff = std::min(CI.Offset0, CI.Offset1);

  if ((OffsetDiff % 64 == 0) && isUInt<8>(OffsetDiff / 64)) {
    CI.Offset0 = (EltOffset0 - CI.BaseOff / CI.EltSize) / 64;
    CI.Offset1 = (EltOffset1 - CI.BaseOff / CI.EltSize) / 64;
    CI.UseST64 = true;
    return true;
  }

  if (isUInt<8>(OffsetDiff)) {
    CI.Offset0 = EltOffset0 - CI.BaseOff / CI.EltSize;
    CI.Offset1 = EltOffset1 - CI.BaseOff / CI.EltSize;
    return true;
  }

  return false;
}

bool SILoadStoreOptimizer::findMatchingInst(CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();
  MachineBasicBlock::iterator E = MBB->end();
  MachineBasicBlock::iterator MBBI = CI.I;

  unsigned AddrOpName[3] = {0};
  int AddrIdx[3];
  const MachineOperand *AddrReg[3];
  unsigned NumAddresses = 0;

  switch (CI.InstClass) {
  case DS_READ_WRITE:
    AddrOpName[NumAddresses++] = AMDGPU::OpName::addr;
    break;
  case S_BUFFER_LOAD_IMM:
    AddrOpName[NumAddresses++] = AMDGPU::OpName::sbase;
    break;
  case BUFFER_LOAD_OFFEN:
  case BUFFER_STORE_OFFEN:
    AddrOpName[NumAddresses++] = AMDGPU::OpName::srsrc;
    AddrOpName[NumAddresses++] = AMDGPU::OpName::vaddr;
    AddrOpName[NumAddresses++] = AMDGPU::OpName::soffset;
    break;
  case BUFFER_LOAD_OFFSET:
  case BUFFER_STORE_OFFSET:
    AddrOpName[NumAddresses++] = AMDGPU::OpName::srsrc;
    AddrOpName[NumAddresses++] = AMDGPU::OpName::soffset;
    break;
  }

  for (unsigned i = 0; i < NumAddresses; i++) {
    AddrIdx[i] = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(), AddrOpName[i]);
    AddrReg[i] = &CI.I->getOperand(AddrIdx[i]);

    // We only ever merge operations with the same base address register, so don't
    // bother scanning forward if there are no other uses.
    if (AddrReg[i]->isReg() &&
        (TargetRegisterInfo::isPhysicalRegister(AddrReg[i]->getReg()) ||
         MRI->hasOneNonDBGUse(AddrReg[i]->getReg())))
      return false;
  }

  ++MBBI;

  DenseSet<unsigned> RegDefsToMove;
  DenseSet<unsigned> PhysRegUsesToMove;
  addDefsUsesToList(*CI.I, RegDefsToMove, PhysRegUsesToMove);

  for ( ; MBBI != E; ++MBBI) {
    if (MBBI->getOpcode() != CI.I->getOpcode()) {
      // This is not a matching DS instruction, but we can keep looking as
      // long as one of these conditions are met:
      // 1. It is safe to move I down past MBBI.
      // 2. It is safe to move MBBI down past the instruction that I will
      //    be merged into.

      if (MBBI->hasUnmodeledSideEffects()) {
        // We can't re-order this instruction with respect to other memory
        // operations, so we fail both conditions mentioned above.
        return false;
      }

      if (MBBI->mayLoadOrStore() &&
        (!memAccessesCanBeReordered(*CI.I, *MBBI, TII, AA) ||
         !canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, TII, AA))) {
        // We fail condition #1, but we may still be able to satisfy condition
        // #2.  Add this instruction to the move list and then we will check
        // if condition #2 holds once we have selected the matching instruction.
        CI.InstsToMove.push_back(&*MBBI);
        addDefsUsesToList(*MBBI, RegDefsToMove, PhysRegUsesToMove);
        continue;
      }

      // When we match I with another DS instruction we will be moving I down
      // to the location of the matched instruction any uses of I will need to
      // be moved down as well.
      addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
                            CI.InstsToMove);
      continue;
    }

    // Don't merge volatiles.
    if (MBBI->hasOrderedMemoryRef())
      return false;

    // Handle a case like
    //   DS_WRITE_B32 addr, v, idx0
    //   w = DS_READ_B32 addr, idx0
    //   DS_WRITE_B32 addr, f(w), idx1
    // where the DS_READ_B32 ends up in InstsToMove and therefore prevents
    // merging of the two writes.
    if (addToListsIfDependent(*MBBI, RegDefsToMove, PhysRegUsesToMove,
                              CI.InstsToMove))
      continue;

    bool Match = true;
    for (unsigned i = 0; i < NumAddresses; i++) {
      const MachineOperand &AddrRegNext = MBBI->getOperand(AddrIdx[i]);

      if (AddrReg[i]->isImm() || AddrRegNext.isImm()) {
        if (AddrReg[i]->isImm() != AddrRegNext.isImm() ||
            AddrReg[i]->getImm() != AddrRegNext.getImm()) {
          Match = false;
          break;
        }
        continue;
      }

      // Check same base pointer. Be careful of subregisters, which can occur with
      // vectors of pointers.
      if (AddrReg[i]->getReg() != AddrRegNext.getReg() ||
          AddrReg[i]->getSubReg() != AddrRegNext.getSubReg()) {
        Match = false;
        break;
      }
    }

    if (Match) {
      int OffsetIdx = AMDGPU::getNamedOperandIdx(CI.I->getOpcode(),
                                                 AMDGPU::OpName::offset);
      CI.Offset0 = CI.I->getOperand(OffsetIdx).getImm();
      CI.Offset1 = MBBI->getOperand(OffsetIdx).getImm();
      CI.Paired = MBBI;

      if (CI.InstClass == DS_READ_WRITE) {
        CI.Offset0 &= 0xffff;
        CI.Offset1 &= 0xffff;
      } else {
        CI.GLC0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::glc)->getImm();
        CI.GLC1 = TII->getNamedOperand(*MBBI, AMDGPU::OpName::glc)->getImm();
        if (CI.InstClass != S_BUFFER_LOAD_IMM) {
          CI.SLC0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::slc)->getImm();
          CI.SLC1 = TII->getNamedOperand(*MBBI, AMDGPU::OpName::slc)->getImm();
        }
      }

      // Check both offsets fit in the reduced range.
      // We also need to go through the list of instructions that we plan to
      // move and make sure they are all safe to move down past the merged
      // instruction.
      if (offsetsCanBeCombined(CI))
        if (canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, TII, AA))
          return true;
    }

    // We've found a load/store that we couldn't merge for some reason.
    // We could potentially keep looking, but we'd need to make sure that
    // it was safe to move I and also all the instruction in InstsToMove
    // down past this instruction.
    // check if we can move I across MBBI and if we can move all I's users
    if (!memAccessesCanBeReordered(*CI.I, *MBBI, TII, AA) ||
        !canMoveInstsAcrossMemOp(*MBBI, CI.InstsToMove, TII, AA))
      break;
  }
  return false;
}

unsigned SILoadStoreOptimizer::read2Opcode(unsigned EltSize) const {
  if (STM->ldsRequiresM0Init())
    return (EltSize == 4) ? AMDGPU::DS_READ2_B32 : AMDGPU::DS_READ2_B64;
  return (EltSize == 4) ? AMDGPU::DS_READ2_B32_gfx9 : AMDGPU::DS_READ2_B64_gfx9;
}

unsigned SILoadStoreOptimizer::read2ST64Opcode(unsigned EltSize) const {
  if (STM->ldsRequiresM0Init())
    return (EltSize == 4) ? AMDGPU::DS_READ2ST64_B32 : AMDGPU::DS_READ2ST64_B64;

  return (EltSize == 4) ?
    AMDGPU::DS_READ2ST64_B32_gfx9 : AMDGPU::DS_READ2ST64_B64_gfx9;
}

MachineBasicBlock::iterator  SILoadStoreOptimizer::mergeRead2Pair(
  CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();

  // Be careful, since the addresses could be subregisters themselves in weird
  // cases, like vectors of pointers.
  const auto *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);

  const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdst);
  const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdst);

  unsigned NewOffset0 = CI.Offset0;
  unsigned NewOffset1 = CI.Offset1;
  unsigned Opc = CI.UseST64 ?
    read2ST64Opcode(CI.EltSize) : read2Opcode(CI.EltSize);

  unsigned SubRegIdx0 = (CI.EltSize == 4) ? AMDGPU::sub0 : AMDGPU::sub0_sub1;
  unsigned SubRegIdx1 = (CI.EltSize == 4) ? AMDGPU::sub1 : AMDGPU::sub2_sub3;

  if (NewOffset0 > NewOffset1) {
    // Canonicalize the merged instruction so the smaller offset comes first.
    std::swap(NewOffset0, NewOffset1);
    std::swap(SubRegIdx0, SubRegIdx1);
  }

  assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
         (NewOffset0 != NewOffset1) &&
         "Computed offset doesn't fit");

  const MCInstrDesc &Read2Desc = TII->get(Opc);

  const TargetRegisterClass *SuperRC
    = (CI.EltSize == 4) ? &AMDGPU::VReg_64RegClass : &AMDGPU::VReg_128RegClass;
  unsigned DestReg = MRI->createVirtualRegister(SuperRC);

  DebugLoc DL = CI.I->getDebugLoc();

  unsigned BaseReg = AddrReg->getReg();
  unsigned BaseRegFlags = 0;
  if (CI.BaseOff) {
    unsigned ImmReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
    BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
      .addImm(CI.BaseOff);

    BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
    BaseRegFlags = RegState::Kill;

    TII->getAddNoCarry(*MBB, CI.Paired, DL, BaseReg)
      .addReg(ImmReg)
      .addReg(AddrReg->getReg());
  }

  MachineInstrBuilder Read2 =
    BuildMI(*MBB, CI.Paired, DL, Read2Desc, DestReg)
      .addReg(BaseReg, BaseRegFlags) // addr
      .addImm(NewOffset0)            // offset0
      .addImm(NewOffset1)            // offset1
      .addImm(0)                     // gds
      .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired));

  (void)Read2;

  const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);

  // Copy to the old destination registers.
  BuildMI(*MBB, CI.Paired, DL, CopyDesc)
      .add(*Dest0) // Copy to same destination including flags and sub reg.
      .addReg(DestReg, 0, SubRegIdx0);
  MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
                            .add(*Dest1)
                            .addReg(DestReg, RegState::Kill, SubRegIdx1);

  moveInstsAfter(Copy1, CI.InstsToMove);

  MachineBasicBlock::iterator Next = std::next(CI.I);
  CI.I->eraseFromParent();
  CI.Paired->eraseFromParent();

  LLVM_DEBUG(dbgs() << "Inserted read2: " << *Read2 << '\n');
  return Next;
}

unsigned SILoadStoreOptimizer::write2Opcode(unsigned EltSize) const {
  if (STM->ldsRequiresM0Init())
    return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32 : AMDGPU::DS_WRITE2_B64;
  return (EltSize == 4) ? AMDGPU::DS_WRITE2_B32_gfx9 : AMDGPU::DS_WRITE2_B64_gfx9;
}

unsigned SILoadStoreOptimizer::write2ST64Opcode(unsigned EltSize) const {
  if (STM->ldsRequiresM0Init())
    return (EltSize == 4) ? AMDGPU::DS_WRITE2ST64_B32 : AMDGPU::DS_WRITE2ST64_B64;

  return (EltSize == 4) ?
    AMDGPU::DS_WRITE2ST64_B32_gfx9 : AMDGPU::DS_WRITE2ST64_B64_gfx9;
}

MachineBasicBlock::iterator SILoadStoreOptimizer::mergeWrite2Pair(
  CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();

  // Be sure to use .addOperand(), and not .addReg() with these. We want to be
  // sure we preserve the subregister index and any register flags set on them.
  const MachineOperand *AddrReg = TII->getNamedOperand(*CI.I, AMDGPU::OpName::addr);
  const MachineOperand *Data0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::data0);
  const MachineOperand *Data1
    = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::data0);

  unsigned NewOffset0 = CI.Offset0;
  unsigned NewOffset1 = CI.Offset1;
  unsigned Opc = CI.UseST64 ?
    write2ST64Opcode(CI.EltSize) : write2Opcode(CI.EltSize);

  if (NewOffset0 > NewOffset1) {
    // Canonicalize the merged instruction so the smaller offset comes first.
    std::swap(NewOffset0, NewOffset1);
    std::swap(Data0, Data1);
  }

  assert((isUInt<8>(NewOffset0) && isUInt<8>(NewOffset1)) &&
         (NewOffset0 != NewOffset1) &&
         "Computed offset doesn't fit");

  const MCInstrDesc &Write2Desc = TII->get(Opc);
  DebugLoc DL = CI.I->getDebugLoc();

  unsigned BaseReg = AddrReg->getReg();
  unsigned BaseRegFlags = 0;
  if (CI.BaseOff) {
    unsigned ImmReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
    BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::S_MOV_B32), ImmReg)
      .addImm(CI.BaseOff);

    BaseReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
    BaseRegFlags = RegState::Kill;

    TII->getAddNoCarry(*MBB, CI.Paired, DL, BaseReg)
      .addReg(ImmReg)
      .addReg(AddrReg->getReg());
  }

  MachineInstrBuilder Write2 =
    BuildMI(*MBB, CI.Paired, DL, Write2Desc)
      .addReg(BaseReg, BaseRegFlags) // addr
      .add(*Data0)                   // data0
      .add(*Data1)                   // data1
      .addImm(NewOffset0)            // offset0
      .addImm(NewOffset1)            // offset1
      .addImm(0)                     // gds
      .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired));

  moveInstsAfter(Write2, CI.InstsToMove);

  MachineBasicBlock::iterator Next = std::next(CI.I);
  CI.I->eraseFromParent();
  CI.Paired->eraseFromParent();

  LLVM_DEBUG(dbgs() << "Inserted write2 inst: " << *Write2 << '\n');
  return Next;
}

MachineBasicBlock::iterator SILoadStoreOptimizer::mergeSBufferLoadImmPair(
  CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();
  DebugLoc DL = CI.I->getDebugLoc();
  unsigned Opcode = CI.IsX2 ? AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM :
                              AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;

  const TargetRegisterClass *SuperRC =
    CI.IsX2 ? &AMDGPU::SReg_128RegClass : &AMDGPU::SReg_64_XEXECRegClass;
  unsigned DestReg = MRI->createVirtualRegister(SuperRC);
  unsigned MergedOffset = std::min(CI.Offset0, CI.Offset1);

  BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode), DestReg)
      .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::sbase))
      .addImm(MergedOffset) // offset
      .addImm(CI.GLC0)      // glc
      .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired));

  unsigned SubRegIdx0 = CI.IsX2 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
  unsigned SubRegIdx1 = CI.IsX2 ? AMDGPU::sub2_sub3 : AMDGPU::sub1;

  // Handle descending offsets
  if (CI.Offset0 > CI.Offset1)
    std::swap(SubRegIdx0, SubRegIdx1);

  // Copy to the old destination registers.
  const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
  const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::sdst);
  const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::sdst);

  BuildMI(*MBB, CI.Paired, DL, CopyDesc)
      .add(*Dest0) // Copy to same destination including flags and sub reg.
      .addReg(DestReg, 0, SubRegIdx0);
  MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
                            .add(*Dest1)
                            .addReg(DestReg, RegState::Kill, SubRegIdx1);

  moveInstsAfter(Copy1, CI.InstsToMove);

  MachineBasicBlock::iterator Next = std::next(CI.I);
  CI.I->eraseFromParent();
  CI.Paired->eraseFromParent();
  return Next;
}

MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferLoadPair(
  CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();
  DebugLoc DL = CI.I->getDebugLoc();
  unsigned Opcode;

  if (CI.InstClass == BUFFER_LOAD_OFFEN) {
    Opcode = CI.IsX2 ? AMDGPU::BUFFER_LOAD_DWORDX4_OFFEN :
                       AMDGPU::BUFFER_LOAD_DWORDX2_OFFEN;
  } else {
    Opcode = CI.IsX2 ? AMDGPU::BUFFER_LOAD_DWORDX4_OFFSET :
                       AMDGPU::BUFFER_LOAD_DWORDX2_OFFSET;
  }

  const TargetRegisterClass *SuperRC =
    CI.IsX2 ? &AMDGPU::VReg_128RegClass : &AMDGPU::VReg_64RegClass;
  unsigned DestReg = MRI->createVirtualRegister(SuperRC);
  unsigned MergedOffset = std::min(CI.Offset0, CI.Offset1);

  auto MIB = BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode), DestReg);

  if (CI.InstClass == BUFFER_LOAD_OFFEN)
      MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));

  MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
      .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
      .addImm(MergedOffset) // offset
      .addImm(CI.GLC0)      // glc
      .addImm(CI.SLC0)      // slc
      .addImm(0)            // tfe
      .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired));

  unsigned SubRegIdx0 = CI.IsX2 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
  unsigned SubRegIdx1 = CI.IsX2 ? AMDGPU::sub2_sub3 : AMDGPU::sub1;

  // Handle descending offsets
  if (CI.Offset0 > CI.Offset1)
    std::swap(SubRegIdx0, SubRegIdx1);

  // Copy to the old destination registers.
  const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
  const auto *Dest0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
  const auto *Dest1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdata);

  BuildMI(*MBB, CI.Paired, DL, CopyDesc)
      .add(*Dest0) // Copy to same destination including flags and sub reg.
      .addReg(DestReg, 0, SubRegIdx0);
  MachineInstr *Copy1 = BuildMI(*MBB, CI.Paired, DL, CopyDesc)
                            .add(*Dest1)
                            .addReg(DestReg, RegState::Kill, SubRegIdx1);

  moveInstsAfter(Copy1, CI.InstsToMove);

  MachineBasicBlock::iterator Next = std::next(CI.I);
  CI.I->eraseFromParent();
  CI.Paired->eraseFromParent();
  return Next;
}

unsigned SILoadStoreOptimizer::promoteBufferStoreOpcode(
  const MachineInstr &I, bool &IsX2, bool &IsOffen) const {
  IsX2 = false;
  IsOffen = false;

  switch (I.getOpcode()) {
  case AMDGPU::BUFFER_STORE_DWORD_OFFEN:
    IsOffen = true;
    return AMDGPU::BUFFER_STORE_DWORDX2_OFFEN;
  case AMDGPU::BUFFER_STORE_DWORD_OFFEN_exact:
    IsOffen = true;
    return AMDGPU::BUFFER_STORE_DWORDX2_OFFEN_exact;
  case AMDGPU::BUFFER_STORE_DWORDX2_OFFEN:
    IsX2 = true;
    IsOffen = true;
    return AMDGPU::BUFFER_STORE_DWORDX4_OFFEN;
  case AMDGPU::BUFFER_STORE_DWORDX2_OFFEN_exact:
    IsX2 = true;
    IsOffen = true;
    return AMDGPU::BUFFER_STORE_DWORDX4_OFFEN_exact;
  case AMDGPU::BUFFER_STORE_DWORD_OFFSET:
    return AMDGPU::BUFFER_STORE_DWORDX2_OFFSET;
  case AMDGPU::BUFFER_STORE_DWORD_OFFSET_exact:
    return AMDGPU::BUFFER_STORE_DWORDX2_OFFSET_exact;
  case AMDGPU::BUFFER_STORE_DWORDX2_OFFSET:
    IsX2 = true;
    return AMDGPU::BUFFER_STORE_DWORDX4_OFFSET;
  case AMDGPU::BUFFER_STORE_DWORDX2_OFFSET_exact:
    IsX2 = true;
    return AMDGPU::BUFFER_STORE_DWORDX4_OFFSET_exact;
  }
  return 0;
}

MachineBasicBlock::iterator SILoadStoreOptimizer::mergeBufferStorePair(
  CombineInfo &CI) {
  MachineBasicBlock *MBB = CI.I->getParent();
  DebugLoc DL = CI.I->getDebugLoc();
  bool Unused1, Unused2;
  unsigned Opcode = promoteBufferStoreOpcode(*CI.I, Unused1, Unused2);

  unsigned SubRegIdx0 = CI.IsX2 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
  unsigned SubRegIdx1 = CI.IsX2 ? AMDGPU::sub2_sub3 : AMDGPU::sub1;

  // Handle descending offsets
  if (CI.Offset0 > CI.Offset1)
    std::swap(SubRegIdx0, SubRegIdx1);

  // Copy to the new source register.
  const TargetRegisterClass *SuperRC =
    CI.IsX2 ? &AMDGPU::VReg_128RegClass : &AMDGPU::VReg_64RegClass;
  unsigned SrcReg = MRI->createVirtualRegister(SuperRC);

  const auto *Src0 = TII->getNamedOperand(*CI.I, AMDGPU::OpName::vdata);
  const auto *Src1 = TII->getNamedOperand(*CI.Paired, AMDGPU::OpName::vdata);

  BuildMI(*MBB, CI.Paired, DL, TII->get(AMDGPU::REG_SEQUENCE), SrcReg)
      .add(*Src0)
      .addImm(SubRegIdx0)
      .add(*Src1)
      .addImm(SubRegIdx1);

  auto MIB = BuildMI(*MBB, CI.Paired, DL, TII->get(Opcode))
      .addReg(SrcReg, RegState::Kill);

  if (CI.InstClass == BUFFER_STORE_OFFEN)
      MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::vaddr));

  MIB.add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::srsrc))
      .add(*TII->getNamedOperand(*CI.I, AMDGPU::OpName::soffset))
      .addImm(std::min(CI.Offset0, CI.Offset1)) // offset
      .addImm(CI.GLC0)      // glc
      .addImm(CI.SLC0)      // slc
      .addImm(0)            // tfe
      .setMemRefs(CI.I->mergeMemRefsWith(*CI.Paired));

  moveInstsAfter(MIB, CI.InstsToMove);

  MachineBasicBlock::iterator Next = std::next(CI.I);
  CI.I->eraseFromParent();
  CI.Paired->eraseFromParent();
  return Next;
}

// Scan through looking for adjacent LDS operations with constant offsets from
// the same base register. We rely on the scheduler to do the hard work of
// clustering nearby loads, and assume these are all adjacent.
bool SILoadStoreOptimizer::optimizeBlock(MachineBasicBlock &MBB) {
  bool Modified = false;

  for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
    MachineInstr &MI = *I;

    // Don't combine if volatile.
    if (MI.hasOrderedMemoryRef()) {
      ++I;
      continue;
    }

    CombineInfo CI;
    CI.I = I;
    unsigned Opc = MI.getOpcode();
    if (Opc == AMDGPU::DS_READ_B32 || Opc == AMDGPU::DS_READ_B64 ||
        Opc == AMDGPU::DS_READ_B32_gfx9 || Opc == AMDGPU::DS_READ_B64_gfx9) {

      CI.InstClass = DS_READ_WRITE;
      CI.EltSize =
        (Opc == AMDGPU::DS_READ_B64 || Opc == AMDGPU::DS_READ_B64_gfx9) ? 8 : 4;

      if (findMatchingInst(CI)) {
        Modified = true;
        I = mergeRead2Pair(CI);
      } else {
        ++I;
      }

      continue;
    } else if (Opc == AMDGPU::DS_WRITE_B32 || Opc == AMDGPU::DS_WRITE_B64 ||
               Opc == AMDGPU::DS_WRITE_B32_gfx9 ||
               Opc == AMDGPU::DS_WRITE_B64_gfx9) {
      CI.InstClass = DS_READ_WRITE;
      CI.EltSize
        = (Opc == AMDGPU::DS_WRITE_B64 || Opc == AMDGPU::DS_WRITE_B64_gfx9) ? 8 : 4;

      if (findMatchingInst(CI)) {
        Modified = true;
        I = mergeWrite2Pair(CI);
      } else {
        ++I;
      }

      continue;
    }
    if (Opc == AMDGPU::S_BUFFER_LOAD_DWORD_IMM ||
        Opc == AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM) {
      // EltSize is in units of the offset encoding.
      CI.InstClass = S_BUFFER_LOAD_IMM;
      CI.EltSize = AMDGPU::getSMRDEncodedOffset(*STM, 4);
      CI.IsX2 = Opc == AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM;
      if (findMatchingInst(CI)) {
        Modified = true;
        I = mergeSBufferLoadImmPair(CI);
        if (!CI.IsX2)
          CreatedX2++;
      } else {
        ++I;
      }
      continue;
    }
    if (Opc == AMDGPU::BUFFER_LOAD_DWORD_OFFEN ||
        Opc == AMDGPU::BUFFER_LOAD_DWORDX2_OFFEN ||
        Opc == AMDGPU::BUFFER_LOAD_DWORD_OFFSET ||
        Opc == AMDGPU::BUFFER_LOAD_DWORDX2_OFFSET) {
      if (Opc == AMDGPU::BUFFER_LOAD_DWORD_OFFEN ||
          Opc == AMDGPU::BUFFER_LOAD_DWORDX2_OFFEN)
        CI.InstClass = BUFFER_LOAD_OFFEN;
      else
        CI.InstClass = BUFFER_LOAD_OFFSET;

      CI.EltSize = 4;
      CI.IsX2 = Opc == AMDGPU::BUFFER_LOAD_DWORDX2_OFFEN ||
                Opc == AMDGPU::BUFFER_LOAD_DWORDX2_OFFSET;
      if (findMatchingInst(CI)) {
        Modified = true;
        I = mergeBufferLoadPair(CI);
        if (!CI.IsX2)
          CreatedX2++;
      } else {
        ++I;
      }
      continue;
    }

    bool StoreIsX2, IsOffen;
    if (promoteBufferStoreOpcode(*I, StoreIsX2, IsOffen)) {
      CI.InstClass = IsOffen ? BUFFER_STORE_OFFEN : BUFFER_STORE_OFFSET;
      CI.EltSize = 4;
      CI.IsX2 = StoreIsX2;
      if (findMatchingInst(CI)) {
        Modified = true;
        I = mergeBufferStorePair(CI);
        if (!CI.IsX2)
          CreatedX2++;
      } else {
        ++I;
      }
      continue;
    }

    ++I;
  }

  return Modified;
}

bool SILoadStoreOptimizer::runOnMachineFunction(MachineFunction &MF) {
  if (skipFunction(MF.getFunction()))
    return false;

  STM = &MF.getSubtarget<GCNSubtarget>();
  if (!STM->loadStoreOptEnabled())
    return false;

  TII = STM->getInstrInfo();
  TRI = &TII->getRegisterInfo();

  MRI = &MF.getRegInfo();
  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();

  assert(MRI->isSSA() && "Must be run on SSA");

  LLVM_DEBUG(dbgs() << "Running SILoadStoreOptimizer\n");

  bool Modified = false;

  for (MachineBasicBlock &MBB : MF) {
    CreatedX2 = 0;
    Modified |= optimizeBlock(MBB);

    // Run again to convert x2 to x4.
    if (CreatedX2 >= 1)
      Modified |= optimizeBlock(MBB);
  }

  return Modified;
}

redpajama_set_name: RedPajamaGithub


text:
@if(! $exchanges->isEmpty())

Exchanges waiting your confirmation

                    @each('exchanges.dashboard.proposed.show', $exchanges, 'exchange')

@endif


text:
<?

/**
 * Functions useful for adding asset library access to your blocks and applications.
 * @package Helpers
 * @category Concrete
 * @author Andrew Embler <andrew@concrete5.org>
 * @copyright  Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org)
 * @license    http://www.concrete5.org/license/     MIT License
 */

	defined('C5_EXECUTE') or die("Access Denied.");
	class ConcreteAssetLibraryHelper {

		/**
		 * Sets up a file field for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */
		public function file($id, $postname, $chooseText, $bf = null, $filterArgs = array()) {

			$selectedDisplay = 'none';
			$resetDisplay = 'block';
			$fileID = 0;

			/**
			 * If $_POST[$postname] is a valid File ID
			 * use that file
			 * If not try to use the $bf parameter passed in
			 */
			$vh = Loader::helper('validation/numbers');
			if (isset($_POST[$postname]) && $vh->integer($_POST[$postname])) {
				$postFile = File::getByID($_POST[$postname]);
				if (!$postFile->isError() && $postFile->getFileID() > 0) {
					$bf = $postFile;
				}
			}

			if (is_object($bf) && (!$bf->isError()) && $bf->getFileID() > 0) {
				$fileID = $bf->getFileID();
				$selectedDisplay = 'block';
				$resetDisplay = 'none';
			}

			$html = '

';

			$html .= '
';
			$html .= '' . $chooseText . '';
			if ($filterArgs != false) {
				foreach($filterArgs as $key => $value) {
					if(is_array($value)) {
						foreach($value as $valueItem) {
							$html .= '<input type="hidden" class="ccm-file-manager-filter" name="' . $key . '" value="' . $valueItem . '" />';
						}
					}
					else {
						$html .= '<input type="hidden" class="ccm-file-manager-filter" name="' . $key . '" value="' . $value . '" />';
					}
				}
			}
			$html .= '
<input id="' . $id . '-fm-value" type="hidden" name="' . $postname . '" value="' . $fileID . '" />';

			if (is_object($bf) && (!$bf->isError()) && $bf->getFileID() > 0) {
				$html .= '';
			}

			return $html;
		}

		/**
		 * Sets up an image to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */
		public function image($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_IMAGE;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}
		/**
		* Sets up a video to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */

		public function video($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_VIDEO;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}

			/**
		* Sets up a text file to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */

		public function text($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_TEXT;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}

		 /**
		 * Sets up audio to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */

		public function audio($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_AUDIO;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}

		 /**
		 * Sets up a document to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */

		public function doc($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_DOCUMENT;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}

		 /**
		 * Sets up an application to be chosen for use with a block.
		 * @param string $id The ID of your form field
		 * @param string $postname The name of your database column into which you'd like to save the file ID
		 * @param string $chooseText
		 * @param LibraryFileBlock $bf
		 * return string $html
		 */

		public function app($id, $postname, $chooseText, $fileInstanceBlock = null, $additionalArgs = array()) {
			$args = array();
			$args['fType'] = FileType::T_APPLICATION;
			$args = array_merge($args, $additionalArgs);
			return $this->file($id, $postname, $chooseText, $fileInstanceBlock, $args);
		}

	}


text:
package avlTree.slpBuilders;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import SLPs.ISLPExtractor;
import avlTree.IAvlTree;
import avlTree.IAvlTreeManager;
import avlTree.IAvlTreeManagerFactory;
import avlTree.buffers.IAvlTreeBuffer;
import avlTree.buffers.IAvlTreeBufferFactory;
import avlTree.helpers.AvlTreeArrayMergeCounter;
import avlTree.helpers.IAvlTreeArrayMergeCounter;
import avlTree.helpers.IRebalancingCounter;
import avlTree.helpers.NodesCacheStatisticsCounter;
import avlTree.helpers.RebalancingCounter;
import commons.utils.TimeCounter;
import dataContracts.FactorDef;
import dataContracts.SLPModel;
import dataContracts.statistics.IStatistics;
import dataContracts.statistics.StatisticKeys;
import productEnumerator.IProductEnumerator;
import serialization.products.IProductSerializer;

public class AvlTreeSLPBuilder implements IAvlTreeSLPBuilder {
    private static final Logger log = LogManager.getLogger(AvlTreeSLPBuilder.class);

    private IAvlTreeManagerFactory avlTreeManagerFactory;
    private IAvlTreeBufferFactory avlTreeBufferFactory;
    private final ISLPExtractor slpExtractor;
    private IProductSerializer productsSerializer;

    public AvlTreeSLPBuilder(
            IAvlTreeManagerFactory avlTreeManagerFactory,
            IAvlTreeBufferFactory avlTreeBufferFactory,
            ISLPExtractor slpExtractor,
            IProductSerializer productsSerializer) {
        this.avlTreeManagerFactory = avlTreeManagerFactory;
        this.avlTreeBufferFactory = avlTreeBufferFactory;
        this.slpExtractor = slpExtractor;
        this.productsSerializer = productsSerializer;
    }

    @Override
    public SLPModel buildSlp(FactorDef[] factors, IStatistics statistics) {
        TimeCounter timeCounter = TimeCounter.start();
        IAvlTree resultTree = buildAvlTree(factors, statistics);
        IProductEnumerator slpBuilder = slpExtractor.getSLP(resultTree);
        timeCounter.finish();
        resultTree.dispose();

        SLPModel slpModel = slpBuilder.toSLPModel();
        statistics.putParam(StatisticKeys.FactorizationLength, factors.length);
        statistics.putParam(StatisticKeys.RunningTime, timeCounter.getMillis());
        slpModel.appendStats(statistics, productsSerializer);
        return slpModel;
    }

    private IAvlTree buildAvlTree(FactorDef[] factors, IStatistics statistics) {
        NodesCacheStatisticsCounter nodesCacheStatisticsCounter = new NodesCacheStatisticsCounter();
        IRebalancingCounter rebalancingCounter = new RebalancingCounter();
        IAvlTreeArrayMergeCounter avlTreeArrayMergeCounter = new AvlTreeArrayMergeCounter();

        IAvlTreeManager avlTreeManager = avlTreeManagerFactory.create();
        IAvlTreeBuffer buffer = avlTreeBufferFactory.create(rebalancingCounter, nodesCacheStatisticsCounter, avlTreeArrayMergeCounter, avlTreeManager.createEmptyTree());
        for (int i = 0; i < factors.length; i++) {
            FactorDef factor = factors[i];
            if (factor.isTerminal)
                buffer.append(avlTreeManager.createNewTree((long) factor.symbol));
            else
                buffer.append(buffer.substring(factor.beginPosition, factor.beginPosition + factor.length));

            if (i % 10000 == 0) {
                log.info(String.format("Processed %d factors from %d", i, factors.length));
            }
        }
        IAvlTree resultTree = buffer.getTree();

        avlTreeArrayMergeCounter.printStatistics();
        statistics.putParam(StatisticKeys.RebalanceCount, rebalancingCounter.getCount());
        return resultTree;
    }
}


text:
from __future__ import print_function

import argparse
import json
import os

_FILE_URL = 'https://repo.maven.apache.org/maven2/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar'
_FILE_NAME = 'checker-qual-3.12.0.jar'
_FILE_VERSION = '3.12.0'

def do_latest():
    print(_FILE_VERSION)

def get_download_url(version):
    if _FILE_URL.endswith('.jar'):
        ext = '.jar'
    elif _FILE_URL.endswith('.aar'):
        ext = '.aar'
    else:
        raise Exception('Unsupported extension for %s' % _FILE_URL)

    partial_manifest = {
        'url': [_FILE_URL],
        'name': [_FILE_NAME],
        'ext': ext,
    }
    print(json.dumps(partial_manifest))

def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers()

    latest = sub.add_parser("latest")
    latest.set_defaults(func=lambda _opts: do_latest())

    download = sub.add_parser("get_url")
    download.set_defaults(
        func=lambda _opts: get_download_url(os.environ['_3PP_VERSION']))

    opts = ap.parse_args()
    opts.func(opts)

if __name__ == '__main__':
    main()


text:
package com.google.places.showcase.utils;

import com.squareup.otto.Bus;

/**
 * Default event bus provider
 */
public final class BusProvider {
    private static final MainThreadBus BUS = new MainThreadBus();

    public static Bus getInstance() {
        return BUS;
    }

    private BusProvider() {
        // no instances allowed
    }
}


text:
package com.datastax.driver.core;

import com.datastax.driver.core.exceptions.DriverInternalError;
import com.datastax.driver.core.exceptions.FrameTooLongException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.*;

import java.util.EnumSet;
import java.util.List;

/**
 * A frame for the CQL binary protocol.
 *

 * Each frame contains a fixed size header (8 bytes for V1 and V2, 9 bytes for V3 and V4)
 * followed by a variable size body. The content of the body depends
 * on the header opcode value (the body can in particular be empty for some
 * opcode values).
 *

 * The protocol distinguishes 2 types of frames: requests and responses. Requests
 * are those frames sent by the clients to the server, response are the ones sent
 * by the server. Note however that the protocol supports server pushes (events)
 * so responses does not necessarily come right after a client request.
 *

 * Frames for protocol versions 1+2 are defined as:
 *

 *

 *  0         8        16        24        32
 * +---------+---------+---------+---------+
 * | version |  flags  | stream  | opcode  |
 * +---------+---------+---------+---------+
 * |                length                 |
 * +---------+---------+---------+---------+
 * |                                       |
 * .            ...  body ...              .
 * .                                       .
 * .                                       .
 * +---------------------------------------- *
 *

 *

 * Frames for protocol versions 3+4 are defined as:
 *

 *

 * 0         8        16        24        32         40
 * +---------+---------+---------+---------+---------+
 * | version |  flags  |      stream       | opcode  |
 * +---------+---------+---------+---------+---------+
 * |                length                 |
 * +---------+---------+---------+---------+
 * |                                       |
 * .            ...  body ...              .
 * .                                       .
 * .                                       .
 * +----------------------------------------
 *

 *
 * @see "https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v1.spec"
 * @see "https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v2.spec"
 * @see "https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec"
 * @see "https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec"
 */
class Frame {

    final Header header;
    final ByteBuf body;

    private Frame(Header header, ByteBuf body) {
        this.header = header;
        this.body = body;
    }

    private static Frame create(ByteBuf fullFrame) {
        assert fullFrame.readableBytes() >= 1 : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());

        int versionBytes = fullFrame.readByte();
        // version first byte is the "direction" of the frame (request or response)
        ProtocolVersion version = ProtocolVersion.fromInt(versionBytes & 0x7F);
        int hdrLen = Header.lengthFor(version);
        assert fullFrame.readableBytes() >= (hdrLen - 1) : String.format("Frame too short (%d bytes)", fullFrame.readableBytes());

        int flags = fullFrame.readByte();
        int streamId = readStreamid(fullFrame, version);
        int opcode = fullFrame.readByte();
        int length = fullFrame.readInt();
        assert length == fullFrame.readableBytes();

        Header header = new Header(version, flags, streamId, opcode);
        return new Frame(header, fullFrame);
    }

    private static int readStreamid(ByteBuf fullFrame, ProtocolVersion version) {
        switch (version) {
            case V1:
            case V2:
                return fullFrame.readByte();
            case V3:
            case V4:
            case V5:
                return fullFrame.readShort();
            default:
                throw version.unsupported();
        }
    }

    static Frame create(ProtocolVersion version, int opcode, int streamId, EnumSet flags, ByteBuf body) {
        Header header = new Header(version, flags, streamId, opcode);
        return new Frame(header, body);
    }

    static class Header {

        final ProtocolVersion version;
        final EnumSet<Flag> flags;
        final int streamId;
        final int opcode;

        private Header(ProtocolVersion version, int flags, int streamId, int opcode) {
            this(version, Flag.deserialize(flags), streamId, opcode);
        }

        private Header(ProtocolVersion version, EnumSet<Flag> flags, int streamId, int opcode) {
            this.version = version;
            this.flags = flags;
            this.streamId = streamId;
            this.opcode = opcode;
        }

        /**
         * Return the expected frame header length in bytes according to the protocol version in use.
         *
         * @param version the protocol version in use
         * @return the expected frame header length in bytes
         */
        static int lengthFor(ProtocolVersion version) {
            switch (version) {
                case V1:
                case V2:
                    return 8;
                case V3:
                case V4:
                case V5:
                    return 9;
                default:
                    throw version.unsupported();
            }
        }

        enum Flag {
            // The order of that enum matters!!
            COMPRESSED,
            TRACING,
            CUSTOM_PAYLOAD,
            WARNING,
            USE_BETA;

            static EnumSet<Flag> deserialize(int flags) {
                EnumSet<Flag> set = EnumSet.noneOf(Flag.class);
                Flag[] values = Flag.values();
                for (int n = 0; n < 8; n++) {
                    if ((flags & (1 << n)) != 0)
                        set.add(values[n]);
                }
                return set;
            }

            static int serialize(EnumSet<Flag> flags) {
                int i = 0;
                for (Flag flag : flags)
                    i |= 1 << flag.ordinal();
                return i;
            }
        }
    }

    Frame with(ByteBuf newBody) {
        return new Frame(header, newBody);
    }

    static final class Decoder extends ByteToMessageDecoder {
        private DecoderForStreamIdSize decoder;

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
            if (buffer.readableBytes() < 1)
                return;

            // Initialize sub decoder on first message.  No synchronization needed as
            // decode is always called from same thread.
            if (decoder == null) {
                int version = buffer.getByte(buffer.readerIndex());
                // version first bit is the "direction" of the frame (request or response)
                version = version & 0x7F;
                decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1);
            }

            Object frame = decoder.decode(ctx, buffer);
            if (frame != null)
                out.add(frame);
        }

        static class DecoderForStreamIdSize extends LengthFieldBasedFrameDecoder {
            // The maximum response frame length allowed.  Note that C* does not currently restrict the length of its responses (CASSANDRA-12630).
            private static final int MAX_FRAME_LENGTH = SystemProperties.getInt("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", 256) * 1024 * 1024; // 256 MB
            private final int protocolVersion;

            DecoderForStreamIdSize(int protocolVersion, int streamIdSize) {
                super(MAX_FRAME_LENGTH, /*lengthOffset=*/ 3 + streamIdSize, 4, 0, 0, true);
                this.protocolVersion = protocolVersion;
            }

            @Override
            protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
                // Capture current index in case we need to get the stream id.
                // If a TooLongFrameException is thrown the readerIndex will advance to the end of
                // the buffer (or past the frame) so we need the position as we entered this method.
                int curIndex = buffer.readerIndex();
                try {
                    ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
                    if (frame == null) {
                        return null;
                    }
                    // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used
                    // in Message.ProtocolDecoder or Frame.Decompressor if compression is enabled (we deallocate
                    // it there).
                    Frame theFrame = Frame.create(frame);
                    // Validate the opcode (this will throw if it's not a response)
                    Message.Response.Type.fromOpcode(theFrame.header.opcode);
                    return theFrame;
                } catch (CorruptedFrameException e) {
                    throw new DriverInternalError(e);
                } catch (TooLongFrameException e) {
                    int streamId = protocolVersion > 2 ?
                            buffer.getShort(curIndex + 2) :
                            buffer.getByte(curIndex + 2);
                    throw new FrameTooLongException(streamId);
                }
            }
        }
    }

    @ChannelHandler.Sharable
    static class Encoder extends MessageToMessageEncoder<Frame> {

        @Override
        protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
            ProtocolVersion protocolVersion = frame.header.version;
            ByteBuf header = ctx.alloc().ioBuffer(Frame.Header.lengthFor(protocolVersion));
            // We don't bother with the direction, we only send requests.
            header.writeByte(frame.header.version.toInt());
            header.writeByte(Header.Flag.serialize(frame.header.flags));
            writeStreamId(frame.header.streamId, header, protocolVersion);
            header.writeByte(frame.header.opcode);
            header.writeInt(frame.body.readableBytes());

            out.add(header);
            out.add(frame.body);
        }

        private void writeStreamId(int streamId, ByteBuf header, ProtocolVersion protocolVersion) {
            switch (protocolVersion) {
                case V1:
                case V2:
                    header.writeByte(streamId);
                    break;
                case V3:
                case V4:
                case V5:
                    header.writeShort(streamId);
                    break;
                default:
                    throw protocolVersion.unsupported();
            }
        }
    }

    static class Decompressor extends MessageToMessageDecoder<Frame> {

        private final FrameCompressor compressor;

        Decompressor(FrameCompressor compressor) {
            assert compressor != null;
            this.compressor = compressor;
        }

        @Override
        protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
            if (frame.header.flags.contains(Header.Flag.COMPRESSED)) {
                // All decompressors allocate a new buffer for the decompressed data, so this is the last time
                // we have a reference to the compressed body (and therefore a chance to release it).
                ByteBuf compressedBody = frame.body;
                try {
                    out.add(compressor.decompress(frame));
                } finally {
                    compressedBody.release();
                }
            } else {
                out.add(frame);
            }
        }
    }

    static class Compressor extends MessageToMessageEncoder<Frame> {

        private final FrameCompressor compressor;

        Compressor(FrameCompressor compressor) {
            assert compressor != null;
            this.compressor = compressor;
        }

        @Override
        protected void encode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
            // Never compress STARTUP messages
            if (frame.header.opcode == Message.Request.Type.STARTUP.opcode) {
                out.add(frame);
            } else {
                frame.header.flags.add(Header.Flag.COMPRESSED);
                // See comment in decode()
                ByteBuf uncompressedBody = frame.body;
                try {
                    out.add(compressor.compress(frame));
                } finally {
                    uncompressedBody.release();
                }
            }
        }
    }
}


text:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from apps.api.v1.views import MessagesView, ChatView

urlpatterns = [
    url(r'messages$', MessagesView.as_view()),
    url(r'chat$', ChatView.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)


text:
`char`s are generally easy to use. They can be extracted from strings, added back
(by means of a string builder), defined and initialised using literals with single quotes, as in `char ch = 'A';`
, assigned and compared.

General information on `char`s can be found here:

- [Chars documentation][chars-docs]: reference documentation for `char`.
- [Chars tutorial][chars-tutorial]: basic tutorial on how to work with chars.

However, `char`s have a number of rough edges as detailed below.
These rough edges mostly relate to the opposition
between the full unicode standard on the one side and historic representations
of text as well as performance and memory usage on the other.

## Unicode Issues

When dealing with strings, if `System.String` library methods are available you should
seek these out and use them rather than breaking the string down into characters.
Some textual "characters" consist of more than one `char` because the unicode standard
has more than 65536 code points. For instance the emojis that show up in some
of the tests have 2 `char`s as they comprise [surrogate][surrogates] characters.
Additionally, there are combining sequences for instance where in some cases
an accented character may consist of one `char` for the plain character
and another `char` for the accent.

If you have to deal with individual characters you should try to use
library methods such as [`System.Char.IsControl`][is-control], [`System.Char.IsDigit`][is-digit]
rather than making naive comparisons such as checking that a character is
between '0' and '9'. For instance, note that '٢' is the arabic digit 2. `IsDigit`
will return true for the arabic version so you need to be clear say when validating
what range of inputs is acceptable. Even the `System.Char` library methods may not
behave as you would expect when you are dealing with more obscure languages.

One way safely to break a string into display "characters" is to use [`StringInfo`][string-info] and
methods such as [`GetNexttextElement`][get-next-text-element]. This might be necessary if you are
dealing with globalization/localization. Another avenue where the scalar values
of unicode characters is important (say you are rolling your own encoding system) is to use
[runes][runes]. However, if you know the range of characters
you deal with does not include surrogates or combining character sequences (e.g. Latin ASCII) and your input
is well validated then you can avoid this. Again, the best position to be in
is where you can use `String`'s library methods.

If you do find yourself in the unenviable position of dealing with the minutiae of unicode
then [this][char-encoding-net] is a good starting point.

## Globalization

If you are working in an environment where you are dealing with multiple cultures or
the culture is important in some parts of the code but not others then be
aware of the overloads of [`ToUpper`][to-upper] and [`ToLower`][to-lower] which take a culture and
[`ToUpperInvariant`][to-upper-invariant] and [`ToLowerInvariant`][to-lower-invariant] which will provide a consistent
result irrespective of the current [culture][culture-info].

## Representation, Characters and Integers

Like other simple types (`int`s, `bool`s, etc.) the `char` has a companion
or alias type, in this case, `System.Char`. This is in fact a `struct` with
a 16 bit field. `char` in fact has some instance methods such as
`Equals`, `ToString` and [`CompareTo`][compare-to].

`char` has the same width as a [`ushort`][uint16] but they are generally
not used inter-changeably as they are in some languages. `ushort` has
to be explicitly cast to a `char`. For what it's worth `char`s can
be subject to arithmetic operations. The result of these operations is an integer.

Obviously there is no equivalence between a `byte` at 8 bits and the 16 bit `char`.

[chars-docs]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/char
[chars-tutorial]: https://csharp.net-tutorials.com/data-types/the-char-type/
[culture-info]: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netcore-3.1
[uint16]: https://docs.microsoft.com/en-us/dotnet/api/system.uint16?view=netcore-3.1
[string-info]: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.stringinfo?view=netcore-3.1
[runes]: https://docs.microsoft.com/en-us/dotnet/api/system.text.rune?view=netcore-3.1
[char-encoding-net]: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-encoding-introduction
[surrogates]: https://docs.microsoft.com/en-us/dotnet/api/system.char.issurrogate?view=netcore-3.1
[is-control]: https://docs.microsoft.com/en-us/dotnet/api/system.char.iscontrol?view=netcore-3.1
[to-upper]: https://docs.microsoft.com/en-us/dotnet/api/system.char.toupper?view=netcore-3.1#System_Char_ToUpper_System_Char_System_Globalization_CultureInfo_
[to-lower]: https://docs.microsoft.com/en-us/dotnet/api/system.char.tolower?view=netcore-3.1#System_Char_ToLower_System_Char_System_Globalization_CultureInfo_
[to-upper-invariant]: https://docs.microsoft.com/en-us/dotnet/api/system.char.toupperinvariant?view=netcore-3.1
[to-lower-invariant]: https://docs.microsoft.com/en-us/dotnet/api/system.char.tolowerinvariant?view=netcore-3.1
[is-digit]: https://docs.microsoft.com/en-us/dotnet/api/system.char.isdigit?view=netcore-3.1
[get-next-text-element]: https://docs.microsoft.com/en-us/dotnet/api/system.globalization.stringinfo.getnexttextelement?view=netcore-3.1
[compare-to]: https://docs.microsoft.com/en-us/dotnet/api/system.char.compareto?view=netcore-3.1


text:
#ifndef AVFORMAT_MMS_H
#define AVFORMAT_MMS_H

#include "url.h"

typedef struct {
    int id;
}MMSStream;

typedef struct {
    URLContext *mms_hd;                  ///< TCP connection handle
    MMSStream *streams;

    /** Buffer for outgoing packets. */
    /*@{*/
    uint8_t *write_out_ptr;              ///< Pointer for writing the buffer.
    uint8_t out_buffer[512];            ///< Buffer for outgoing packet.
    /*@}*/

    /** Buffer for incoming packets. */
    /*@{*/
    uint8_t in_buffer[65536];            ///< Buffer for incoming packets.
    uint8_t *read_in_ptr;                ///< Pointer for reading from incoming buffer.
    int remaining_in_len;                ///< Reading length from incoming buffer.
    /*@}*/

    /** Internal handling of the ASF header */
    /*@{*/
    uint8_t *asf_header;                 ///< Stored ASF header.
    int asf_header_size;                 ///< Size of stored ASF header.
    int header_parsed;                   ///< The header has been received and parsed.
    int asf_packet_len;
    int asf_header_read_size;
    /*@}*/

    int stream_num;                      ///< stream numbers.
    unsigned int nb_streams_allocated;   ///< allocated size of streams
} MMSContext;

int ff_mms_asf_header_parser(MMSContext * mms);
int ff_mms_read_data(MMSContext *mms, uint8_t *buf, const int size);
int ff_mms_read_header(MMSContext * mms, uint8_t * buf, const int size);

#endif /* AVFORMAT_MMS_H */


text:
namespace Microsoft.Azure.Management.IotHub.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The JSON-serialized array of Certificate objects.
    /// </summary>
    public partial class CertificateListDescription
    {
        /// <summary>
        /// Initializes a new instance of the CertificateListDescription class.
        /// </summary>
        public CertificateListDescription()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the CertificateListDescription class.
        /// </summary>
        /// <param name="value">The array of Certificate objects.</param>
        public CertificateListDescription(IList<CertificateDescription> value = default(IList<CertificateDescription>))
        {
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the array of Certificate objects.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<CertificateDescription> Value { get; set; }

    }
}


text:
<?php
require_once("../model/menu_model.php");
$categories = getAllCategories();
$categories = json_decode($categories, true);

require_once '../view/afegir_producte.php';
?>


text:
```
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
```

## 提升`/usr/local`权限

```
sudo chown -R `whoami` /usr/local
```
## 安装ReactNative

```
npm install -g react-native-cli
npm install -g yarn react-native-cli

```
## 创建demo工程并运行

```
react-native init demo1
cd demo1
react-native run-android
```
## 查看版本和帮助

```
react-native -h
react-native -v
```

## 安装Nuclide

在Atom中安装插件:Nuclide

## 安装React Developer Tools

在Chrome浏览器中安装调试工具。

## 安装Watchman

```
brew update
brew install watchman
```

## 查看运行日志

```
adb logcat *:S ReactNative:V ReactNativeJS:V
```

## 升级ReactNative

`react-native upgrade`

## 调试

当代码修改完成保存以后,ReactNative会检测到代码发生变化以后,会立即针对改变 进行编译。通过手机的menu键或者摇晃手机弹出调试菜单,选择'Relaod JavaScript'
## tips

### init失败

`npm WARN deprecated connect@2.30.2: connect 2.x series is deprecated
`

npm update connect@2.30.2
npm update -d

### init失败

删除yarn  `rm /usr/local/bin/yarn`

```
This will walk you through creating a new React Native project in /Users/trunx/git/rn/demo
Using yarn v1.0.0
Installing react-native...
yarn add v1.0.0
info No lockfile found.
[1/4] 🔍  Resolving packages...
error Received malformed response from registry for undefined. The registry may be down.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
{ Error: Command failed: yarn add react-native --exact
    at checkExecSyncError (child_process.js:591:13)
    at execSync (child_process.js:631:13)
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
  error: null,
  cmd: 'yarn add react-native --exact',
  file: '/bin/sh',
  args: [ '/bin/sh', '-c', 'yarn add react-native --exact' ],
  ....
  Command `yarn add react-native --exact` failed.
```

###

```
Installing react-native...
Consider installing yarn to make this faster: https://yarnpkg.com
npm WARN deprecated connect@2.30.2: connect 2.x series is deprecated
npm ERR! Unexpected end of input at 1:5370
npm ERR! ,"babel-helper-hoist-variables":"7.0.0-alpha.9"},"directories":{},"di
npm ERR!                                                                      ^

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/trunx/.npm/_logs/2017-09-10T05_20_15_338Z-debug.log
{ Error: Command failed: npm install --save --save-exact react-native
    at checkExecSyncError (child_process.js:591:13)
    at execSync (child_process.js:631:13)
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
  error: null,
  cmd: 'npm install --save --save-exact react-native',
  file: '/bin/sh',
  args:
   [ '/bin/sh',
     '-c',
     'npm install --save --save-exact react-native' ],
  options:
   { stdio: [ [Object], [Object], [Object] ],
     shell: true,
     file: '/bin/sh',
     args:
      [ '/bin/sh',
        '-c',
        'npm install --save --save-exact react-native' ],
     envPairs:
      [ 'TERM_PROGRAM=iTerm.app',
        'ANDROID_HOME=/Users/trunx/android/android-sdk',
        'TERM=xterm-256color',
        'SHELL=/bin/bash',
        'TMPDIR=/var/folders/b6/hp76wj2d7_l_wqc950blpnwh0000gq/T/',
        'GRADLE_HOME=/Users/trunx/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3',
        'GOBIN=/Users/trunx/go/package/bin',
        'Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.Hb729Z0B88/Render',
        'OLDPWD=/Users/trunx/git',
        'MAIL_USERNAME=disheng54@163.com',
        'http_proxy=http://127.0.0.1:8118',
        'USER=trunx',
        'CLASS_PATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/bin:/Users/trunx/depot_tools:/Users/trunx/android/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/go/go1.8/bin:/Users/trunx/mongodb/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/android/android-ndk-r10e:/Library/tomcat9/bin:/Users/trunx/git/startools',
        'COMMAND_MODE=unix2003',
        'ANDROID_NDK_ROOT=/Users/trunx/android/android-ndk-r10e',
        'SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.s1fYpNNUR2/Listeners',
        '__CF_USER_TEXT_ENCODING=0x1F7:0x19:0x34',
        'XWALK_OS_ANDROID=1',
        'INTEL_MULTI_OS_ENGINE_HOME=/Applications/Intel/multi_os_engine',
        'MAIL_PASSWORD=duzitingyu',
        'PATH=/Users/trunx/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/bin:/Users/trunx/depot_tools:/Users/trunx/android/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/go/go1.8/bin:/Users/trunx/mongodb/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/android/android-ndk-r10e:/Library/tomcat9/bin:/Users/trunx/git/startools',
        'PWD=/Users/trunx/git/rn',
        'JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home',
        'LANG=zh_CN.UTF-8',
        'ITERM_PROFILE=Default',
        'XPC_FLAGS=0x0',
        'ANDROID_HVPROTO=ddm',
        'https_proxy=http://127.0.0.1:8118',
        'MONGODBROOT=/Users/trunx/mongodb',
        'XPC_SERVICE_NAME=0',
        'SHLVL=1',
        'HOME=/Users/trunx',
        'COLORFGBG=7;0',
        'GOROOT=/Users/trunx/go/go1.8',
        'ITERM_SESSION_ID=w0t0p0',
        'LOGNAME=trunx',
        'GOPATH=/Users/trunx/go/package',
        'FLASKY_ADMIN=MAIL_USERNAME',
        'DISPLAY=/private/tmp/com.apple.launchd.Td9Mh1vkcE/org.macosforge.xquartz:0',
        'NDK_ROOT=/Users/trunx/android/android-ndk-r10e',
        'GYP_GENERATORS=ninja',
        'SECURITYSESSIONID=186a6',
        '_=/usr/local/bin/react-native' ],
     killSignal: undefined },
  envPairs:
   [ 'TERM_PROGRAM=iTerm.app',
     'ANDROID_HOME=/Users/trunx/android/android-sdk',
     'TERM=xterm-256color',
     'SHELL=/bin/bash',
     'TMPDIR=/var/folders/b6/hp76wj2d7_l_wqc950blpnwh0000gq/T/',
     'GRADLE_HOME=/Users/trunx/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3',
     'GOBIN=/Users/trunx/go/package/bin',
     'Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.Hb729Z0B88/Render',
     'OLDPWD=/Users/trunx/git',
     'MAIL_USERNAME=disheng54@163.com',
     'http_proxy=http://127.0.0.1:8118',
     'USER=trunx',
     'CLASS_PATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/lib/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/bin:/Users/trunx/depot_tools:/Users/trunx/android/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/go/go1.8/bin:/Users/trunx/mongodb/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/android/android-ndk-r10e:/Library/tomcat9/bin:/Users/trunx/git/startools',
     'COMMAND_MODE=unix2003',
     'ANDROID_NDK_ROOT=/Users/trunx/android/android-ndk-r10e',
     'SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.s1fYpNNUR2/Listeners',
     '__CF_USER_TEXT_ENCODING=0x1F7:0x19:0x34',
     'XWALK_OS_ANDROID=1',
     'INTEL_MULTI_OS_ENGINE_HOME=/Applications/Intel/multi_os_engine',
     'MAIL_PASSWORD=duzitingyu',
     'PATH=/Users/trunx/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3/bin:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/bin:/Users/trunx/depot_tools:/Users/trunx/android/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/go/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/go/go1.8/bin:/Users/trunx/mongodb/bin:/Users/trunx/android/android-sdk/platform-tools:/Users/trunx/android/android-sdk/tools:/Users/trunx/android/android-ndk-r10e:/Library/tomcat9/bin:/Users/trunx/git/startools',
     'PWD=/Users/trunx/git/rn',
     'JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home',
     'LANG=zh_CN.UTF-8',
     'ITERM_PROFILE=Default',
     'XPC_FLAGS=0x0',
     'ANDROID_HVPROTO=ddm',
     'https_proxy=http://127.0.0.1:8118',
     'MONGODBROOT=/Users/trunx/mongodb',
     'XPC_SERVICE_NAME=0',
     'SHLVL=1',
     'HOME=/Users/trunx',
     'COLORFGBG=7;0',
     'GOROOT=/Users/trunx/go/go1.8',
     'ITERM_SESSION_ID=w0t0p0',
     'LOGNAME=trunx',
     'GOPATH=/Users/trunx/go/package',
     'FLASKY_ADMIN=MAIL_USERNAME',
     'DISPLAY=/private/tmp/com.apple.launchd.Td9Mh1vkcE/org.macosforge.xquartz:0',
     'NDK_ROOT=/Users/trunx/android/android-ndk-r10e',
     'GYP_GENERATORS=ninja',
     'SECURITYSESSIONID=186a6',
     '_=/usr/local/bin/react-native' ],
  stderr: null,
  stdout: null,
  pid: 93659,
  output: [ null, null, null ],
  signal: null,
  status: 1 }
Command `npm install --save --save-exact react-native` failed.
Test-Mac:rn trunx$
```

### 连接不上Genymotion

```
在电脑中查看该网址是否可以打开:https://localhost:8081/index.android.bundle?platform=android
```


text:
using System;
using System.Collections.Generic;
using Lucene.Net.Util;

namespace Lucene.Net.Index
{
    using System.IO;
    using CommandLineUtil = Lucene.Net.Util.CommandLineUtil;
    using Constants = Lucene.Net.Util.Constants;

    using Directory = Lucene.Net.Store.Directory;
    using FSDirectory = Lucene.Net.Store.FSDirectory;
    using InfoStream = Lucene.Net.Util.InfoStream;

    ///
    /// this is an easy-to-use tool that upgrades all segments of an index from previous Lucene versions
    /// to the current segment file format. It can be used from command line:
    ///

    ///  java -cp lucene-core.jar Lucene.Net.Index.IndexUpgrader [-delete-prior-commits] [-verbose] indexDir
    ///

    /// Alternatively this class can be instantiated and <seealso cref="#upgrade"/> invoked. It uses <seealso cref="UpgradeIndexMergePolicy"/>
    /// and triggers the upgrade via an forceMerge request to <seealso cref="IndexWriter"/>.
    ///
this tool keeps only the last commit in an index; for this
    /// reason, if the incoming index has more than one commit, the tool
    /// refuses to run by default. Specify {@code -delete-prior-commits}
    /// to override this, allowing the tool to delete all but the last commit.
    /// From Java code this can be enabled by passing {@code true} to
    /// <seealso cref="#IndexUpgrader(Directory,Version,StreamWriter,boolean)"/>.
    ///
Warning: this tool may reorder documents if the index was partially
    /// upgraded before execution (e.g., documents were added). If your application relies
    /// on "monotonicity" of doc IDs (which means that the order in which the documents
    /// were added to the index is preserved), do a full forceMerge instead.
    /// The <seealso cref="MergePolicy"/> set by <seealso cref="IndexWriterConfig"/> may also reorder
    /// documents.
    ///
    public sealed class IndexUpgrader
    {
        private static void PrintUsage()
        {
            Console.Error.WriteLine("Upgrades an index so all segments created with a previous Lucene version are rewritten.");
            Console.Error.WriteLine("Usage:");
            Console.Error.WriteLine("  java " + typeof(IndexUpgrader).Name + " [-delete-prior-commits] [-verbose] [-dir-impl X] indexDir");
            Console.Error.WriteLine("this tool keeps only the last commit in an index; for this");
            Console.Error.WriteLine("reason, if the incoming index has more than one commit, the tool");
            Console.Error.WriteLine("refuses to run by default. Specify -delete-prior-commits to override");
            Console.Error.WriteLine("this, allowing the tool to delete all but the last commit.");
            Console.Error.WriteLine("Specify a " + typeof(FSDirectory).Name + " implementation through the -dir-impl option to force its use. If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used.");
            Console.Error.WriteLine("WARNING: this tool may reorder document IDs!");
            Environment.Exit(1);
        }

        ///
        /// Main method to run {code IndexUpgrader} from the
        ///  command-line.
        ///
        /*public static void Main(string[] args)
        {
          ParseArgs(args).Upgrade();
        }*/

        public static IndexUpgrader ParseArgs(string[] args)
        {
            string path = null;
            bool deletePriorCommits = false;
            TextWriter @out = null;
            string dirImpl = null;
            int i = 0;
            while (i < args.Length)
            {
                string arg = args[i];
                if ("-delete-prior-commits".Equals(arg))
                {
                    deletePriorCommits = true;
                }
                else if ("-verbose".Equals(arg))
                {
                    @out = Console.Out;
                }
                else if ("-dir-impl".Equals(arg))
                {
                    if (i == args.Length - 1)
                    {
                        Console.WriteLine("ERROR: missing value for -dir-impl option");
                        Environment.Exit(1);
                    }
                    i++;
                    dirImpl = args[i];
                }
                else if (path == null)
                {
                    path = arg;
                }
                else
                {
                    PrintUsage();
                }
                i++;
            }
            if (path == null)
            {
                PrintUsage();
            }

            Directory dir = null;
            if (dirImpl == null)
            {
                dir = FSDirectory.Open(new DirectoryInfo(path));
            }
            else
            {
                dir = CommandLineUtil.NewFSDirectory(dirImpl, new DirectoryInfo(path));
            }
            return new IndexUpgrader(dir, LuceneVersion.LUCENE_CURRENT, @out, deletePriorCommits);
        }

        private readonly Directory Dir;
        private readonly IndexWriterConfig Iwc;
        private readonly bool DeletePriorCommits;

        ///
        /// Creates index upgrader on the given directory, using an <seealso cref="IndexWriter"/> using the given
        /// {@code matchVersion}. The tool refuses to upgrade indexes with multiple commit points.
        ///
        public IndexUpgrader(Directory dir, LuceneVersion matchVersion)
            : this(dir, new IndexWriterConfig(matchVersion, null), false)
        {
        }

        ///
        /// Creates index upgrader on the given directory, using an <seealso cref="IndexWriter"/> using the given
        /// {@code matchVersion}. You have the possibility to upgrade indexes with multiple commit points by removing
        /// all older ones. If {@code infoStream} is not {@code null}, all logging output will be sent to this stream.
        ///
        public IndexUpgrader(Directory dir, LuceneVersion matchVersion, TextWriter infoStream, bool deletePriorCommits)
            : this(dir, new IndexWriterConfig(matchVersion, null), deletePriorCommits)
        {
            if (null != infoStream)
            {
                this.Iwc.SetInfoStream(infoStream);
            }
        }

        ///
        /// Creates index upgrader on the given directory, using an <seealso cref="IndexWriter"/> using the given
        /// config. You have the possibility to upgrade indexes with multiple commit points by removing
        /// all older ones.
        ///
        public IndexUpgrader(Directory dir, IndexWriterConfig iwc, bool deletePriorCommits)
        {
            this.Dir = dir;
            this.Iwc = iwc;
            this.DeletePriorCommits = deletePriorCommits;
        }

        ///
        /// Perform the upgrade.
        public void Upgrade()
        {
            if (!DirectoryReader.IndexExists(Dir))
            {
                throw new IndexNotFoundException(Dir.ToString());
            }

            if (!DeletePriorCommits)
            {
                ICollection<IndexCommit> commits = DirectoryReader.ListCommits(Dir);
                if (commits.Count > 1)
                {
                    throw new System.ArgumentException("this tool was invoked to not delete prior commit points, but the following commits were found: " + commits);
                }
            }

            IndexWriterConfig c = (IndexWriterConfig)Iwc.Clone();
            c.SetMergePolicy(new UpgradeIndexMergePolicy(c.MergePolicy));
            c.SetIndexDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());

            IndexWriter w = new IndexWriter(Dir, c);
            try
            {
                InfoStream infoStream = c.InfoStream;
                if (infoStream.IsEnabled("IndexUpgrader"))
                {
                    infoStream.Message("IndexUpgrader", "Upgrading all pre-" + Constants.LUCENE_MAIN_VERSION + " segments of index directory '" + Dir + "' to version " + Constants.LUCENE_MAIN_VERSION + "...");
                }
                w.ForceMerge(1);
                if (infoStream.IsEnabled("IndexUpgrader"))
                {
                    infoStream.Message("IndexUpgrader", "All segments upgraded to version " + Constants.LUCENE_MAIN_VERSION);
                }
            }
            finally
            {
                w.Dispose();
            }
        }
    }
}


text:
package com.hubspot.singularity.s3downloader.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.hubspot.singularity.runner.base.configuration.SingularityRunnerBaseConfiguration;
import com.hubspot.singularity.runner.base.sentry.SingularityRunnerExceptionNotifier;
import com.hubspot.singularity.s3.base.ArtifactManager;
import com.hubspot.singularity.s3.base.config.SingularityS3Configuration;

public class ArtifactManagerProvider implements Provider<ArtifactManager> {

  private final Logger log;
  private final SingularityRunnerBaseConfiguration runnerBaseConfiguration;
  private final SingularityS3Configuration s3Configuration;
  private final SingularityRunnerExceptionNotifier exceptionNotifier;

  @Inject
  public ArtifactManagerProvider(SingularityRunnerBaseConfiguration runnerBaseConfiguration, SingularityS3Configuration s3Configuration, SingularityRunnerExceptionNotifier exceptionNotifier) {
    this.log = LoggerFactory.getLogger(ArtifactManager.class);
    this.runnerBaseConfiguration = runnerBaseConfiguration;
    this.s3Configuration = s3Configuration;
    this.exceptionNotifier = exceptionNotifier;
  }

  @Override
  public ArtifactManager get() {
    return new ArtifactManager(runnerBaseConfiguration, s3Configuration, log, exceptionNotifier);
  }

}