text:
namespace webcrypto {

namespace {

// This mock is used to initialize blink.
class InitOnce : public blink::Platform {
 public:
  InitOnce() {
    base::CommandLine::Init(0, nullptr);
    mojo::core::Init();
    blink::Platform::CreateMainThreadAndInitialize(this);
  }
  ~InitOnce() override {}

 private:
  base::SingleThreadTaskExecutor main_thread_task_executor_;
};

void EnsureInitialized() {
  static base::NoDestructor<InitOnce> init_once;
}

blink::WebCryptoAlgorithm CreateRsaHashedImportAlgorithm(
    blink::WebCryptoAlgorithmId id,
    blink::WebCryptoAlgorithmId hash_id) {
  DCHECK(blink::WebCryptoAlgorithm::IsHash(hash_id));
  return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
      id,
      new blink::WebCryptoRsaHashedImportParams(
          blink::WebCryptoAlgorithm::AdoptParamsAndCreate(hash_id, nullptr)));
}

blink::WebCryptoAlgorithm CreateEcImportAlgorithm(
    blink::WebCryptoAlgorithmId id,
    blink::WebCryptoNamedCurve named_curve) {
  return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
      id, new blink::WebCryptoEcKeyImportParams(named_curve));
}

}  // namespace

blink::WebCryptoKeyUsageMask GetCompatibleKeyUsages(
    blink::WebCryptoKeyFormat format) {
  // SPKI format implies import of a public key, whereas PKCS8 implies import
  // of a private key. Pick usages that are compatible with a signature
  // algorithm.
  return format == blink::kWebCryptoKeyFormatSpki
             ? blink::kWebCryptoKeyUsageVerify
             : blink::kWebCryptoKeyUsageSign;
}

void ImportEcKeyFromDerFuzzData(const uint8_t* data,
                                size_t size,
                                blink::WebCryptoKeyFormat format) {
  DCHECK(format == blink::kWebCryptoKeyFormatSpki ||
         format == blink::kWebCryptoKeyFormatPkcs8);
  EnsureInitialized();

  // There are 3 possible EC named curves. Fix this parameter. It shouldn't
  // matter based on the current implementation for PKCS8 or SPKI. But it
  // will have an impact when parsing JWK format.
  blink::WebCryptoNamedCurve curve = blink::kWebCryptoNamedCurveP384;

  // Always use ECDSA as the algorithm. Shouldn't make much difference for
  // non-JWK formats.
  blink::WebCryptoAlgorithmId algorithm_id = blink::kWebCryptoAlgorithmIdEcdsa;

  // Use key usages that are compatible with the chosen algorithm and key type.
  blink::WebCryptoKeyUsageMask usages = GetCompatibleKeyUsages(format);

  blink::WebCryptoKey key;
  webcrypto::Status status = webcrypto::ImportKey(
      format, base::make_span(data, size),
      CreateEcImportAlgorithm(algorithm_id, curve), true, usages, &key);

  // These errors imply a bad setup of parameters, and means ImportKey() may not
  // be testing the actual parsing.
  DCHECK_NE(status.error_details(),
            Status::ErrorUnsupportedImportKeyFormat().error_details());
  DCHECK_NE(status.error_details(),
            Status::ErrorCreateKeyBadUsages().error_details());
}

void ImportEcKeyFromRawFuzzData(const uint8_t* data, size_t size) {
  EnsureInitialized();

  // There are 3 possible EC named curves. Consume the first byte to decide on
  // the curve.
  uint8_t curve_index = 0;
  if (size > 0) {
    curve_index = data[0];
    data++;
    size--;
  }

  blink::WebCryptoNamedCurve curve;

  switch (curve_index % 3) {
    case 0:
      curve = blink::kWebCryptoNamedCurveP256;
      break;
    case 1:
      curve = blink::kWebCryptoNamedCurveP384;
      break;
    default:
      curve = blink::kWebCryptoNamedCurveP521;
      break;
  }

  // Always use ECDSA as the algorithm. Shouldn't make an difference for import.
  blink::WebCryptoAlgorithmId algorithm_id = blink::kWebCryptoAlgorithmIdEcdsa;

  // Use key usages that are compatible with the chosen algorithm and key type.
  blink::WebCryptoKeyUsageMask usages = blink::kWebCryptoKeyUsageVerify;

  blink::WebCryptoKey key;
  webcrypto::Status status = webcrypto::ImportKey(
      blink::kWebCryptoKeyFormatRaw, base::make_span(data, size),
      CreateEcImportAlgorithm(algorithm_id, curve), true, usages, &key);

  // These errors imply a bad setup of parameters, and means ImportKey() may not
  // be testing the actual parsing.
  DCHECK_NE(status.error_details(),
            Status::ErrorUnsupportedImportKeyFormat().error_details());
  DCHECK_NE(status.error_details(),
            Status::ErrorCreateKeyBadUsages().error_details());
}

void ImportRsaKeyFromDerFuzzData(const uint8_t* data,
                                 size_t size,
                                 blink::WebCryptoKeyFormat format) {
  DCHECK(format == blink::kWebCryptoKeyFormatSpki ||
         format == blink::kWebCryptoKeyFormatPkcs8);
  EnsureInitialized();

  // There are several possible hash functions. Fix this parameter. It shouldn't
  // matter based on the current implementation for PKCS8 or SPKI. But it
  // will have an impact when parsing JWK format.
  blink::WebCryptoAlgorithmId hash_id = blink::kWebCryptoAlgorithmIdSha256;

  // Always use RSA-SSA PKCS#1 as the algorithm. Shouldn't make much difference
  // for non-JWK formats.
  blink::WebCryptoAlgorithmId algorithm_id =
      blink::kWebCryptoAlgorithmIdRsaSsaPkcs1v1_5;

  // Use key usages that are compatible with the chosen algorithm and key type.
  blink::WebCryptoKeyUsageMask usages = GetCompatibleKeyUsages(format);

  blink::WebCryptoKey key;
  webcrypto::Status status = webcrypto::ImportKey(
      format, base::make_span(data, size),
      CreateRsaHashedImportAlgorithm(algorithm_id, hash_id), true, usages,
      &key);

  // These errors imply a bad setup of parameters, and means ImportKey() may not
  // be testing the actual parsing.
  DCHECK_NE(status.error_details(),
            Status::ErrorUnsupportedImportKeyFormat().error_details());
  DCHECK_NE(status.error_details(),
            Status::ErrorCreateKeyBadUsages().error_details());
}

}  // namespace webcrypto


text:
using namespace llvm;

#define DEBUG_TYPE "systemz-long-branch"

STATISTIC(LongBranches, "Number of long branches.");

namespace {
// Represents positional information about a basic block.
struct MBBInfo {
  // The address that we currently assume the block has.
  uint64_t Address;

  // The size of the block in bytes, excluding terminators.
  // This value never changes.
  uint64_t Size;

  // The minimum alignment of the block, as a log2 value.
  // This value never changes.
  unsigned Alignment;

  // The number of terminators in this block.  This value never changes.
  unsigned NumTerminators;

  MBBInfo()
    : Address(0), Size(0), Alignment(0), NumTerminators(0) {}
};

// Represents the state of a block terminator.
struct TerminatorInfo {
  // If this terminator is a relaxable branch, this points to the branch
  // instruction, otherwise it is null.
  MachineInstr *Branch;

  // The address that we currently assume the terminator has.
  uint64_t Address;

  // The current size of the terminator in bytes.
  uint64_t Size;

  // If Branch is nonnull, this is the number of the target block,
  // otherwise it is unused.
  unsigned TargetBlock;

  // If Branch is nonnull, this is the length of the longest relaxed form,
  // otherwise it is zero.
  unsigned ExtraRelaxSize;

  TerminatorInfo() : Branch(nullptr), Size(0), TargetBlock(0),
                     ExtraRelaxSize(0) {}
};

// Used to keep track of the current position while iterating over the blocks.
struct BlockPosition {
  // The address that we assume this position has.
  uint64_t Address;

  // The number of low bits in Address that are known to be the same
  // as the runtime address.
  unsigned KnownBits;

  BlockPosition(unsigned InitialAlignment)
    : Address(0), KnownBits(InitialAlignment) {}
};

class SystemZLongBranch : public MachineFunctionPass {
public:
  static char ID;
  SystemZLongBranch(const SystemZTargetMachine &tm)
    : MachineFunctionPass(ID), TII(nullptr) {}

  const char *getPassName() const override {
    return "SystemZ Long Branch";
  }

  bool runOnMachineFunction(MachineFunction &F) override;

private:
  void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);
  void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,
                      bool AssumeRelaxed);
  TerminatorInfo describeTerminator(MachineInstr *MI);
  uint64_t initMBBInfo();
  bool mustRelaxBranch(const TerminatorInfo &Terminator, uint64_t Address);
  bool mustRelaxABranch();
  void setWorstCaseAddresses();
  void splitBranchOnCount(MachineInstr *MI, unsigned AddOpcode);
  void splitCompareBranch(MachineInstr *MI, unsigned CompareOpcode);
  void relaxBranch(TerminatorInfo &Terminator);
  void relaxBranches();

  const SystemZInstrInfo *TII;
  MachineFunction *MF;
  SmallVector<MBBInfo, 16> MBBs;
  SmallVector<TerminatorInfo, 16> Terminators;
};

char SystemZLongBranch::ID = 0;

const uint64_t MaxBackwardRange = 0x10000;
const uint64_t MaxForwardRange = 0xfffe;
} // end anonymous namespace

FunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) {
  return new SystemZLongBranch(TM);
}

// Position describes the state immediately before Block.  Update Block
// accordingly and move Position to the end of the block's non-terminator
// instructions.
void SystemZLongBranch::skipNonTerminators(BlockPosition &Position,
                                           MBBInfo &Block) {
  if (Block.Alignment > Position.KnownBits) {
    // When calculating the address of Block, we need to conservatively
    // assume that Block had the worst possible misalignment.
    Position.Address += ((uint64_t(1) << Block.Alignment) -
                         (uint64_t(1) << Position.KnownBits));
    Position.KnownBits = Block.Alignment;
  }

  // Align the addresses.
  uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1;
  Position.Address = (Position.Address + AlignMask) & ~AlignMask;

  // Record the block's position.
  Block.Address = Position.Address;

  // Move past the non-terminators in the block.
  Position.Address += Block.Size;
}

// Position describes the state immediately before Terminator.
// Update Terminator accordingly and move Position past it.
// Assume that Terminator will be relaxed if AssumeRelaxed.
void SystemZLongBranch::skipTerminator(BlockPosition &Position,
                                       TerminatorInfo &Terminator,
                                       bool AssumeRelaxed) {
  Terminator.Address = Position.Address;
  Position.Address += Terminator.Size;
  if (AssumeRelaxed)
    Position.Address += Terminator.ExtraRelaxSize;
}

// Return a description of terminator instruction MI.
TerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) {
  TerminatorInfo Terminator;
  Terminator.Size = TII->getInstSizeInBytes(MI);
  if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) {
    switch (MI->getOpcode()) {
    case SystemZ::J:
      // Relaxes to JG, which is 2 bytes longer.
      Terminator.ExtraRelaxSize = 2;
      break;
    case SystemZ::BRC:
      // Relaxes to BRCL, which is 2 bytes longer.
      Terminator.ExtraRelaxSize = 2;
      break;
    case SystemZ::BRCT:
    case SystemZ::BRCTG:
      // Relaxes to A(G)HI and BRCL, which is 6 bytes longer.
      Terminator.ExtraRelaxSize = 6;
      break;
    case SystemZ::CRJ:
    case SystemZ::CLRJ:
      // Relaxes to a C(L)R/BRCL sequence, which is 2 bytes longer.
      Terminator.ExtraRelaxSize = 2;
      break;
    case SystemZ::CGRJ:
    case SystemZ::CLGRJ:
      // Relaxes to a C(L)GR/BRCL sequence, which is 4 bytes longer.
      Terminator.ExtraRelaxSize = 4;
      break;
    case SystemZ::CIJ:
    case SystemZ::CGIJ:
      // Relaxes to a C(G)HI/BRCL sequence, which is 4 bytes longer.
      Terminator.ExtraRelaxSize = 4;
      break;
    case SystemZ::CLIJ:
    case SystemZ::CLGIJ:
      // Relaxes to a CL(G)FI/BRCL sequence, which is 6 bytes longer.
      Terminator.ExtraRelaxSize = 6;
      break;
    default:
      llvm_unreachable("Unrecognized branch instruction");
    }
    Terminator.Branch = MI;
    Terminator.TargetBlock =
      TII->getBranchInfo(MI).Target->getMBB()->getNumber();
  }
  return Terminator;
}

// Fill MBBs and Terminators, setting the addresses on the assumption
// that no branches need relaxation.  Return the size of the function under
// this assumption.
uint64_t SystemZLongBranch::initMBBInfo() {
  MF->RenumberBlocks();
  unsigned NumBlocks = MF->size();

  MBBs.clear();
  MBBs.resize(NumBlocks);

  Terminators.clear();
  Terminators.reserve(NumBlocks);

  BlockPosition Position(MF->getAlignment());
  for (unsigned I = 0; I < NumBlocks; ++I) {
    MachineBasicBlock *MBB = MF->getBlockNumbered(I);
    MBBInfo &Block = MBBs[I];

    // Record the alignment, for quick access.
    Block.Alignment = MBB->getAlignment();

    // Calculate the size of the fixed part of the block.
    MachineBasicBlock::iterator MI = MBB->begin();
    MachineBasicBlock::iterator End = MBB->end();
    while (MI != End && !MI->isTerminator()) {
      Block.Size += TII->getInstSizeInBytes(MI);
      ++MI;
    }
    skipNonTerminators(Position, Block);

    // Add the terminators.
    while (MI != End) {
      if (!MI->isDebugValue()) {
        assert(MI->isTerminator() && "Terminator followed by non-terminator");
        Terminators.push_back(describeTerminator(MI));
        skipTerminator(Position, Terminators.back(), false);
        ++Block.NumTerminators;
      }
      ++MI;
    }
  }

  return Position.Address;
}

// Return true if, under current assumptions, Terminator would need to be
// relaxed if it were placed at address Address.
bool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator,
                                        uint64_t Address) {
  if (!Terminator.Branch)
    return false;

  const MBBInfo &Target = MBBs[Terminator.TargetBlock];
  if (Address >= Target.Address) {
    if (Address - Target.Address <= MaxBackwardRange)
      return false;
  } else {
    if (Target.Address - Address <= MaxForwardRange)
      return false;
  }

  return true;
}

// Return true if, under current assumptions, any terminator needs
// to be relaxed.
bool SystemZLongBranch::mustRelaxABranch() {
  for (auto &Terminator : Terminators)
    if (mustRelaxBranch(Terminator, Terminator.Address))
      return true;
  return false;
}

// Set the address of each block on the assumption that all branches
// must be long.
void SystemZLongBranch::setWorstCaseAddresses() {
  SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
  BlockPosition Position(MF->getAlignment());
  for (auto &Block : MBBs) {
    skipNonTerminators(Position, Block);
    for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) {
      skipTerminator(Position, *TI, true);
      ++TI;
    }
  }
}

// Split BRANCH ON COUNT MI into the addition given by AddOpcode followed
// by a BRCL on the result.
void SystemZLongBranch::splitBranchOnCount(MachineInstr *MI,
                                           unsigned AddOpcode) {
  MachineBasicBlock *MBB = MI->getParent();
  DebugLoc DL = MI->getDebugLoc();
  BuildMI(*MBB, MI, DL, TII->get(AddOpcode))
    .addOperand(MI->getOperand(0))
    .addOperand(MI->getOperand(1))
    .addImm(-1);
  MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
    .addImm(SystemZ::CCMASK_ICMP)
    .addImm(SystemZ::CCMASK_CMP_NE)
    .addOperand(MI->getOperand(2));
  // The implicit use of CC is a killing use.
  BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo());
  MI->eraseFromParent();
}

// Split MI into the comparison given by CompareOpcode followed
// a BRCL on the result.
void SystemZLongBranch::splitCompareBranch(MachineInstr *MI,
                                           unsigned CompareOpcode) {
  MachineBasicBlock *MBB = MI->getParent();
  DebugLoc DL = MI->getDebugLoc();
  BuildMI(*MBB, MI, DL, TII->get(CompareOpcode))
    .addOperand(MI->getOperand(0))
    .addOperand(MI->getOperand(1));
  MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
    .addImm(SystemZ::CCMASK_ICMP)
    .addOperand(MI->getOperand(2))
    .addOperand(MI->getOperand(3));
  // The implicit use of CC is a killing use.
  BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo());
  MI->eraseFromParent();
}

// Relax the branch described by Terminator.
void SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) {
  MachineInstr *Branch = Terminator.Branch;
  switch (Branch->getOpcode()) {
  case SystemZ::J:
    Branch->setDesc(TII->get(SystemZ::JG));
    break;
  case SystemZ::BRC:
    Branch->setDesc(TII->get(SystemZ::BRCL));
    break;
  case SystemZ::BRCT:
    splitBranchOnCount(Branch, SystemZ::AHI);
    break;
  case SystemZ::BRCTG:
    splitBranchOnCount(Branch, SystemZ::AGHI);
    break;
  case SystemZ::CRJ:
    splitCompareBranch(Branch, SystemZ::CR);
    break;
  case SystemZ::CGRJ:
    splitCompareBranch(Branch, SystemZ::CGR);
    break;
  case SystemZ::CIJ:
    splitCompareBranch(Branch, SystemZ::CHI);
    break;
  case SystemZ::CGIJ:
    splitCompareBranch(Branch, SystemZ::CGHI);
    break;
  case SystemZ::CLRJ:
    splitCompareBranch(Branch, SystemZ::CLR);
    break;
  case SystemZ::CLGRJ:
    splitCompareBranch(Branch, SystemZ::CLGR);
    break;
  case SystemZ::CLIJ:
    splitCompareBranch(Branch, SystemZ::CLFI);
    break;
  case SystemZ::CLGIJ:
    splitCompareBranch(Branch, SystemZ::CLGFI);
    break;
  default:
    llvm_unreachable("Unrecognized branch");
  }

  Terminator.Size += Terminator.ExtraRelaxSize;
  Terminator.ExtraRelaxSize = 0;
  Terminator.Branch = nullptr;

  ++LongBranches;
}

// Run a shortening pass and relax any branches that need to be relaxed.
void SystemZLongBranch::relaxBranches() {
  SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
  BlockPosition Position(MF->getAlignment());
  for (auto &Block : MBBs) {
    skipNonTerminators(Position, Block);
    for (unsigned BTI = 0, BTE = Block.NumTerminators; BTI != BTE; ++BTI) {
      assert(Position.Address <= TI->Address &&
             "Addresses shouldn't go forwards");
      if (mustRelaxBranch(*TI, Position.Address))
        relaxBranch(*TI);
      skipTerminator(Position, *TI, false);
      ++TI;
    }
  }
}

bool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) {
  TII = static_cast<const SystemZInstrInfo *>(F.getSubtarget().getInstrInfo());
  MF = &F;
  uint64_t Size = initMBBInfo();
  if (Size <= MaxForwardRange || !mustRelaxABranch())
    return false;

  setWorstCaseAddresses();
  relaxBranches();
  return true;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:materialdesign="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >
	</LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="84dp"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="Categoría" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image_view_product"
            android:layout_width="50dp"
            android:layout_height="104dp"
            android:layout_weight="0.06"
            android:src="@drawable/abc_ic_clear" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="84dp"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="Descrición" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="84dp"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="Marca" />
    </LinearLayout>
     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

         <ImageView
             android:id="@+id/ImageView01"
             android:layout_width="50dp"
             android:layout_height="104dp"
             android:layout_weight="0.06"
             android:src="@drawable/abc_ic_clear" />

        <TextView
            android:layout_width="84dp"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="Prezo" />

    </LinearLayout>

     <ListView
         android:id="@+id/listView1"
         android:layout_width="match_parent"
         android:layout_height="104dp" >
     </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="horizontal" >

        <com.gc.materialdesign.views.ButtonRectangle
            android:id="@+id/cancel_new_product"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@color/verde_oscuro"
            android:text="Compartir"
            materialdesign:animate="true" >

        </com.gc.materialdesign.views.ButtonRectangle>

        <com.gc.materialdesign.views.ButtonRectangle
            android:id="@+id/add_new_product"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@color/verde_oscuro"
            android:text="Engadir"
            materialdesign:animate="true" />
    </LinearLayout>

</LinearLayout>


text:
<?php

namespace LastCall\Crawler\Test\Handler\Discovery;

use LastCall\Crawler\Handler\Discovery\ScriptDiscoverer;
use LastCall\Crawler\Uri\NormalizerInterface;

class ScriptDiscovererTest extends AbstractDiscovererTest
{
    public function getDiscoveryTests()
    {
        return [
            ['', ['http://google.com/foo.js'], 'script'],
            ['', [], null],
            ['', [], null],
            ['', ['http://google.com/foo.css'], 'script'],
        ];
    }

    public function getDiscoverer(NormalizerInterface $normalizer)
    {
        return new ScriptDiscoverer($normalizer);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsActivity"
    android:showDividers="middle">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:id="@+id/myactionbar"
        android:background="@color/black">
        <LinearLayout
            android:id="@+id/myactionbartitle"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:orientation="horizontal"
            android:gravity="center_vertical|left"
            android:background="@color/black"
            android:clickable="true">
            <ImageView
                android:id="@+id/ab_drawer_icon"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:background="@color/black"
                android:scaleY="0.6"/>
            <ImageView
                android:id="@+id/ab_app_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:background="@drawable/ic_launcher"/>
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="@string/app_name"
                android:textColor="@color/white"
                android:textSize="18dp"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <gopherdoc.buttercoin.trader.ListItemSettings
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="80"
            android:id="@+id/settings_primarykey"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="20"
            android:text="@string/QR"
            android:id="@+id/settings_btn_primarykey"
            android:onClick="OnSettingsQRClick"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <gopherdoc.buttercoin.trader.ListItemSettings
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="80"
            android:id="@+id/settings_secretkey"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="20"
            android:text="@string/QR"
            android:id="@+id/settings_btn_secretkey"
            android:onClick="OnSettingsQRClick"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="80"
            android:text="Refresh Interval (sec)"
            android:layout_gravity="center"
            android:textSize="28sp" />
        <NumberPicker
            android:id="@+id/refreshPicker"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:orientation="vertical"/>
     </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="80"
            android:text="Depth Range (%)"
            android:layout_gravity="center"
            android:textSize="28sp" />
        <NumberPicker
            android:id="@+id/depthRange"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:orientation="vertical"/>
    </LinearLayout>

</LinearLayout>


text:
import operator
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType

class TopicQuerySet(models.query.QuerySet):

    def published(self):
        return self.filter(deleted=False)

class TopicManager(models.Manager):

    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
            return TopicQuerySet(self.model, using=self._db)

    def search(self, search_terms):
        from libs.search import normalize
        terms = normalize(search_terms)
        q_objects = []

        for term in terms:
            q_objects.append(models.Q(title__icontains=term))
            q_objects.append(models.Q(tags__icontains=term))

        # Start with a bare QuerySet
        qs = self.get_query_set()

        # Use operator's or_ to string together all of your Q objects.
        return qs.filter(reduce(operator.or_, q_objects))


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2020 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="@color/icon_tint_gray">
    <group
        android:translateX="3"
        android:translateY="3">
        <path
            android:fillColor="#000"
            android:pathData="M14,10H12V14H14V10ZM10,4H8V14H10V4ZM16,0H2C0.9,0 0,0.9 0,2V16C0,17.1 0.9,18 2,18H16C17.1,18 18,17.1 18,16V2C18,0.9 17.1,0 16,0ZM16,16H2V2H16V16ZM6,7H4V14H6V7Z" />
    </group>
</vector>


text:
package com.gemstone.gemfire.distributed;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

import com.gemstone.gemfire.CancelException;
import com.gemstone.gemfire.SystemConnectException;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache30.CacheSerializableRunnable;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionException;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystemJUnitTest;
import com.gemstone.gemfire.distributed.internal.SerialDistributionMessage;
import com.gemstone.gemfire.distributed.internal.SizeableRunnable;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.distributed.internal.membership.jgroup.JGroupMembershipManager;
import com.gemstone.gemfire.distributed.internal.membership.jgroup.MembershipManagerHelper;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.org.jgroups.protocols.pbcast.ClientGmsImpl;
import com.gemstone.org.jgroups.util.ExternalStrings;
import dunit.DistributedTestCase;
import dunit.Host;
import dunit.VM;

/**
 * Tests the functionality of the {@link DistributedSystem} class.
 *
 * @see InternalDistributedSystemJUnitTest
 *
 * @author David Whitlock
 */
public class DistributedSystemTest extends DistributedTestCase {

  public DistributedSystemTest(String name) {
    super(name);
  }

  public void setUp() throws Exception {
    super.setUp();
    disconnectAllFromDS();
  }

  ////////  Test methods

  /**
   * ensure that waitForMemberDeparture correctly flushes the serial message queue for
   * the given member
   */
  public void testWaitForDeparture() throws Exception {
    disconnectAllFromDS();
    Properties p = getDistributedSystemProperties();
    p.put(DistributionConfig.LOCATORS_NAME, "");
    p.put(DistributionConfig.MCAST_PORT_NAME, ""+AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS));
    p.put(DistributionConfig.DISABLE_TCP_NAME, "true");
    InternalDistributedSystem ds = (InternalDistributedSystem)DistributedSystem.connect(p);
    try {
      // construct a member ID that will represent a departed member
      InternalDistributedMember mbr = new InternalDistributedMember("localhost", 12345, "", "");
      final DistributionManager mgr = (DistributionManager)ds.getDistributionManager();
      // schedule a message in order to create a queue for the fake member
      final FakeMessage msg = new FakeMessage(null);
      mgr.getExecutor(DistributionManager.SERIAL_EXECUTOR, mbr).execute(new SizeableRunnable(100) {
        public void run() {
          msg.doAction(mgr, false);
        }
        public String toString() {
          return "Processing fake message";
        }
      });
      try {
        assertTrue("expected the serial queue to be flushed", mgr.getMembershipManager().waitForDeparture(mbr));
      } catch (InterruptedException e) {
        fail("interrupted");
      } catch (TimeoutException e) {
        fail("timed out - increase this test's member-timeout setting");
      }
    } finally {
      ds.disconnect();
    }
  }

  static class FakeMessage extends SerialDistributionMessage {
    volatile boolean[] blocked;
    volatile boolean processed;

    FakeMessage(boolean[] blocked) {
      this.blocked = blocked;
    }
    public void doAction(DistributionManager dm, boolean block) {
      processed = true;
      if (block) {
        synchronized(blocked) {
          blocked[0] = true;
          blocked.notify();
          try {
            blocked.wait(60000);
          } catch (InterruptedException e) {}
        }
      }
    }
    public int getDSFID() {
      return 0; // never serialized
    }
    protected void process(DistributionManager dm) {
      // this is never called
    }
    public String toString() {
      return "FakeMessage(blocking="+(blocked!=null)+")";
    }
  }

  /**
   * Tests that we can get a DistributedSystem with the same
   * configuration twice.
   */
  public void testGetSameSystemTwice() {
    Properties config = new Properties();

//     int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
//     config.setProperty("mcast-port", String.valueOf(unusedPort));
    // a loner is all this test needs
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");
    // set a flow-control property for the test (bug 37562)
    config.setProperty("mcast-flow-control", "3000000,0.20,3000");

    DistributedSystem system1 = DistributedSystem.connect(config);
    DistributedSystem system2 = DistributedSystem.connect(config);
    assertSame(system1, system2);
    system1.disconnect();
  }

  /**
   * Tests that getting a DistributedSystem with a
   * different configuration after one has already been obtained
   * throws an exception.
   */
  public void testGetDifferentSystem() {
    Properties config = new Properties();

//     int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
//     config.setProperty("mcast-port", String.valueOf(unusedPort));
    // a loner is all this test needs
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");
    config.setProperty("mcast-flow-control", "3000000,0.20,3000");

    DistributedSystem system1 = DistributedSystem.connect(config);
    config.setProperty("mcast-address", "224.0.0.1");
    try {
      DistributedSystem.connect(config);
      if (System.getProperty("gemfire.mcast-address") == null) {
        fail("Should have thrown an IllegalStateException");
      }
    }
    catch (IllegalStateException ex) {
      // pass...
    }
    finally {
      system1.disconnect();
    }
  }

  /**
   * Tests getting a system with a different configuration after
   * another system has been closed.
   */
  public void testGetDifferentSystemAfterClose() {
    Properties config = new Properties();

//     int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
//     config.setProperty("mcast-port", String.valueOf(unusedPort));
    // a loner is all this test needs
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");

    DistributedSystem system1 = DistributedSystem.connect(config);
    system1.disconnect();
    int time = DistributionConfig.DEFAULT_ACK_WAIT_THRESHOLD + 17;
    config.put(DistributionConfig.ACK_WAIT_THRESHOLD_NAME,
               String.valueOf(time));
    DistributedSystem system2 = DistributedSystem.connect(config);
    system2.disconnect();
  }

  public void testGetProperties() {
    Properties config = new Properties();

//     int unusedPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
//     config.setProperty("mcast-port", String.valueOf(unusedPort));
    // a loner is all this test needs
    int unusedPort = 0;
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");

    DistributedSystem system1 = DistributedSystem.connect(config);

    assertTrue(config != system1.getProperties());
    assertEquals(unusedPort, Integer.parseInt(system1.getProperties().getProperty("mcast-port")));

    system1.disconnect();

    assertTrue(config != system1.getProperties());
    assertEquals(unusedPort, Integer.parseInt(system1.getProperties().getProperty("mcast-port")));
  }

  public void testIsolatedDistributedSystem() throws Exception {
    Properties config = new Properties();
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");
    system = (InternalDistributedSystem)DistributedSystem.connect(config);
    try {
      // make sure isolated distributed system can still create a cache and region
      Cache cache = CacheFactory.create(getSystem());
      Region r = cache.createRegion(getUniqueName(), new AttributesFactory().create());
      r.put("test", "value");
      assertEquals("value", r.get("test"));
    } finally {
      getSystem().disconnect();
    }
  }

  /** test the ability to set the port used to listen for tcp/ip connections */
  public void testSpecificTcpPort() throws Exception {
    Properties config = new Properties();
    int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
    int tcpPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    config.setProperty("mcast-port", String.valueOf(mcastPort));
    config.setProperty("locators", "");
    config.setProperty("tcp-port", String.valueOf(tcpPort));
    system = (InternalDistributedSystem)DistributedSystem.connect(config);
    DistributionManager dm = (DistributionManager)system.getDistributionManager();
    JGroupMembershipManager mgr = (JGroupMembershipManager)dm.getMembershipManager();
    int actualPort = mgr.getDirectChannelPort();
    system.disconnect();
    assertEquals(tcpPort, actualPort);
  }

  /** test that loopback cannot be used as a bind address when a locator w/o a bind address is being used */
  public void DISABLED_BUG_51467_testLoopbackNotAllowed() throws Exception {
    InetAddress loopback = null;
    for (Enumeration<NetworkInterface> it = NetworkInterface.getNetworkInterfaces(); it.hasMoreElements(); ) {
      NetworkInterface nif = it.nextElement();
      for (Enumeration<InetAddress> ait = nif.getInetAddresses(); ait.hasMoreElements(); ) {
        InetAddress a = ait.nextElement();
        if (a.isLoopbackAddress()) {
          loopback = a;
          // continue searching for IPv4 address
          if (!(a instanceof Inet6Address)) {
            break;
          }
        }
      }
    }
    if (loopback != null) {
      Properties config = new Properties();
      config.put(DistributionConfig.MCAST_PORT_NAME, "0");
      String locators = InetAddress.getLocalHost().getHostName()+":"+getDUnitLocatorPort();
      config.put(DistributionConfig.LOCATORS_NAME, locators);
      config.setProperty(DistributionConfig.BIND_ADDRESS_NAME, loopback.getHostAddress());
      getLogWriter().info("attempting to connect with " + loopback +" and locators=" + locators);
      try {
        system = (InternalDistributedSystem)DistributedSystem.connect(config);
        system.disconnect();
        fail("expected a configuration exception disallowing use of loopback address");
      } catch (DistributionException e) {
        // expected
      }
    }
  }

  /** test jgroups handling of a request to retransmit a large message */
  public void testBug43652() throws Exception {
    DistributedSystem sys = getSystem();
    JGroupMembershipManager mgr = MembershipManagerHelper.getMembershipManager(sys);
    boolean result = mgr.getNakAck().testRetransmitLargeMessage(new byte[75000]);
    assertTrue(result);
    sys.disconnect();
  }

  public void testUDPPortRange() throws Exception {
    Properties config = new Properties();
    int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
    int unicastPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    config.setProperty("mcast-port", String.valueOf(mcastPort));
    config.setProperty("locators", "");
    // Minimum 3 ports required in range for UDP, FD_SOCK and TcpConduit.
    config.setProperty(DistributionConfig.MEMBERSHIP_PORT_RANGE_NAME,
        ""+unicastPort+"-"+(unicastPort+2));
    system = (InternalDistributedSystem)DistributedSystem.connect(config);
    DistributionManager dm = (DistributionManager)system.getDistributionManager();
    InternalDistributedMember idm = dm.getDistributionManagerId();
    system.disconnect();
    assertTrue(unicastPort <= idm.getPort() && idm.getPort() <= unicastPort+2);
    assertTrue(unicastPort <= idm.getPort() && idm.getDirectChannelPort() <= unicastPort+2);
  }

  public void testMembershipPortRange() throws Exception {
    Properties config = new Properties();
    int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
    int unicastPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    config.setProperty("mcast-port", String.valueOf(mcastPort));
    config.setProperty("locators", "");
    config.setProperty(DistributionConfig.MEMBERSHIP_PORT_RANGE_NAME,
        ""+unicastPort+"-"+(unicastPort+1));
    try {
      system = (InternalDistributedSystem)DistributedSystem.connect(config);
    } catch (Exception e) {
      assertTrue("The exception must be IllegalArgumentException", e instanceof IllegalArgumentException);
      return;
    }
    fail("IllegalArgumentException must have been thrown by DistributedSystem.connect() as port-range: "
        + config.getProperty(DistributionConfig.MEMBERSHIP_PORT_RANGE_NAME)
        + " must have at least 3 values in range");
  }

  public void testMembershipPortRangeWithExactThreeValues() throws Exception {
    Properties config = new Properties();
    int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
    config.setProperty("mcast-port", String.valueOf(mcastPort));
    config.setProperty("locators", "");
    config.setProperty(DistributionConfig.MEMBERSHIP_PORT_RANGE_NAME, ""
        + (DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1] - 2) + "-"
        + (DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1]));
    system = (InternalDistributedSystem)DistributedSystem.connect(config);
    Cache cache = CacheFactory.create(system);
    cache.addCacheServer();
    DistributionManager dm = (DistributionManager) system.getDistributionManager();
    InternalDistributedMember idm = dm.getDistributionManagerId();
    system.disconnect();
    assertTrue(idm.getPort() <= DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1]);
    assertTrue(idm.getPort() >= DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[0]);
    assertTrue(idm.getDirectChannelPort() <= DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1]);
    assertTrue(idm.getDirectChannelPort() >= DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[0]);
  }

  public void testConflictingUDPPort() throws Exception {
    final Properties config = new Properties();
    final int mcastPort = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
    final int unicastPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    config.setProperty("mcast-port", String.valueOf(mcastPort));
    config.setProperty("locators", "");
    config.setProperty(DistributionConfig.MEMBERSHIP_PORT_RANGE_NAME,
        ""+unicastPort+"-"+(unicastPort+2));
    system = (InternalDistributedSystem)DistributedSystem.connect(config);
    DistributionManager dm = (DistributionManager)system.getDistributionManager();
    InternalDistributedMember idm = dm.getDistributionManagerId();
    VM vm = Host.getHost(0).getVM(1);
    vm.invoke(new CacheSerializableRunnable("start conflicting system") {
      public void run2() {
        try {
          DistributedSystem system = DistributedSystem.connect(config);
          system.disconnect();
        } catch (SystemConnectException e) {
          return; //
        }
        fail("expected a SystemConnectException but didn't get one");
      }
    });
    system.disconnect();
  }

  /**
   * Tests that configuring a distributed system with a cache-xml-file
   * of "" does not initialize a cache.  See bug 32254.
   *
   * @since 4.0
   */
  public void testEmptyCacheXmlFile() throws Exception {
    Properties config = new Properties();

//     int unusedPort =
//       AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS);
//     config.setProperty("mcast-port", String.valueOf(unusedPort));
    // a loner is all this test needs
    config.setProperty("mcast-port", "0");
    config.setProperty("locators", "");
    config.setProperty(DistributionConfig.CACHE_XML_FILE_NAME, "");

    DistributedSystem sys = DistributedSystem.connect(config);

    try {
      try {
        CacheFactory.getInstance(sys);
        fail("Should have thrown a CancelException");
      }
      catch (CancelException expected) {
      }
      // now make sure we can create the cache
      CacheFactory.create(sys);

    } finally {
      sys.disconnect();
    }
  }

  static volatile String problem;

  public void testInterruptedWhileConnecting() throws Exception {
    Runnable r = new Runnable() {
      public void run() {
        ClientGmsImpl.SLOW_JOIN_LOCK = new Object();
        ClientGmsImpl.SLOW_JOIN = true;
        try {
          assertTrue("should be disconnected at this point", InternalDistributedSystem.getConnectedInstance() == null);
          getSystem();
          problem = "a connection to the distributed system was established but it should have failed";
        } catch (SystemConnectException e) {
          if (!e.getMessage().endsWith(ExternalStrings.ClientGmsImpl_JOIN_INTERRUPTED.getRawText())) {
            problem = "got a system connect exception but it was for the wrong reason";
            getLogWriter().info("wrong exception thrown: '" + e.getMessage() + "' (wanted '"+
              ExternalStrings.ClientGmsImpl_JOIN_INTERRUPTED.getRawText()+"')", e);
          }
        } finally {
          ClientGmsImpl.SLOW_JOIN = false;
          ClientGmsImpl.SLOW_JOIN_LOCK = null;
        }
      }
    };
    Thread connectThread = new Thread(r, "testInterruptedWhileConnecting connect thread");
    ClientGmsImpl.SLOW_JOIN = false;
    connectThread.start();
    while (ClientGmsImpl.SLOW_JOIN == false) {
      pause(1000);
    }
    pause(5000);
    connectThread.interrupt();
    connectThread.join(60000);
    getLogWriter().info("done waiting for connectThread.  Thread is " +
      (connectThread.isAlive()? "still alive" : "stopped"));
    if (ClientGmsImpl.SLOW_JOIN) {
      problem = "failed to either connect or get an exception - one of these should have happened";
      dumpMyThreads(getLogWriter());
    }
    if (problem != null) {
      fail(problem);
    }
  }

}


text:
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const Foo = {template: '
foo
'}
const Bar = {template: '
bar
'}

const router = new VueRouter({
    mode: 'history',
    base: '/',
    routes: [
        {path: '/foo', component: Foo},
        {path: '/bar', component: Bar}
    ]
});

new Vue({
    router
}).$mount('#app');


text:
package de.fau.amos.virtualledger.android.views.shared.transactionList;

import java.util.Comparator;

/**
 * Created by sebastian on 05.06.17.
 */

public class TransactionsComparator implements Comparator<Transaction> {
    @Override
    public int compare(Transaction transaction, Transaction t1) {
        return t1.booking().getDate().compareTo(transaction.booking().getDate());
    }
}


text:
package org.codegist.crest.serializer.jaxb;

import org.codegist.common.reflect.Types;
import org.codegist.crest.CRestConfig;

import javax.xml.bind.JAXBException;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author laurent.gilles@codegist.org
 */
class TypeCachingJaxb implements Jaxb {

    private final CRestConfig crestConfig;
    private final ConcurrentMap<Set<Class<?>>, Jaxb> cache = new ConcurrentHashMap<Set<Class<?>>, Jaxb>();
    private final Class<?> source;

    TypeCachingJaxb(CRestConfig crestConfig, Class<?> source) {
        this.crestConfig = crestConfig;
        this.source = source;
    }

    public <T> void marshal(T object, OutputStream out, Charset charset) throws Exception {
        Jaxb jaxb;
        if(object instanceof Classes) {
            Set<Class<?>> classes = ((Classes) object).getClasses();
            jaxb = get(classes);
        }else{
            jaxb = get(Collections.<Class<?>>singleton(object.getClass()));
        }
        jaxb.<T>marshal(object, out, charset);
    }

    public <T> T unmarshal(Class<T> type, Type genericType, Reader reader) throws Exception {
        Set<Class<?>> classes = Types.getActors(genericType);
        classes.add(type);

        Jaxb jaxb = get(classes);
        return jaxb.<T>unmarshal(type, genericType, reader);
    }

    private Jaxb get(Set<Class<?>> key) throws JAXBException {
        Jaxb jaxb = cache.get(key);
        if(jaxb == null) {
            jaxb = JaxbFactory.create(crestConfig, source, key.toArray(new Class<?>[key.size()]));
            Jaxb previousJaxb = cache.putIfAbsent(key, jaxb);
            jaxb = previousJaxb != null ? previousJaxb : jaxb;
        }
        return jaxb;
    }

}


text:
import React from "react"
import './index.scss'

export default ({ data }) => {
  const post = data.markdownRemark;
  return (

            {post.frontmatter.title}

{post.frontmatter.date}

  )
}

export const query = graphql`
  query BlogPostQuery($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        title
        date
      }
    }
  }
`


text: Small Project


text:
package org.apache.camel.component.sjms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;

import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.sjms.support.JmsTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

@DisabledIfSystemProperty(named = "activemq.instance.type", matches = "remote",
                          disabledReason = "Requires control of ActiveMQ, so it can only run locally (embedded or container)")
public class ReconnectInOutProducerTest extends JmsTestSupport {

    private static final String TEST_DESTINATION_NAME = "in.out.queue.producer.test";

    @Override
    protected boolean useJmx() {
        return false;
    }

    @Test
    public void testInOutQueueProducer() throws Exception {
        MessageConsumer mc = createQueueConsumer(TEST_DESTINATION_NAME + ".request");
        assertNotNull(mc);
        final String requestText = "Hello World!";
        final String responseText = "How are you";
        mc.setMessageListener(new MyMessageListener(requestText, responseText));
        Object responseObject = template.requestBody("direct:start", requestText);
        assertNotNull(responseObject);
        assertTrue(responseObject instanceof String);
        assertEquals(responseText, responseObject);
        mc.close();

        reconnect();

        mc = createQueueConsumer(TEST_DESTINATION_NAME + ".request");
        assertNotNull(mc);
        mc.setMessageListener(new MyMessageListener(requestText, responseText));
        responseObject = template.requestBody("direct:start", requestText);
        assertNotNull(responseObject);
        assertTrue(responseObject instanceof String);
        assertEquals(responseText, responseObject);
        mc.close();

    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                from("direct:start")
                        .to("log:" + TEST_DESTINATION_NAME + ".in.log.1?showBody=true")
                        .to(ExchangePattern.InOut, "sjms:queue:" + TEST_DESTINATION_NAME + ".request" + "?replyTo="
                                                   + TEST_DESTINATION_NAME + ".response")
                        .to("log:" + TEST_DESTINATION_NAME + ".out.log.1?showBody=true");
            }
        };
    }

    protected class MyMessageListener implements MessageListener {
        private String requestText;
        private String responseText;

        public MyMessageListener(String request, String response) {
            this.requestText = request;
            this.responseText = response;
        }

        @Override
        public void onMessage(Message message) {
            try {
                TextMessage request = (TextMessage) message;
                assertNotNull(request);
                String text = request.getText();
                assertEquals(requestText, text);

                TextMessage response = getSession().createTextMessage();
                response.setText(responseText);
                response.setJMSCorrelationID(request.getJMSCorrelationID());
                MessageProducer mp = getSession().createProducer(message.getJMSReplyTo());
                mp.send(response);
                mp.close();
            } catch (JMSException e) {
                fail(e.getLocalizedMessage());
            }
        }
    }
}


text:
from django.conf.urls import patterns, include, url
from views import AboutView

urlpatterns = patterns('',
	# About
	url(r'^$', AboutView.as_view(), name='about'),
)


text:
package Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Mukta on 9/28/15.
 * User Story 4
 */
public class BirthBeforeMarriage {
    public static boolean compare (String birthDateString, String marriageDateString) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");

        Date birthDate = format.parse(birthDateString);
        Date marriageDate = format.parse(marriageDateString);

        if (birthDate.compareTo(marriageDate) == 1) {
            System.out.println("Error: Birth date should be before the marriage date.");
            return true;
        } else {
            return false;
        }
    }
}


text:
package com.intellij.psi.search;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class LocalSearchScope extends SearchScope {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.search.LocalSearchScope");

  private final PsiElement[] myScope;
  private final boolean myIgnoreInjectedPsi;

  public static final LocalSearchScope EMPTY = new LocalSearchScope(PsiElement.EMPTY_ARRAY);
  private String myDisplayName;

  public LocalSearchScope(PsiElement scope) {
    this(scope, null);
  }

  public LocalSearchScope(PsiElement scope, String displayName) {
    this(new PsiElement[]{scope});
    myDisplayName = displayName;
  }

  public LocalSearchScope(PsiElement[] scope) {
    this(scope, null);
  }

  public LocalSearchScope(PsiElement[] scope, String displayName) {
    this(scope, displayName, false);
  }

  public LocalSearchScope(final PsiElement[] scope, final String displayName, final boolean ignoreInjectedPsi) {
    myIgnoreInjectedPsi = ignoreInjectedPsi;
    myDisplayName = displayName;
    Set<PsiElement> localScope = new LinkedHashSet<PsiElement>(scope.length);

    for (final PsiElement element : scope) {
      LOG.assertTrue(element.getContainingFile() != null);
      if (element instanceof PsiFile) {
        ContainerUtil.addAll(localScope, ((PsiFile)element).getPsiRoots());
      }
      else {
        localScope.add(element);
      }
    }
    myScope = localScope.toArray(new PsiElement[localScope.size()]);
  }

  public boolean isIgnoreInjectedPsi() {
    return myIgnoreInjectedPsi;
  }

  public String getDisplayName() {
    return myDisplayName == null ? super.getDisplayName() : myDisplayName;
  }

  public PsiElement[] getScope() {
    return myScope;
  }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof LocalSearchScope)) return false;

    final LocalSearchScope localSearchScope = (LocalSearchScope)o;

    if (localSearchScope.myIgnoreInjectedPsi != myIgnoreInjectedPsi) return false;
    if (localSearchScope.myScope.length != myScope.length) return false;
    for (final PsiElement scopeElement : myScope) {
      final PsiElement[] thatScope = localSearchScope.myScope;
      for (final PsiElement thatScopeElement : thatScope) {
        if (!Comparing.equal(scopeElement, thatScopeElement)) return false;
      }
    }

    return true;
  }

  public int hashCode() {
    int result = 0;
    result += myIgnoreInjectedPsi? 1 : 0;
    for (final PsiElement element : myScope) {
      result += element.hashCode();
    }
    return result;
  }

  @NotNull public LocalSearchScope intersectWith(@NotNull LocalSearchScope scope2){
    if (equals(scope2)) return this;
    return intersection(this, scope2);
  }

  private static LocalSearchScope intersection(LocalSearchScope scope1, LocalSearchScope scope2) {
    List<PsiElement> result = new ArrayList<PsiElement>();
    final PsiElement[] elements1 = scope1.myScope;
    final PsiElement[] elements2 = scope2.myScope;
    for (final PsiElement element1 : elements1) {
      for (final PsiElement element2 : elements2) {
        final PsiElement element = intersectScopeElements(element1, element2);
        if (element != null) {
          result.add(element);
        }
      }
    }
    return new LocalSearchScope(result.toArray(new PsiElement [result.size()]), null, scope1.myIgnoreInjectedPsi || scope2.myIgnoreInjectedPsi);
  }

  @NotNull
  @Override
  public SearchScope intersectWith(@NotNull SearchScope scope2) {
    if (scope2 instanceof LocalSearchScope) {
      return intersectWith((LocalSearchScope)scope2);
    }
    return ((GlobalSearchScope)scope2).intersectWith(this);
  }

  @Nullable
  private static PsiElement intersectScopeElements(PsiElement element1, PsiElement element2) {
    if (PsiTreeUtil.isContextAncestor(element1, element2, false)) return element2;
    if (PsiTreeUtil.isContextAncestor(element2, element1, false)) return element1;
    if (PsiTreeUtil.isAncestor(element1, element2, false)) return element2;
    if (PsiTreeUtil.isAncestor(element2, element1, false)) return element1;
    return null;
  }

  public String toString() {
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < myScope.length; i++) {
      final PsiElement element = myScope[i];
      if (i > 0) {
        result.append(",");
      }
      result.append(element.toString());
    }
    //noinspection HardCodedStringLiteral
    return "LocalSearchScope:" + result;
  }

  @NotNull
  public SearchScope union(@NotNull SearchScope scope) {
    if (scope instanceof LocalSearchScope) return union((LocalSearchScope)scope);
    return ((GlobalSearchScope)scope).union(this);
  }

  public SearchScope union(LocalSearchScope scope2) {
    if (equals(scope2)) return this;
    PsiElement[] elements1 = getScope();
    PsiElement[] elements2 = scope2.getScope();
    boolean[] united = new boolean[elements2.length];
    List<PsiElement> result = new ArrayList<PsiElement>();
    loop1:
    for (final PsiElement element1 : elements1) {
      for (int j = 0; j < elements2.length; j++) {
        final PsiElement element2 = elements2[j];
        final PsiElement unionElement = scopeElementsUnion(element1, element2);
        if (unionElement != null) {
          result.add(unionElement);
          united[j] = true;
          break loop1;
        }
      }
      result.add(element1);
    }
    for (int i = 0; i < united.length; i++) {
      final boolean b = united[i];
      if (!b) {
        result.add(elements2[i]);
      }
    }
    return new LocalSearchScope(result.toArray(new PsiElement[result.size()]));
  }

  private static PsiElement scopeElementsUnion(PsiElement element1, PsiElement element2) {
    if (PsiTreeUtil.isAncestor(element1, element2, false)) return element1;
    if (PsiTreeUtil.isAncestor(element2, element1, false)) return element2;
    PsiElement commonParent = PsiTreeUtil.findCommonParent(element1, element2);
    if (commonParent == null) return null;
    return commonParent;
  }

  public boolean isInScope(VirtualFile file) {
    for (PsiElement element : myScope) {
      PsiFile containingFile = element.getContainingFile();
      if (containingFile == null) continue;
      if (containingFile.getVirtualFile() == file) return true;
    }
    return false;
  }
}


text:
#include "address.hpp"
#include "err.hpp"
#include "tcp_address.hpp"
#include "ipc_address.hpp"

#include <string>
#include <sstream>

zmq::address_t::address_t (
    const std::string &protocol_, const std::string &address_)
    : protocol (protocol_),
      address (address_)
{
    memset (&resolved, 0, sizeof (resolved));
}

zmq::address_t::~address_t ()
{
    if (protocol == "tcp") {
        if (resolved.tcp_addr) {
            delete resolved.tcp_addr;
            resolved.tcp_addr = 0;
        }
    }
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
    else if (protocol == "ipc") {
        if (resolved.ipc_addr) {
            delete resolved.ipc_addr;
            resolved.ipc_addr = 0;
        }
    }
#endif
}

int zmq::address_t::to_string (std::string &addr_) const
{
    if (protocol == "tcp") {
        if (resolved.tcp_addr) {
            return resolved.tcp_addr->to_string(addr_);
        }
    }
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS
    else if (protocol == "ipc") {
        if (resolved.ipc_addr) {
            return resolved.ipc_addr->to_string(addr_);
        }
    }
#endif

    if (!protocol.empty () && !address.empty ()) {
        std::stringstream s;
        s << protocol << "://" << address;
        addr_ = s.str ();
        return 0;
    }
    addr_.clear ();
    return -1;
}


text:
@interface TestViewController2 : UIViewController

@end


text:
/***************************************************
	Significance Labs
	Brooklyn, NYC

 	Author: Alexandra Berke (aberke)
 	Written: Summer 2014

 	AngularJS app

****************************************************/

var UtilityService = function() {

  this.dateStringToDate = function(dateString) {
    /*
    Server returns datetimes as UTC strings like 2014-07-15 20:56:32.027186
    Safari fails to make a new Date out of these without extra help

    @param {string} dateString   - UTC string to turn into Date object
    Returns {Date obj} UTC date
    */
    if (!dateString || dateString instanceof Date) { return dateString; } // necessary to avoid errors when dateString is already turned into Date object

    var arr = dateString.split(/[- :]/);
    return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
  }

  this.removeFromList = function(list, item, matchingKey) {
    /*
    @param {array} list         - list from which to find and remove item
    @param {object} item        - object that presumably has matchingKey that is subject to removal
    @param {string} matchingKey - key on which to match items in list to item to find the item

    Returns {boolean} true if removed item, false otherwise
    */
    if (!(item && matchingKey && matchingKey in item)) {
      return false;
    }
    for (var i=0; i<list.length; i++) {
      if (list[i][matchingKey] == item[matchingKey]) {
        list.splice(i, 1);
        return true;
      }
    }
    return false;
  }

}

var APIservice = function($http, $q){

  function HTTP(method, endpoint, data, params, options) {

    var config = {
      method:  method,
      url:    endpoint,
      data:   (data || {}),
      params: (params || {}),
    };
    options = (options || {})
    for (var opt in options) { config[opt] = options[opt]; }

    var deferred = $q.defer();
    $http(config)
    .success(function(returnedData){
      deferred.resolve(returnedData);
    })
    .error(function(errData, status) {
      console.log('API Error', status, errData.message);
      deferred.reject(errData.message || "Error");
    });
    return deferred.promise;
  };
  function upload(method, endpoint, files, successCallback, errorCallback) {
    var fd = new FormData();
    fd.append("file", files[0]); //Take the first selected file

    var options = {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    };
    return HTTP(method, endpoint, fd, null, options).then(successCallback, errorCallback);
  }

  /* ---------- below functions return promises ---------------------------
                                              (route resolve needs promises)
  */

  this.PUTupload = function(endpoint, files) {
    return upload('PUT', endpoint, files);
  }
  this.POSTupload = function(endpoint, files) {
    return upload('POST', endpoint, files);
  }

  this.GET = function(endpoint, data) { // if there's data, send it as params
    return HTTP('GET', endpoint, null, data);
  };
  this.POST = function(endpoint, data) {
    return HTTP('POST', endpoint, data);
  };
  this.PUT = function(endpoint, data) {
    return HTTP('PUT', endpoint, data);
  };
  this.DELETE = function(endpoint, data) {
    return HTTP('DELETE', endpoint, data);
  };

};


text:
package sipparser

// Imports from the go standard library
import (
	"errors"
	"strings"
)

type viaStateFn func(v *Via) viaStateFn

type Via struct {
	State      string
	Error      error
	Via        string
	Proto      string
	Version    string
	Transport  string
	SentBy     string
	Branch     string
	Received   string
	RPort      string
	Params     []*Param
	protoEnd   int
	paramStart int
}

func (v *Via) parse() {
	for state := parseViaState; state != nil; {
		state = state(v)
	}
}

func (v *Via) addParam(s string) {
	if v.Params == nil {
		v.Params = make([]*Param, 0)
	}
	p := getParam(s)
	switch {
	case p.Param == "branch":
		v.Branch = p.Val
	case p.Param == "rport":
		v.RPort = p.Val
	case p.Param == "received":
		v.Received = p.Val
	default:
		v.Params = append(v.Params, p)
	}
}

func (v *Via) AddReceived(s string) {
	v.Received = s
}

func parseViaState(v *Via) viaStateFn {
	if v.Error != nil {
		return nil
	}
	return parseViaGetProto
}

func parseViaGetProto(v *Via) viaStateFn {
	v.protoEnd = strings.Index(v.Via, " ")
	if v.protoEnd == -1 {
		v.Error = errors.New("parseViaGetProto err: could not get LWS char.")
		return nil
	}
	protoParts := strings.SplitN(v.Via[0:v.protoEnd], "/", 3)
	if len(protoParts) != 3 {
		v.Error = errors.New("parseViaGetProto err: split err on proto char.")
		return nil
	}
	v.Proto = protoParts[0]
	v.Version = protoParts[1]
	v.Transport = protoParts[2]
	return parseViaGetParams
}

func parseViaGetParams(v *Via) viaStateFn {
	pChar := strings.IndexRune(v.Via, ';')
	if pChar == -1 {
		return parseViaGetHostPort
	}
	if v.paramStart == 0 {
		v.paramStart = pChar
	}
	if len(v.Via)-1 > pChar+1 {
		parts := strings.Split(v.Via[pChar+1:], ";")
		if len(parts) == 1 {
			v.addParam(parts[0])
			return parseViaGetHostPort
		}
		for i := 0; i < len(parts); i++ {
			v.addParam(parts[i])
		}
	}
	return parseViaGetHostPort
}

func parseViaGetHostPort(v *Via) viaStateFn {
	if v.protoEnd == 0 {
		v.Error = errors.New("parseViaGetHostPort err: protoEnd is 0.")
		return nil
	}
	if v.protoEnd < v.paramStart {
		v.SentBy = v.Via[v.protoEnd+1 : v.paramStart]
	}
	return nil
}


text:
Additional header content

A Specialization of BaseErrorModel class. Which acts as the base class of error structures for numerical data.

## Inheritance Hierarchy
System.Object
  iTin.Export.Model.BaseModel(BaseErrorModel)
    iTin.Export.Model.BaseErrorModel
      iTin.Export.Model.NumericErrorModel
        iTin.Export.Model.PercentageErrorModel
        iTin.Export.Model.ScientificErrorModel

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
[SerializableAttribute]
public class NumericErrorModel : BaseErrorModel,
	ICloneable
```

**VB**

``` VB
<SerializableAttribute>
Public Class NumericErrorModel
	Inherits BaseErrorModel
	Implements ICloneable
```

The NumericErrorModel type exposes the following members.

## Constructors

	Name	Description

![Public method](media/pubmethod.gif "Public method")	NumericErrorModel
Initializes a new instance of the NumericErrorModel class.

Back to Top

## Properties

	Name	Description

![Public property](media/pubproperty.gif "Public property")![Code example](media/CodeExample.png "Code example")	Comment
Gets or sets a reference that contains the error comment.
 (Inherited from BaseErrorModel.)

![Public property](media/pubproperty.gif "Public property")	IsDefault
Gets a value indicating whether this instance is default.
 (Overrides BaseErrorModel.IsDefault.)

![Public property](media/pubproperty.gif "Public property")	Properties
Gets or sets a reference to user-defined property list for this element.
 (Inherited from BaseModel(T).)

![Public property](media/pubproperty.gif "Public property")![Code example](media/CodeExample.png "Code example")	Value
Gets or sets preferred default value when occurs an error.

Back to Top

## Methods

	Name	Description

![Public method](media/pubmethod.gif "Public method")	Clone
Clones this instance.

![Public method](media/pubmethod.gif "Public method")	Combine(BaseErrorModel)
Combines this instance with reference parameter.
 (Inherited from BaseErrorModel.)

![Public method](media/pubmethod.gif "Public method")	Combine(NumericErrorModel)
Combines this instance with reference parameter.

![Public method](media/pubmethod.gif "Public method")	Equals	 (Inherited from Object.)

![Protected method](media/protmethod.gif "Protected method")	Finalize	 (Inherited from Object.)

![Public method](media/pubmethod.gif "Public method")	GetHashCode	 (Inherited from Object.)

![Protected method](media/protmethod.gif "Protected method")	GetStaticBindingValue
Gets the static binding value by reflection.
 (Inherited from BaseModel(T).)

![Public method](media/pubmethod.gif "Public method")	GetType	 (Inherited from Object.)

![Protected method](media/protmethod.gif "Protected method")	MemberwiseClone	 (Inherited from Object.)

![Public method](media/pubmethod.gif "Public method")	SaveToFile(String)
Saves to file.
 (Inherited from BaseModel(T).)

![Public method](media/pubmethod.gif "Public method")	SaveToFile(String, Exception)
Serializes current BaseModel object into file
 (Inherited from BaseModel(T).)

![Public method](media/pubmethod.gif "Public method")	Serialize
Serializes current BaseModel object into an Xml document.
 (Inherited from BaseModel(T).)

![Public method](media/pubmethod.gif "Public method")	ToString
Returns a string that represents the current object.
 (Inherited from BaseModel(T).)

Back to Top

## Remarks

The following table shows the different data types error structures.

Class	Description

PercentageErrorModel	Represents the error structure for percentage data type.

ScientificErrorModel	Represents the error structure for scientific data type.

## See Also

#### Reference
iTin.Export.Model Namespace


text:
@implementation UIViewController (Alerts)

// Helper category extension to display alerts easily.
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okButton];
    [self presentViewController:alert animated:YES completion:nil];
}

@end


text:
from robotide.lib.robot.errors import DataError
from robotide.lib.robot.utils import (get_error_message, unic, is_java_method,
                         is_string, is_unicode)

from .arguments import JavaArgumentParser, PythonArgumentParser

def no_dynamic_method(*args):
    pass

class _DynamicMethod(object):
    _underscore_name = NotImplemented

    def __init__(self, lib):
        self.method = self._get_method(lib)

    def _get_method(self, lib):
        for name in self._underscore_name, self._camelCaseName:
            method = getattr(lib, name, None)
            if callable(method):
                return method
        return no_dynamic_method

    @property
    def _camelCaseName(self):
        tokens = self._underscore_name.split('_')
        return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]])

    @property
    def name(self):
        return self.method.__name__

    def __call__(self, *args):
        try:
            return self._handle_return_value(self.method(*args))
        except:
            raise DataError("Calling dynamic method '%s' failed: %s"
                            % (self.method.__name__, get_error_message()))

    def _handle_return_value(self, value):
        raise NotImplementedError

    def _to_string(self, value):
        if not is_string(value):
            raise DataError('Return value must be string.')
        return value if is_unicode(value) else unic(value, 'UTF-8')

    def _to_list_of_strings(self, value):
        try:
            return [self._to_string(v) for v in value]
        except (TypeError, DataError):
            raise DataError('Return value must be list of strings.')

    def __nonzero__(self):
        return self.method is not no_dynamic_method

class GetKeywordNames(_DynamicMethod):
    _underscore_name = 'get_keyword_names'

    def _handle_return_value(self, value):
        return self._to_list_of_strings(value or [])

class RunKeyword(_DynamicMethod):
    _underscore_name = 'run_keyword'

    @property
    def supports_kwargs(self):
        if is_java_method(self.method):
            return self._supports_java_kwargs(self.method)
        return self._supports_python_kwargs(self.method)

    def _supports_python_kwargs(self, method):
        spec = PythonArgumentParser().parse(method)
        return len(spec.positional) == 3

    def _supports_java_kwargs(self, method):
        func = self.method.im_func if hasattr(method, 'im_func') else method
        signatures = func.argslist[:func.nargs]
        spec = JavaArgumentParser().parse(signatures)
        return (self._java_single_signature_kwargs(spec) or
                self._java_multi_signature_kwargs(spec))

    def _java_single_signature_kwargs(self, spec):
        return len(spec.positional) == 1 and spec.varargs and spec.kwargs

    def _java_multi_signature_kwargs(self, spec):
        return len(spec.positional) == 3 and not (spec.varargs or spec.kwargs)

class GetKeywordDocumentation(_DynamicMethod):
    _underscore_name = 'get_keyword_documentation'

    def _handle_return_value(self, value):
        return self._to_string(value or '')

class GetKeywordArguments(_DynamicMethod):
    _underscore_name = 'get_keyword_arguments'

    def __init__(self, lib):
        _DynamicMethod.__init__(self, lib)
        self._supports_kwargs = RunKeyword(lib).supports_kwargs

    def _handle_return_value(self, value):
        if value is None:
            if self._supports_kwargs:
                return ['*varargs', '**kwargs']
            return ['*varargs']
        return self._to_list_of_strings(value)


text:
'use strict'

// modules > native
const p = require('path')
const fs = require('fs')

const projectRoot = p.dirname(__dirname)

const port = fs.existsSync(p.join(projectRoot, 'server/config/port.js'))
  ? require(p.join(projectRoot, 'server/config/port')) : null

const suffix = `-${Date.now().toString(16)}`

module.exports = {
  babel: {
    src: 'client/**/*.{js,jsx}',
    dest: 'build',
    presets: [
      ['@babel/env', { targets: { node: 'current' }, shippedProposals: true }],
    ],
    plugins: [
      ['@babel/transform-react-jsx', { pragma: 'h' }],
      'add-module-exports',
      ['module-resolver', {
        alias: {
          'easy-tz': 'easy-tz/cjs',
          lowline: 'lodash',
          'mini-qs': 'querystring',
          preact: 'jsx-node',
        },
      }],
    ],
  },

  browserSync: {
    browser: null,
    ghostMode: false,
    proxy: `localhost:${port || 3000}`,
    port: 1337,
    ui: {
      port: 1338,
    },
    files: [
      p.join(projectRoot, 'public/css/**/*.css'),
      p.join(projectRoot, 'public/js/**/*.js'),
    ],
  },

  less: {
    suffix,
    src: [
      p.join(projectRoot, 'assets/less/*.less'),
    ],
    dest: p.join(projectRoot, 'public/css'),
    functions: require(p.join(process.cwd(), 'gulp/less/functions')),
    options: {
      paths: [
        p.join(projectRoot, 'node_modules/spineless/less'),
      ],
    },
  },

  nodemon: {
    ext: 'js,jsx,marko',
    ignore: '*.marko.js',
    watch: [
      'server',
    ],
    script: fs.existsSync(p.join(projectRoot, 'package.json')) ? require(p.join(projectRoot, 'package.json')).main.replace(/^\./, projectRoot) : 'server/server.js',
    env: {
      BABEL_ENV: 'node',
      // what port you actually put into the browser... when using browser-sync
      // this will differ from the internal port used by express
      EXTERNAL_PORT: 1337,
      // needed to force debug to use colors despite tty.istty(0) being false,
      // which it is in a child process
      DEBUG_COLORS: true,
      // needed to force chalk to use when running gulp nodemon tasks.
      FORCE_COLOR: true,
      projectRoot,
      NODE_ENV: process.env.NODE_ENV,
      // DEBUG: 'midwest:*'
    },
  },

  raster: {
    src: p.join(projectRoot, 'assets/raster/**/*.{png,gif,jpg}'),
    dest: p.join(projectRoot, 'public/img'),
  },

  rollup: {
    suffix,
    plugins: {
      babel: {
        include: [
          'node_modules/preact/**',
          'node_modules/comkit-preact/**',
          'client/**',
        ],
        presets: [
          ['@babel/env', { modules: false, shippedProposals: true }],
        ],
        plugins: [
          ['@babel/transform-react-jsx', { pragma: 'h' }],
        ],
      },

      replace: {
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      },

      nodeResolve: {
        module: true, // Default: true
        jsnext: true, // Default: false
        main: true, // Default: true
        browser: true, // Default: false
        preferBuiltins: false,
        extensions: ['.mjs', '.js', '.jsx', '.json'],
        customResolveOptions: {
          // this option is set to ensure symlinked packages still resolve
          // packages in projects node_modules
          moduleDirectory: p.join(process.cwd(), 'node_modules'),
        },
      },

      commonjs: {
        include: [
          p.join(projectRoot, 'node_modules/**'),
        ],
        exclude: [
          p.join(projectRoot, 'node_modules/lodash-es/**'),
          p.join(projectRoot, 'node_modules/symbol-observable/**'),
        ],
        extensions: ['.js'],
        sourceMap: true, // Default: true
        namedExports: {
          'node_modules/react/index.js': ['Component', 'Children', 'PropTypes', 'createElement'],
        },
      },
    },
    inputs: [
      'client/app.js',
    ],
    outputs: [
      'public/js/app.js',
    ],
    output: {
      sourcemap: true,
      format: 'iife',
    },
  },

  sass: {
    src: p.join(projectRoot, 'assets/sass/*.{sass,scss}'),
    dest: p.join(projectRoot, 'public/css'),
    suffix,
    options: {
      outputStyle: 'nested',
      includePaths: [
        p.join(projectRoot, 'node_modules/spysass/sass'),
        p.join(projectRoot, 'node_modules/susy/sass'),
        p.join(projectRoot, 'node_modules/breakpoint-sass/sass'),
      ],
      imagePath: '../img',
    },
  },

  static: {
    src: p.join(projectRoot, 'assets/static/**/*'),
    dest: p.join(projectRoot, 'public'),
  },

  svg: {
    src: p.join(projectRoot, 'assets/svg/**/*.svg'),
    dest: p.join(projectRoot, 'public/img'),
  },

  tasks: {
    development: ['wipe', ['babel', 'raster', 'less', 'rollup', 'static', 'svg', 'video'], ['nodemon'], ['watch', 'browser-sync']],
    staging: ['wipe', ['babel', 'raster', 'less', 'rollup', 'static', 'svg', 'video']],
    production: ['wipe', ['babel', 'raster', 'less', 'rollup', 'static', 'svg', 'video']],
  }[process.env.NODE_ENV],

  video: {
    src: p.join(projectRoot, 'assets/video/**/*'),
    dest: p.join(projectRoot, 'public/video'),
  },

  watch: {
    babel: p.join(projectRoot, 'client/**/*.{js,jsx}'),
    less: p.join(projectRoot, 'assets/less/**/*.less'),
  },

  wipe: {
    src: [
      p.join(projectRoot, 'build'),
      p.join(projectRoot, 'public'),
    ],
  },
}


text:
package org.achtern.AchternEngine.lwjgl.util;

import org.achtern.AchternEngine.core.rendering.mesh.MeshData;
import org.achtern.AchternEngine.core.rendering.state.*;
import org.achtern.AchternEngine.core.rendering.texture.Filter;
import org.achtern.AchternEngine.core.rendering.texture.Format;
import org.achtern.AchternEngine.core.rendering.texture.InternalFormat;
import org.achtern.AchternEngine.core.rendering.texture.Type;
import org.achtern.AchternEngine.core.resource.fileparser.caseclasses.GLSLScript;

import static org.lwjgl.openal.AL10.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.GL_RESCALE_NORMAL;
import static org.lwjgl.opengl.GL12.GL_TEXTURE_3D;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL14.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL32.GL_DEPTH_CLAMP;
import static org.lwjgl.opengl.GL32.GL_GEOMETRY_SHADER;

public class GLEnum {

    // ---
    // DataBinding
    // --

    public static int getGLEnum(Filter minFilter) {
        switch (minFilter) {
            case NEAREST:
                return GL_NEAREST;
            case LINEAR:
                return GL_LINEAR;
            default:
                throw new UnsupportedOperationException("Filter: " + minFilter + " not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(Type type) {
        switch (type) {
            case ONE_DIMENSIONAL:
                return GL_TEXTURE_1D;
            case TWO_DIMENSIONAL:
                return GL_TEXTURE_2D;
            case THREE_DIMENSIONAL:
                return GL_TEXTURE_3D;
            case CUBE_MAP:
                return GL_TEXTURE_CUBE_MAP;
            default:
                // TODO: implement the other types
                throw new UnsupportedOperationException("Texture type " + type + " not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(Format format) {
        switch (format) {
            case RGBA:
                return GL_RGBA;
            case RGB:
                return GL_RGB;
            case DEPTH:
                return GL_DEPTH_COMPONENT;

            default:
                throw new UnsupportedOperationException("Format: " + format + " not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(InternalFormat format) {
        switch (format) {
            case RGBA8:
                return GL_RGBA8;
            case DEPTH_COMPONENT:
                return GL_DEPTH_COMPONENT;
            case DEPTH_COMPONENT16:
                return GL_DEPTH_COMPONENT16;
            case DEPTH_COMPONENT24:
                return GL_DEPTH_COMPONENT24;
            case DEPTH_COMPONENT32:
                return GL_DEPTH_COMPONENT32;

            default:
                throw new UnsupportedOperationException("Format; " + format + " not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(GLSLScript.Type type) {
        switch (type) {
            case VERTEX_SHADER:
                return GL_VERTEX_SHADER;
            case FRAGMENT_SHADER:
                return GL_FRAGMENT_SHADER;
            case GEOMETRY_SHADER:
                return GL_GEOMETRY_SHADER;
            default:
                throw new UnsupportedOperationException("Shader type not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(MeshData.Mode mode) {
        switch (mode) {
            case TRIANGLES:
                return GL_TRIANGLES;
            case LINES:
                return GL_LINES;
            case LINE_LOOP:
                return GL_LINE_LOOP;
            default:
                throw new UnsupportedOperationException("Mode " + mode + " not supported in this LWJGLRenderEngine");
        }
    }

    // ---
    // RenderEngineState
    // --

    public static int getGLEnum(Feature feature) {
        switch (feature) {
            case DEPTH_CLAMP:
                return GL_DEPTH_CLAMP;
            case ALPHA_TEST:
                return GL_ALPHA_TEST;
            case AUTO_NORMAL:
                return GL_AUTO_NORMAL;
            case BLEND:
                return GL_BLEND;
            case COLOR_LOGIC_OP:
                return GL_COLOR_LOGIC_OP;
            case COLOR_MATERIAL:
                return GL_COLOR_MATERIAL;
            case COLOR_SUM:
                return GL_COLOR_SUM;
            case CULL_FACE:
                return GL_CULL_FACE;
            case DEPTH_TEST:
                return GL_DEPTH_TEST;
            case DITHER:
                return GL_DITHER;
            case FOG:
                return GL_FOG;
            case INDEX_LOGIC_OP:
                return GL_INDEX_LOGIC_OP;
            case LIGHTING:
                return GL_LIGHTING;
            case LINE_SMOOTH:
                return GL_LINE_SMOOTH;
            case LINE_STIPPLE:
                return GL_LINE_STIPPLE;
            case MAP1_COLOR_4:
                return GL_MAP1_COLOR_4;
            case MAP1_INDEX:
                return GL_MAP1_INDEX;
            case MAP1_NORMAL:
                return GL_MAP1_NORMAL;
            case MAP1_TEXTURE_COORD_1:
                return GL_MAP1_TEXTURE_COORD_1;
            case MAP1_TEXTURE_COORD_2:
                return GL_MAP1_TEXTURE_COORD_2;
            case MAP1_TEXTURE_COORD_3:
                return GL_MAP1_TEXTURE_COORD_3;
            case MAP1_TEXTURE_COORD_4:
                return GL_MAP1_TEXTURE_COORD_4;
            case MAP1_VERTEX_3:
                return GL_MAP1_VERTEX_3;
            case MAP1_VERTEX_4:
                return GL_MAP1_VERTEX_4;
            case MAP2_COLOR_4:
                return GL_MAP2_COLOR_4;
            case MAP2_INDEX:
                return GL_MAP2_INDEX;
            case MAP2_NORMAL:
                return GL_MAP2_NORMAL;
            case MAP2_TEXTURE_COORD_1:
                return GL_MAP2_TEXTURE_COORD_1;
            case MAP2_TEXTURE_COORD_2:
                return GL_MAP2_TEXTURE_COORD_2;
            case MAP2_TEXTURE_COORD_3:
                return GL_MAP2_TEXTURE_COORD_3;
            case MAP2_TEXTURE_COORD_4:
                return GL_MAP2_TEXTURE_COORD_4;
            case MAP2_VERTEX_3:
                return GL_MAP2_VERTEX_3;
            case MAP2_VERTEX_4:
                return GL_MAP2_VERTEX_4;
            case MULTISAMPLE:
                return GL_MULTISAMPLE;
            case NORMALIZE:
                return GL_NORMALIZE;
            case POINT_SMOOTH:
                return GL_POINT_SMOOTH;
            case POINT_SPRITE:
                return GL_POINT_SPRITE;
            case POLYGON_OFFSET_FILL:
                return GL_POLYGON_OFFSET_FILL;
            case POLYGON_OFFSET_LINE:
                return GL_POLYGON_OFFSET_LINE;
            case POLYGON_OFFSET_POINT:
                return GL_POLYGON_OFFSET_POINT;
            case POLYGON_SMOOTH:
                return GL_POLYGON_SMOOTH;
            case POLYGON_STIPPLE:
                return GL_POLYGON_STIPPLE;
            case RESCALE_NORMAL:
                return GL_RESCALE_NORMAL;
            case SAMPLE_ALPHA_TO_COVERAGE:
                return GL_SAMPLE_ALPHA_TO_COVERAGE;
            case SAMPLE_ALPHA_TO_ONE:
                return GL_SAMPLE_ALPHA_TO_ONE;
            case SAMPLE_COVERAGE:
                return GL_SAMPLE_COVERAGE;
            case SCISSOR_TEST:
                return GL_SCISSOR_TEST;
            case STENCIL_TEST:
                return GL_STENCIL_TEST;
            case TEXTURE_1D:
                return GL_TEXTURE_1D;
            case TEXTURE_2D:
                return GL_TEXTURE_2D;
            case TEXTURE_3D:
                return GL_TEXTURE_3D;
            case TEXTURE_CUBE_MAP:
                return GL_TEXTURE_CUBE_MAP;
            case TEXTURE_GEN_Q:
                return GL_TEXTURE_GEN_Q;
            case TEXTURE_GEN_R:
                return GL_TEXTURE_GEN_R;
            case TEXTURE_GEN_S:
                return GL_TEXTURE_GEN_S;
            case TEXTURE_GEN_T:
                return GL_TEXTURE_GEN_T;
            case VERTEX_PROGRAM_POINT_SIZE:
                return GL_VERTEX_PROGRAM_POINT_SIZE;
            case VERTEX_PROGRAM_TWO_SIDE:
                return GL_VERTEX_PROGRAM_TWO_SIDE;
            default:
                throw new UnsupportedOperationException("Feature " + feature + " not supported in this LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(Face face) {
        switch (face) {
            case BACK:
                return GL_BACK;
            case FRONT:
                return GL_FRONT;
            case ALL:
                return GL_FRONT_AND_BACK;
            default:
                throw new UnsupportedOperationException("Face " + face + " not supported in LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(DepthFunction function) {
        switch (function) {
            case NEVER:
                return GL_NEVER;
            case LESS:
                return GL_LESS;
            case EQUAL:
                return GL_EQUAL;
            case LESS_OR_EQUAL:
                return GL_LEQUAL;
            case GREATER:
                return GL_GREATER;
            case NOT_EQUAL:
                return GL_NOTEQUAL;
            case GREATER_OR_EQUAL:
                return GL_GEQUAL;
            case ALWAYS:
                return GL_ALWAYS;
            default:
                throw new UnsupportedOperationException("DepthFunction "
                        + function + " not supported in LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(FrontFaceMethod face) {
        switch (face) {
            case CLOCKWISE:
                return GL_CW;
            case COUNTER_CLOCKWISE:
                return GL_CCW;
            default:
                throw new UnsupportedOperationException("FrontFace "
                        + face + " not supported in LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(BlendFunction function) {
        switch (function) {
            case ZERO:
                return GL_ZERO;
            case ONE:
                return GL_ONE;
            case SRC_COLOR:
                return GL_SRC_COLOR;
            case ONE_MINUS_SRC_COLOR:
                return GL_ONE_MINUS_SRC_COLOR;
            case DST_COLOR:
                return GL_DST_COLOR;
            case ONE_MINUS_DST_COLOR:
                return GL_ONE_MINUS_DST_COLOR;
            case SRC_ALPHA:
                return GL_SRC_ALPHA;
            case ONE_MINUS_SRC_ALPHA:
                return GL_ONE_MINUS_SRC_ALPHA;
            case DST_ALPHA:
                return GL_DST_ALPHA;
            case ONE_MINUS_DST_ALPHA:
                return GL_ONE_MINUS_DST_ALPHA;
            case CONSTANT_COLOR:
                return GL_CONSTANT_COLOR;
            case ONE_MINUS_CONSTANT_COLOR:
                return GL_ONE_MINUS_CONSTANT_COLOR;
            case CONSTANT_ALPHA:
                return GL_CONSTANT_ALPHA;
            case ONE_MINUS_CONSTANT_ALPHA:
                return GL_ONE_MINUS_CONSTANT_ALPHA;
            case SRC_ALPHA_SATURATE:
                return GL_SRC_ALPHA_SATURATE;
            default:
                throw new UnsupportedOperationException("BlendFunction "
                        + function + " not supported in LWJGLRenderEngine");
        }
    }

    public static int getGLEnum(FillMode mode) {
        switch (mode) {
            case POINT:
                return GL_POINT;
            case LINE:
                return GL_LINE;
            case FILL:
                return GL_FILL;
            default:
                throw new UnsupportedOperationException("FillMode " + mode + " not supported in LWJGLRenderEngine");
        }
    }

    // ---
    // OpenAL DataBinder
    // --

    public static int getGLEnum(org.achtern.AchternEngine.core.audio.openal.Format format) {
        switch (format) {
            case MONO8:
                return AL_FORMAT_MONO8;
            case MONO16:
                return AL_FORMAT_MONO16;
            case STEREO8:
                return AL_FORMAT_STEREO16;
            case STEREO16:
                return AL_FORMAT_STEREO16;
            default:
                throw new UnsupportedOperationException("OpenAL Format " + format + " not supported by LWJGL OpenAl");
        }
    }

}