text:
<?php

namespace CS\ClientBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('firstname');
        $builder->add('lastname');
        $builder->add('details', 'collection', array('type' => new ContactDetailType, 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, 'label' => 'Contact Details'));
    }

    public function getName()
    {
        return 'contact';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'data_class' => 'CS\ClientBundle\Entity\Contact'
        ));
    }
}


text:
#include <folly/io/IOBuf.h>

#include <folly/Format.h>
#include <folly/Range.h>
#include <folly/io/Cursor.h>

#include <gtest/gtest.h>

using folly::ByteRange;
using folly::format;
using folly::IOBuf;
using folly::StringPiece;
using std::unique_ptr;
using namespace folly::io;

TEST(IOBuf, RWCursor) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(20);
  unique_ptr<IOBuf> iobuf2(IOBuf::create(20));
  iobuf2->append(20);

  iobuf2.get();
  iobuf1->prependChain(std::move(iobuf2));

  EXPECT_TRUE(iobuf1->isChained());

  RWPrivateCursor wcursor(iobuf1.get());
  Cursor rcursor(iobuf1.get());
  wcursor.writeLE((uint64_t)1);
  wcursor.writeLE((uint64_t)1);
  wcursor.writeLE((uint64_t)1);
  wcursor.write((uint8_t)1);

  EXPECT_EQ(1, rcursor.readLE<uint64_t>());
  rcursor.skip(8);
  EXPECT_EQ(1, rcursor.readLE<uint32_t>());
  rcursor.skip(0);
  EXPECT_EQ(0, rcursor.read<uint8_t>());
  EXPECT_EQ(0, rcursor.read<uint8_t>());
  EXPECT_EQ(0, rcursor.read<uint8_t>());
  EXPECT_EQ(0, rcursor.read<uint8_t>());
  EXPECT_EQ(1, rcursor.read<uint8_t>());
}

TEST(IOBuf, skip) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(20);
  RWPrivateCursor wcursor(iobuf1.get());
  wcursor.write((uint8_t)1);
  wcursor.write((uint8_t)2);
  Cursor cursor(iobuf1.get());
  cursor.skip(1);
  EXPECT_EQ(2, cursor.read<uint8_t>());
}

TEST(IOBuf, reset) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(20);
  RWPrivateCursor wcursor(iobuf1.get());
  wcursor.write((uint8_t)1);
  wcursor.write((uint8_t)2);
  wcursor.reset(iobuf1.get());
  EXPECT_EQ(1, wcursor.read<uint8_t>());
}

TEST(IOBuf, copy_assign_convert) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(20);
  RWPrivateCursor wcursor(iobuf1.get());
  RWPrivateCursor cursor2(wcursor);
  RWPrivateCursor cursor3(iobuf1.get());

  wcursor.write((uint8_t)1);
  cursor3 = wcursor;
  wcursor.write((uint8_t)2);
  Cursor cursor4(wcursor);
  RWPrivateCursor cursor5(wcursor);
  wcursor.write((uint8_t)3);

  EXPECT_EQ(1, cursor2.read<uint8_t>());
  EXPECT_EQ(2, cursor3.read<uint8_t>());
  EXPECT_EQ(3, cursor4.read<uint8_t>());
}

TEST(IOBuf, arithmetic) {
  IOBuf iobuf1(IOBuf::CREATE, 20);
  iobuf1.append(20);
  RWPrivateCursor wcursor(&iobuf1);
  wcursor += 1;
  wcursor.write((uint8_t)1);
  Cursor cursor(&iobuf1);
  cursor += 1;
  EXPECT_EQ(1, cursor.read<uint8_t>());

  Cursor start(&iobuf1);
  Cursor cursor2 = start + 9;
  EXPECT_EQ(7, cursor2 - cursor);
  EXPECT_NE(cursor, cursor2);
  cursor += 8;
  cursor2 = cursor2 + 1;
  EXPECT_EQ(cursor, cursor2);
}

TEST(IOBuf, endian) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(20);
  RWPrivateCursor wcursor(iobuf1.get());
  Cursor rcursor(iobuf1.get());
  uint16_t v = 1;
  int16_t vu = -1;
  wcursor.writeBE(v);
  wcursor.writeBE(vu);
  // Try a couple combinations to ensure they were generated correctly
  wcursor.writeBE(vu);
  wcursor.writeLE(vu);
  wcursor.writeLE(vu);
  wcursor.writeLE(v);
  EXPECT_EQ(v, rcursor.readBE<uint16_t>());
}

TEST(IOBuf, Cursor) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(1));
  iobuf1->append(1);
  RWPrivateCursor c(iobuf1.get());
  c.write((uint8_t)40); // OK
  try {
    c.write((uint8_t)10); // Bad write, checked should except.
    EXPECT_EQ(true, false);
  } catch (...) {
  }
}

TEST(IOBuf, UnshareCursor) {
  uint8_t buf = 0;
  unique_ptr<IOBuf> iobuf1(IOBuf::wrapBuffer(&buf, 1));
  unique_ptr<IOBuf> iobuf2(IOBuf::wrapBuffer(&buf, 1));
  RWUnshareCursor c1(iobuf1.get());
  RWUnshareCursor c2(iobuf2.get());

  c1.write((uint8_t)10); // This should duplicate the two buffers.
  uint8_t t = c2.read<uint8_t>();
  EXPECT_EQ(0, t);

  iobuf1 = IOBuf::wrapBuffer(&buf, 1);
  iobuf2 = IOBuf::wrapBuffer(&buf, 1);
  RWPrivateCursor c3(iobuf1.get());
  RWPrivateCursor c4(iobuf2.get());

  c3.write((uint8_t)10); // This should _not_ duplicate the two buffers.
  t = c4.read<uint8_t>();
  EXPECT_EQ(10, t);
}

namespace {
void append(std::unique_ptr<IOBuf>& buf, folly::StringPiece data) {
  EXPECT_LE(data.size(), buf->tailroom());
  memcpy(buf->writableData(), data.data(), data.size());
  buf->append(data.size());
}

void append(Appender& appender, StringPiece data) {
  appender.push(ByteRange(data));
}

std::string toString(const IOBuf& buf) {
  std::string str;
  Cursor cursor(&buf);
  ByteRange b;
  while (!(b = cursor.peekBytes()).empty()) {
    str.append(reinterpret_cast<const char*>(b.data()), b.size());
    cursor.skip(b.size());
  }
  return str;
}

}  // namespace

TEST(IOBuf, PullAndPeek) {
  std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
  append(iobuf1, "he");
  std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
  append(iobuf2, "llo ");
  std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
  append(iobuf3, "world");
  iobuf1->prependChain(std::move(iobuf2));
  iobuf1->prependChain(std::move(iobuf3));
  EXPECT_EQ(3, iobuf1->countChainElements());
  EXPECT_EQ(11, iobuf1->computeChainDataLength());

  char buf[12];
  memset(buf, 0, sizeof(buf));
  Cursor(iobuf1.get()).pull(buf, 11);
  EXPECT_EQ("hello world", std::string(buf));

  memset(buf, 0, sizeof(buf));
  EXPECT_EQ(11, Cursor(iobuf1.get()).pullAtMost(buf, 20));
  EXPECT_EQ("hello world", std::string(buf));

  EXPECT_THROW({Cursor(iobuf1.get()).pull(buf, 20);},
               std::out_of_range);

  {
    RWPrivateCursor cursor(iobuf1.get());
    auto b = cursor.peekBytes();
    EXPECT_EQ("he", StringPiece(b));
    cursor.skip(b.size());
    b = cursor.peekBytes();
    EXPECT_EQ("llo ", StringPiece(b));
    cursor.skip(b.size());
    b = cursor.peekBytes();
    EXPECT_EQ("world", StringPiece(b));
    cursor.skip(b.size());
    EXPECT_EQ(3, iobuf1->countChainElements());
    EXPECT_EQ(11, iobuf1->computeChainDataLength());
  }

  {
    RWPrivateCursor cursor(iobuf1.get());
    cursor.gather(11);
    auto b = cursor.peekBytes();
    EXPECT_EQ("hello world", StringPiece(b));
    EXPECT_EQ(1, iobuf1->countChainElements());
    EXPECT_EQ(11, iobuf1->computeChainDataLength());
  }
}

TEST(IOBuf, pushCursorData) {
  unique_ptr<IOBuf> iobuf1(IOBuf::create(20));
  iobuf1->append(15);
  iobuf1->trimStart(5);
  unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
  unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
  iobuf3->append(10);

  iobuf1->prependChain(std::move(iobuf2));
  iobuf1->prependChain(std::move(iobuf3));
  EXPECT_TRUE(iobuf1->isChained());

  //write 20 bytes to the buffer chain
  RWPrivateCursor wcursor(iobuf1.get());
  EXPECT_FALSE(wcursor.isAtEnd());
  wcursor.writeBE<uint64_t>(1);
  wcursor.writeBE<uint64_t>(10);
  wcursor.writeBE<uint32_t>(20);
  EXPECT_TRUE(wcursor.isAtEnd());

  // create a read buffer for the buffer chain
  Cursor rcursor(iobuf1.get());
  EXPECT_EQ(1, rcursor.readBE<uint64_t>());
  EXPECT_EQ(10, rcursor.readBE<uint64_t>());
  EXPECT_EQ(20, rcursor.readBE<uint32_t>());
  EXPECT_EQ(0, rcursor.totalLength());
  rcursor.reset(iobuf1.get());
  EXPECT_EQ(20, rcursor.totalLength());

  // create another write buffer
  unique_ptr<IOBuf> iobuf4(IOBuf::create(30));
  iobuf4->append(30);
  RWPrivateCursor wcursor2(iobuf4.get());
  // write buffer chain data into it, now wcursor2 should only
  // have 10 bytes writable space
  wcursor2.push(rcursor, 20);
  EXPECT_EQ(wcursor2.totalLength(), 10);
  // write again with not enough space in rcursor
  EXPECT_THROW(wcursor2.push(rcursor, 20), std::out_of_range);

  // create a read cursor to check iobuf3 data back
  Cursor rcursor2(iobuf4.get());
  EXPECT_EQ(1, rcursor2.readBE<uint64_t>());
  EXPECT_EQ(10, rcursor2.readBE<uint64_t>());
  EXPECT_EQ(20, rcursor2.readBE<uint32_t>());

}

TEST(IOBuf, Gather) {
  std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
  append(iobuf1, "he");
  std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
  append(iobuf2, "llo ");
  std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
  append(iobuf3, "world");
  iobuf1->prependChain(std::move(iobuf2));
  iobuf1->prependChain(std::move(iobuf3));
  EXPECT_EQ(3, iobuf1->countChainElements());
  EXPECT_EQ(11, iobuf1->computeChainDataLength());

  // Attempting to gather() more data than available in the chain should fail.
  // Try from the very beginning of the chain.
  RWPrivateCursor cursor(iobuf1.get());
  EXPECT_THROW(cursor.gather(15), std::overflow_error);
  // Now try from the middle of the chain
  cursor += 3;
  EXPECT_THROW(cursor.gather(10), std::overflow_error);

  // Calling gatherAtMost() should succeed, however, and just gather
  // as much as it can
  cursor.gatherAtMost(10);
  EXPECT_EQ(8, cursor.length());
  EXPECT_EQ(8, cursor.totalLength());
  EXPECT_FALSE(cursor.isAtEnd());
  EXPECT_EQ("lo world",
            folly::StringPiece(reinterpret_cast<const char*>(cursor.data()),
                               cursor.length()));
  EXPECT_EQ(2, iobuf1->countChainElements());
  EXPECT_EQ(11, iobuf1->computeChainDataLength());

  // Now try gather again on the chain head
  cursor = RWPrivateCursor(iobuf1.get());
  cursor.gather(5);
  // Since gather() doesn't split buffers, everything should be collapsed into
  // a single buffer now.
  EXPECT_EQ(1, iobuf1->countChainElements());
  EXPECT_EQ(11, iobuf1->computeChainDataLength());
  EXPECT_EQ(11, cursor.length());
  EXPECT_EQ(11, cursor.totalLength());
}

TEST(IOBuf, cloneAndInsert) {
  std::unique_ptr<IOBuf> iobuf1(IOBuf::create(10));
  append(iobuf1, "he");
  std::unique_ptr<IOBuf> iobuf2(IOBuf::create(10));
  append(iobuf2, "llo ");
  std::unique_ptr<IOBuf> iobuf3(IOBuf::create(10));
  append(iobuf3, "world");
  iobuf1->prependChain(std::move(iobuf2));
  iobuf1->prependChain(std::move(iobuf3));
  EXPECT_EQ(3, iobuf1->countChainElements());
  EXPECT_EQ(11, iobuf1->computeChainDataLength());

  std::unique_ptr<IOBuf> cloned;

  Cursor(iobuf1.get()).clone(cloned, 3);
  EXPECT_EQ(2, cloned->countChainElements());
  EXPECT_EQ(3, cloned->computeChainDataLength());

  EXPECT_EQ(11, Cursor(iobuf1.get()).cloneAtMost(cloned, 20));
  EXPECT_EQ(3, cloned->countChainElements());
  EXPECT_EQ(11, cloned->computeChainDataLength());

  EXPECT_THROW({Cursor(iobuf1.get()).clone(cloned, 20);},
               std::out_of_range);

  {
    // Check that inserting in the middle of an iobuf splits
    RWPrivateCursor cursor(iobuf1.get());
    Cursor(iobuf1.get()).clone(cloned, 3);
    EXPECT_EQ(2, cloned->countChainElements());
    EXPECT_EQ(3, cloned->computeChainDataLength());

    cursor.skip(1);

    cursor.insert(std::move(cloned));
    cursor.insert(folly::IOBuf::create(0));
    EXPECT_EQ(7, iobuf1->countChainElements());
    EXPECT_EQ(14, iobuf1->computeChainDataLength());
    // Check that nextBuf got set correctly to the buffer with 1 byte left
    EXPECT_EQ(1, cursor.peekBytes().size());
    cursor.read<uint8_t>();
  }

  {
    // Check that inserting at the end doesn't create empty buf
    RWPrivateCursor cursor(iobuf1.get());
    Cursor(iobuf1.get()).clone(cloned, 1);
    EXPECT_EQ(1, cloned->countChainElements());
    EXPECT_EQ(1, cloned->computeChainDataLength());

    cursor.skip(1);

    cursor.insert(std::move(cloned));
    EXPECT_EQ(8, iobuf1->countChainElements());
    EXPECT_EQ(15, iobuf1->computeChainDataLength());
    // Check that nextBuf got set correctly
    cursor.read<uint8_t>();
  }
  {
    // Check that inserting at the beginning doesn't create empty buf
    RWPrivateCursor cursor(iobuf1.get());
    Cursor(iobuf1.get()).clone(cloned, 1);
    EXPECT_EQ(1, cloned->countChainElements());
    EXPECT_EQ(1, cloned->computeChainDataLength());

    cursor.insert(std::move(cloned));
    EXPECT_EQ(9, iobuf1->countChainElements());
    EXPECT_EQ(16, iobuf1->computeChainDataLength());
    // Check that nextBuf got set correctly
    cursor.read<uint8_t>();
  }
}

TEST(IOBuf, cloneWithEmptyBufAtStart) {
  folly::IOBufEqual eq;
  auto empty = IOBuf::create(0);
  auto hel = IOBuf::create(3);
  append(hel, "hel");
  auto lo = IOBuf::create(2);
  append(lo, "lo");

  auto iobuf = empty->clone();
  iobuf->prependChain(hel->clone());
  iobuf->prependChain(lo->clone());
  iobuf->prependChain(empty->clone());
  iobuf->prependChain(hel->clone());
  iobuf->prependChain(lo->clone());
  iobuf->prependChain(empty->clone());
  iobuf->prependChain(lo->clone());
  iobuf->prependChain(hel->clone());
  iobuf->prependChain(lo->clone());
  iobuf->prependChain(lo->clone());

  Cursor cursor(iobuf.get());
  std::unique_ptr<IOBuf> cloned;
  char data[3];
  cursor.pull(&data, 3);
  cursor.clone(cloned, 2);
  EXPECT_EQ(1, cloned->countChainElements());
  EXPECT_EQ(2, cloned->length());
  EXPECT_TRUE(eq(lo, cloned));

  cursor.pull(&data, 3);
  EXPECT_EQ("hel", std::string(data, sizeof(data)));

  cursor.skip(2);
  cursor.clone(cloned, 2);
  EXPECT_TRUE(eq(lo, cloned));

  std::string hello = cursor.readFixedString(5);
  cursor.clone(cloned, 2);
  EXPECT_TRUE(eq(lo, cloned));
}

TEST(IOBuf, Appender) {
  std::unique_ptr<IOBuf> head(IOBuf::create(10));
  append(head, "hello");

  Appender app(head.get(), 10);
  uint32_t cap = head->capacity();
  uint32_t len1 = app.length();
  EXPECT_EQ(cap - 5, len1);
  app.ensure(len1);  // won't grow
  EXPECT_EQ(len1, app.length());
  app.ensure(len1 + 1);  // will grow
  EXPECT_LE(len1 + 1, app.length());

  append(app, " world");
  EXPECT_EQ("hello world", toString(*head));
}

TEST(IOBuf, Printf) {
  IOBuf head(IOBuf::CREATE, 24);
  Appender app(&head, 32);

  app.printf("%s", "test");
  EXPECT_EQ(head.length(), 4);
  EXPECT_EQ(0, memcmp(head.data(), "test\0", 5));

  app.printf("%d%s %s%s %#x", 32, "this string is",
             "longer than our original allocation size,",
             "and will therefore require a new allocation", 0x12345678);
  // The tailroom should start with a nul byte now.
  EXPECT_GE(head.prev()->tailroom(), 1);
  EXPECT_EQ(0, *head.prev()->tail());

  EXPECT_EQ("test32this string is longer than our original "
            "allocation size,and will therefore require a "
            "new allocation 0x12345678",
            head.moveToFbString().toStdString());
}

TEST(IOBuf, Format) {
  IOBuf head(IOBuf::CREATE, 24);
  Appender app(&head, 32);

  format("{}", "test")(app);
  EXPECT_EQ(head.length(), 4);
  EXPECT_EQ(0, memcmp(head.data(), "test", 4));

  auto fmt = format("{}{} {}{} {:#x}",
                    32, "this string is",
                    "longer than our original allocation size,",
                    "and will therefore require a new allocation",
                    0x12345678);
  fmt(app);
  EXPECT_EQ("test32this string is longer than our original "
            "allocation size,and will therefore require a "
            "new allocation 0x12345678",
            head.moveToFbString().toStdString());
}

TEST(IOBuf, QueueAppender) {
  folly::IOBufQueue queue;

  // Allocate 100 bytes at once, but don't grow past 1024
  QueueAppender app(&queue, 100);
  size_t n = 1024 / sizeof(uint32_t);
  for (uint32_t i = 0; i < n; ++i) {
    app.writeBE(i);
  }

  // There must be a goodMallocSize between 100 and 1024...
  EXPECT_LT(1, queue.front()->countChainElements());
  const IOBuf* buf = queue.front();
  do {
    EXPECT_LE(100, buf->capacity());
    buf = buf->next();
  } while (buf != queue.front());

  Cursor cursor(queue.front());
  for (uint32_t i = 0; i < n; ++i) {
    EXPECT_EQ(i, cursor.readBE<uint32_t>());
  }

  EXPECT_THROW({cursor.readBE<uint32_t>();}, std::out_of_range);
}

TEST(IOBuf, CursorOperators) {
  // Test operators on a single-item chain
  {
    std::unique_ptr<IOBuf> chain1(IOBuf::create(20));
    chain1->append(10);

    Cursor curs1(chain1.get());
    EXPECT_EQ(0, curs1 - chain1.get());
    EXPECT_FALSE(curs1.isAtEnd());
    curs1.skip(3);
    EXPECT_EQ(3, curs1 - chain1.get());
    EXPECT_FALSE(curs1.isAtEnd());
    curs1.skip(7);
    EXPECT_EQ(10, curs1 - chain1.get());
    EXPECT_TRUE(curs1.isAtEnd());

    Cursor curs2(chain1.get());
    EXPECT_EQ(0, curs2 - chain1.get());
    EXPECT_EQ(10, curs1 - curs2);
    EXPECT_THROW(curs2 - curs1, std::out_of_range);
  }

  // Test cross-chain operations
  {
    std::unique_ptr<IOBuf> chain1(IOBuf::create(20));
    chain1->append(10);
    std::unique_ptr<IOBuf> chain2 = chain1->clone();

    Cursor curs1(chain1.get());
    Cursor curs2(chain2.get());
    EXPECT_THROW(curs1 - curs2, std::out_of_range);
    EXPECT_THROW(curs1 - chain2.get(), std::out_of_range);
  }

  // Test operations on multi-item chains
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(20));
    chain->append(10);
    chain->appendChain(chain->clone());
    EXPECT_EQ(20, chain->computeChainDataLength());

    Cursor curs1(chain.get());
    curs1.skip(5);
    Cursor curs2(chain.get());
    curs2.skip(3);
    EXPECT_EQ(2, curs1 - curs2);
    EXPECT_EQ(5, curs1 - chain.get());
    EXPECT_THROW(curs2 - curs1, std::out_of_range);

    curs1.skip(7);
    EXPECT_EQ(9, curs1 - curs2);
    EXPECT_EQ(12, curs1 - chain.get());
    EXPECT_THROW(curs2 - curs1, std::out_of_range);

    curs2.skip(7);
    EXPECT_EQ(2, curs1 - curs2);
    EXPECT_THROW(curs2 - curs1, std::out_of_range);
  }

  // Test isAtEnd() with empty buffers at the end of a chain
  {
    auto iobuf1 = IOBuf::create(20);
    iobuf1->append(15);
    iobuf1->trimStart(5);

    Cursor c(iobuf1.get());
    EXPECT_FALSE(c.isAtEnd());
    c.skip(10);
    EXPECT_TRUE(c.isAtEnd());

    iobuf1->prependChain(IOBuf::create(10));
    iobuf1->prependChain(IOBuf::create(10));
    EXPECT_TRUE(c.isAtEnd());
    iobuf1->prev()->append(5);
    EXPECT_FALSE(c.isAtEnd());
    c.skip(5);
    EXPECT_TRUE(c.isAtEnd());
  }

  // Test canAdvance with a chain of items
  {
    auto chain = IOBuf::create(10);
    chain->append(10);
    chain->appendChain(chain->clone());
    EXPECT_EQ(2, chain->countChainElements());
    EXPECT_EQ(20, chain->computeChainDataLength());

    Cursor c(chain.get());
    for (size_t i = 0; i <= 20; ++i) {
      EXPECT_TRUE(c.canAdvance(i));
    }
    EXPECT_FALSE(c.canAdvance(21));
    c.skip(10);
    EXPECT_TRUE(c.canAdvance(10));
    EXPECT_FALSE(c.canAdvance(11));
  }
}

TEST(IOBuf, StringOperations) {
  // Test a single buffer with two null-terminated strings and an extra uint8_t
  // at the end
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(16));
    Appender app(chain.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello\0world\0\x01"), 13);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readTerminatedString().c_str());
    EXPECT_STREQ("world", curs.readTerminatedString().c_str());
    EXPECT_EQ(1, curs.read<uint8_t>());
  }

  // Test multiple buffers where the first is empty and the string starts in
  // the second buffer.
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(IOBuf::create(12));
    Appender app(chain.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello world", curs.readTerminatedString().c_str());
  }

  // Test multiple buffers with a single null-terminated string spanning them
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(IOBuf::create(8));
    chain->append(8);
    chain->next()->append(4);
    RWPrivateCursor rwc(chain.get());
    rwc.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello world", curs.readTerminatedString().c_str());
  }

  // Test a reading a null-terminated string that's longer than the maximum
  // allowable length
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(16));
    Appender app(chain.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello world\0"), 12);

    Cursor curs(chain.get());
    EXPECT_THROW(curs.readTerminatedString('\0', 5), std::length_error);
  }

  // Test reading a null-terminated string from a chain with an empty buffer at
  // the front
  {
    std::unique_ptr<IOBuf> buf(IOBuf::create(8));
    Appender app(buf.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello\0"), 6);
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(std::move(buf));

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readTerminatedString().c_str());
  }

  // Test reading a null-terminated string from a chain that doesn't contain the
  // terminator
  {
    std::unique_ptr<IOBuf> buf(IOBuf::create(8));
    Appender app(buf.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello"), 5);
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(std::move(buf));

    Cursor curs(chain.get());
    EXPECT_THROW(curs.readTerminatedString(),
                 std::out_of_range);
  }

  // Test reading a null-terminated string past the maximum length
  {
    std::unique_ptr<IOBuf> buf(IOBuf::create(8));
    Appender app(buf.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello\0"), 6);
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(std::move(buf));

    Cursor curs(chain.get());
    EXPECT_THROW(curs.readTerminatedString('\0', 3),
                 std::length_error);
  }

  // Test reading a two fixed-length strings from a single buffer with an extra
  // uint8_t at the end
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(16));
    Appender app(chain.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("helloworld\x01"), 11);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readFixedString(5).c_str());
    EXPECT_STREQ("world", curs.readFixedString(5).c_str());
    EXPECT_EQ(1, curs.read<uint8_t>());
  }

  // Test multiple buffers where the first is empty and a fixed-length string
  // starts in the second buffer.
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(IOBuf::create(16));
    Appender app(chain.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello world"), 11);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello world", curs.readFixedString(11).c_str());
  }

  // Test multiple buffers with a single fixed-length string spanning them
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(IOBuf::create(8));
    chain->append(7);
    chain->next()->append(4);
    RWPrivateCursor rwc(chain.get());
    rwc.push(reinterpret_cast<const uint8_t*>("hello world"), 11);

    Cursor curs(chain.get());
    EXPECT_STREQ("hello world", curs.readFixedString(11).c_str());
  }

  // Test reading a fixed-length string from a chain with an empty buffer at
  // the front
  {
    std::unique_ptr<IOBuf> buf(IOBuf::create(8));
    Appender app(buf.get(), 0);
    app.push(reinterpret_cast<const uint8_t*>("hello"), 5);
    std::unique_ptr<IOBuf> chain(IOBuf::create(8));
    chain->prependChain(std::move(buf));

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readFixedString(5).c_str());
  }
}

TEST(IOBuf, ReadWhileTrue) {
  auto isAlpha = [](uint8_t ch) {
    return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
  };
  auto isDigit = [](uint8_t ch) { return (ch >= '0' && ch <= '9'); };

  // Test reading alternating alphabetic and numeric strings
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(32));
    Appender app(chain.get(), 0);
    app.push(StringPiece("hello123world456"));

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
    EXPECT_STREQ("123", curs.readWhile(isDigit).c_str());
    EXPECT_STREQ("world", curs.readWhile(isAlpha).c_str());
    EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
    EXPECT_TRUE(curs.isAtEnd());
  }

  // The same, but also use skipWhile()
  {
    std::unique_ptr<IOBuf> chain(IOBuf::create(16));
    Appender app(chain.get(), 0);
    app.push(StringPiece("hello123world456"));

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
    curs.skipWhile(isDigit);
    curs.skipWhile(isAlpha);
    EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
    EXPECT_TRUE(curs.isAtEnd());
  }

  // Test readWhile() using data split across multiple buffers,
  // including some empty buffers in the middle of the chain.
  {
    std::unique_ptr<IOBuf> chain;

    // First element in the chain has "he"
    auto buf = IOBuf::create(40);
    Appender app(buf.get(), 0);
    app.push(StringPiece("he"));
    chain = std::move(buf);

    // The second element has "ll", after 10 bytes of headroom
    buf = IOBuf::create(40);
    buf->advance(10);
    app = Appender{buf.get(), 0};
    app.push(StringPiece("ll"));
    chain->prependChain(std::move(buf));

    // The third element is empty
    buf = IOBuf::create(40);
    buf->advance(15);
    chain->prependChain(std::move(buf));

    // The fourth element has "o12"
    buf = IOBuf::create(40);
    buf->advance(37);
    app = Appender{buf.get(), 0};
    app.push(StringPiece("o12"));
    chain->prependChain(std::move(buf));

    // The fifth element has "3"
    buf = IOBuf::create(40);
    app = Appender{buf.get(), 0};
    app.push(StringPiece("3"));
    chain->prependChain(std::move(buf));

    // The sixth element is empty
    buf = IOBuf::create(40);
    chain->prependChain(std::move(buf));

    // The seventh element has "world456"
    buf = IOBuf::create(40);
    app = Appender{buf.get(), 0};
    app.push(StringPiece("world456"));
    chain->prependChain(std::move(buf));

    // The eighth element is empty
    buf = IOBuf::create(40);
    chain->prependChain(std::move(buf));

    Cursor curs(chain.get());
    EXPECT_STREQ("hello", curs.readWhile(isAlpha).c_str());
    EXPECT_STREQ("123", curs.readWhile(isDigit).c_str());
    EXPECT_STREQ("world", curs.readWhile(isAlpha).c_str());
    EXPECT_STREQ("456", curs.readWhile(isDigit).c_str());
    EXPECT_TRUE(curs.isAtEnd());
  }
}

redpajama_set_name: RedPajamaGithub


text:
def write_file(filename,content,log=nil)
  connection = Fog::Storage.new({
        :provider                 => 'AWS',
        :aws_access_key_id        => ENV['AWS_ACCESS_KEY_ID'],
        :aws_secret_access_key    => ENV['AWS_SECRET_ACCESS_KEY']
      })
  dirname=ENV['AWS_S3_BUCKET']
  # assumes directory exists
  directory=connection.directories.get(dirname)
  file=directory.files.new(:key => filename)
  file=directory.files.create(:key=>filename,:body=>content)
end

def dump_hashes(hashes,filename,skip_cols=nil,log=nil,first=true)
  return nil if hashes.nil? or hashes.size==0
  csv_string=CSV.generate do |csv|
    if first
      columns=[]
      hashes[0].keys.each do |k|
        if skip_cols.nil? or not (skip_cols.include?(k.to_s))
          k=k.to_s.gsub(/\_/,".") # _ to .
          k=k.to_s.gsub(/\@/,"")  # @ removed
          columns << k
        end
      end
      csv << columns # adds the attributes name on the first line
    end
    hashes.each do |hash|
      row=[]
      hash.keys.each do |k|
        if skip_cols.nil? or not (skip_cols.include? (k.to_s))
          row << hash[k]
        end
      end
      csv << row
    end
  end
  if ENV['AWS_S3_BUCKET'] and ENV['AWS_S3_BUCKET'].size>0
    write_file(filename,csv_string,log)
  else
    File.open(filename, 'w') { |file| file.write(csv_string) }
  end
end

def dump_csv(objects,filename=nil,skip_cols=nil,log=nil,first=true)
  return nil if objects.nil?
  log.debug "Writing CSV of #{objects.size} of object #{objects[0].inspect} to #{filename}"
  hashes=[]
  objects.each do |o|
    hashes << Hash[o.instance_variables.map { |name| [name, o.instance_variable_get(name)] } ]
  end
  dump_hashes(hashes,filename,skip_cols,log,first)
end

# Canvas' various API calls are paginated.
# Invoke them in paginated form repeatedly to fully consume
def page_req(url,per_page=50,log=nil)
  full_result=[]
  done=false
  page=1
  if url=~/\?/
    full_url=url+"&per_page=#{per_page}&page=#{page}"
  else
    full_url=url+"?per_page=#{per_page}&page=#{page}"
  end
  while not done do
    if url=~/\?/
      full_url=url+"&per_page=#{per_page}&page=#{page}"
    else
      full_url=url+"?per_page=#{per_page}&page=#{page}"
    end
    result=[]
    begin
      response=open(full_url).read
    rescue
      log.error "Can't access #{full_url}" if log
    end
    if response
      result=JSON.parse(response)
      full_result=full_result.concat result
    end
    break if result.size<per_page
    page+=1
  end
  full_result
end

##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

  client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(
      base_url: OOB_URI)
    puts "Open the following URL in the browser and enter the " +
         "resulting code after authorization"
    puts url
    code = STDIN.gets

    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials
end

# TODO: make this work so it can work on Heroku
# this approach to getting credentials has not been tested
def authorize_from_service_key(scope,client)
=begin
TODO: base64 encode this

{
  "type": "service_account",
  "project_id": "root-rock-123619",
  "private_key_id": "key id",
  "private_key": "text"
  "client_email": "email of service account",
  "client_id": "105190210387870068342",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/oneroster%40root-rock-123619.iam.gserviceaccount.com"
}

=end

  client_id = Google::Auth::ClientId.from_hash(base64encodes)
  token_store = Google::Auth::Stores::FileTokenStore.new(
    :file => '/path/to/tokens.yaml')
  authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)
end

def gdrive_login(key,access_token)
  session = GoogleDrive.login_with_oauth(access_token)
  sheet=session.spreadsheet_by_key(key).worksheets[0]
end

# Google's  API calls are paginated.
# Invoke them in paginated form repeatedly to fully consume
def google_page_req(url,per_page=50,log=nil)
  full_result=[]
  done=false
  page=1
  if url=~/\?/
    full_url=url+"&pageSize=#{per_page}&pageToken=#{page}"
  else
    full_url=url+"?pageSize=#{per_page}&pageToken=#{page}"
  end
  while not done do
    if url=~/\?/
      full_url=url+"&pageSize=#{per_page}&pageToken=#{page}"
    else
      full_url=url+"?pageSize=#{per_page}&pageToken=#{page}"
    end
    result=[]
    begin
      response=open(full_url).read
    rescue Exception=>e
      log.error "Can't access #{full_url}: #{e}" if log
    end
    if response
      result=JSON.parse(response)
      full_result=full_result.concat result
    end
    break if result.size<per_page
    page+=1
  end
  full_result
end

# read filename from specified AWS_S3_BUCKET and return contents as string
def read_file(filename,log=nil)
  connection = Fog::Storage.new({
        :provider                 => 'AWS',
        :aws_access_key_id        => ENV['AWS_ACCESS_KEY_ID'],
        :aws_secret_access_key    => ENV['AWS_SECRET_ACCESS_KEY']
      })
  dirname=ENV['AWS_S3_BUCKET']
  dirname||="oneroster"
  directory=connection.directories.get(dirname)
  file = directory.files.get(filename)
  result=file.body
end

# return a parsed CSV from specified S3 filename on OneRoster S3 bucket
def read(filename,encoding=nil,log=nil)
  data = []
  begin
    read_file(filename,log) do |f|
      if encoding
        csv_string = f.read.encode!("UTF-8", "windows-1251", invalid: :replace)
      else
        csv_string=f.read
      end
      data = CSV.parse csv_string
    end
  rescue Exception=>e
    log.error "Failed to read from #{url}: #{e}" if log
    return nil
  end
  data
end

# Look up school by name in NCES database to retrieve NCES ID based on first 16 chars
# A bit error prone. Best to not use it if possible to get NCES onto Canvas itself
def lookup_school(school,all_schools,name_field=1,len=16,log)
  log.info "Looking up #{school} in field #{name_field}" if log
  all_schools.each do |a|
    return a[0] if a[name_field] and (a[name_field][0..len]==school.upcase[0..len])
  end
  return nil
end


text:
package org.stagemonitor.core.configuration.source;

import java.util.Map;

/**
 * This configuration source get its values from the operating system's environment variables.
 *

 * Because of the naming restrictions/conventions of environment variables, all dots ('.') are replaced with underscores
 * and all letters are converted to upper case.
 *

 * Example: To set the configuration key stagemonitor.active, the environment variable has to be
 * STAGEMONITOR_ACTIVE
 */
public class EnvironmentVariableConfigurationSource extends AbstractConfigurationSource {

	private Map<String, String> env;

	public EnvironmentVariableConfigurationSource() {
		reload();
	}

	public EnvironmentVariableConfigurationSource(Map<String, String> env) {
		this.env = env;
	}

	/**
	 * Returns the configuration value from the the operating system's environment variables.
	 *

	 * Because of the naming restrictions/conventions of environment variables, all dots ('.') are replaced with underscores
	 * and all letters are converted to upper case.
	 *

	 * Example: To set the configuration key stagemonitor.active, the environment variable has to be
	 * STAGEMONITOR_ACTIVE
	 *
	 * @param key the property key
	 * @return the value
	 */
	@Override
	public String getValue(String key) {
		return env.get(key.replace('.', '_').toUpperCase());
	}

	@Override
	public String getName() {
		return "Environment Variables";
	}

	@Override
	public void reload() {
		this.env = System.getenv();
	}
}


text:
package net.java.sip.communicator.plugin.busylampfield;

import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.protocol.*;

import java.util.*;

/**
 * The BLF source contact.
 * @author Damian Minkov
 */
public class BLFSourceContact
    extends GenericSourceContact
{
    private final OperationSetTelephonyBLF.Line line;

    /**
     * Initializes a new <tt>AddrBookSourceContact</tt> instance.
     *
     * @param contactSource  the <tt>ContactSourceService</tt> which is creating
     *                       the new instance
     */
    public BLFSourceContact(ContactSourceService contactSource,
                            OperationSetTelephonyBLF.Line line)
    {
        super(contactSource,
            line.getName() != null ? line.getName() : line.getAddress(),
            new ArrayList<ContactDetail>());

        this.line = line;
    }

    /**
     * Returns the line displayed.
     * @return
     */
    public OperationSetTelephonyBLF.Line getLine()
    {
        return line;
    }
}


text:
title: Generator
localeTitle: Генератор
---
## Генератор

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/generator/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Дополнительная информация:


text:
drop index ACT_IDX_BYTEARRAY_ROOT_PI;
drop index ACT_IDX_BYTEARRAY_RM_TIME;
drop index ACT_IDX_EXEC_ROOT_PI;
drop index ACT_IDX_EXEC_BUSKEY;
drop index ACT_IDX_TASK_CREATE;
drop index ACT_IDX_TASK_LAST_UPDATED;
drop index ACT_IDX_TASK_ASSIGNEE;
drop index ACT_IDX_TASK_OWNER;
drop index ACT_IDX_IDENT_LNK_USER;
drop index ACT_IDX_IDENT_LNK_GROUP;
drop index ACT_IDX_VARIABLE_TASK_ID;
drop index ACT_IDX_VARIABLE_TASK_NAME_TYPE;
drop index ACT_IDX_INC_CONFIGURATION;
drop index ACT_IDX_JOB_PROCINST;
drop index ACT_IDX_AUTH_GROUP_ID;

alter table ACT_GE_BYTEARRAY
    drop constraint ACT_FK_BYTEARR_DEPL;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PROCINST;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PARENT;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_SUPER;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PROCDEF;

alter table ACT_RU_IDENTITYLINK
    drop constraint ACT_FK_TSKASS_TASK;

alter table ACT_RU_IDENTITYLINK
    drop constraint ACT_FK_ATHRZ_PROCEDEF;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_EXE;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_PROCINST;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_PROCDEF;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_EXE;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_PROCINST;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_BYTEARRAY;

alter table ACT_RU_JOB
    drop constraint ACT_FK_JOB_EXCEPTION;

alter table ACT_RU_EVENT_SUBSCR
    drop constraint ACT_FK_EVENT_EXEC;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_EXE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_PROCINST;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_PROCDEF;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_CAUSE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_RCAUSE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_JOB_DEF;

alter table ACT_RU_AUTHORIZATION
    drop constraint ACT_UNIQ_AUTH_GROUP;

alter table ACT_RU_AUTHORIZATION
    drop constraint ACT_UNIQ_AUTH_USER;

alter table ACT_RU_VARIABLE
    drop constraint ACT_UNIQ_VARIABLE;

alter table ACT_RU_EXT_TASK
    drop constraint ACT_FK_EXT_TASK_EXE;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_SEED_JOB_DEF;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_MONITOR_JOB_DEF;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_JOB_DEF;

alter table ACT_RU_EXT_TASK
    drop CONSTRAINT ACT_FK_EXT_TASK_ERROR_DETAILS;

alter table ACT_RU_VARIABLE
    drop CONSTRAINT ACT_FK_VAR_BATCH;

drop index ACT_IDX_EVENT_SUBSCR_CONFIG_;
drop index ACT_IDX_ATHRZ_PROCEDEF;

-- indexes for deadlock problems - https://app.camunda.com/jira/browse/CAM-2567
drop index ACT_IDX_INC_CAUSEINCID;
drop index ACT_IDX_INC_EXID;
drop index ACT_IDX_INC_PROCDEFID;
drop index ACT_IDX_INC_PROCINSTID;
drop index ACT_IDX_INC_ROOTCAUSEINCID;
drop index ACT_IDX_INC_JOB_DEF;

-- new metric milliseconds column
DROP INDEX ACT_IDX_METER_LOG_MS;
DROP INDEX ACT_IDX_METER_LOG_NAME_MS;
DROP INDEX ACT_IDX_METER_LOG_REPORT;

-- old metric timestamp column
DROP INDEX ACT_IDX_METER_LOG_TIME;
DROP INDEX ACT_IDX_METER_LOG;

-- task metric timestamp column
drop index ACT_IDX_TASK_METER_LOG_TIME;

drop index ACT_IDX_AUTH_RESOURCE_ID;
drop index ACT_IDX_EXT_TASK_TOPIC;
drop index ACT_IDX_EXT_TASK_EXEC;

drop index ACT_IDX_BYTEARRAY_NAME;
drop index ACT_IDX_DEPLOYMENT_NAME;
drop index ACT_IDX_JOBDEF_PROC_DEF_ID;
drop index ACT_IDX_JOB_HANDLER_TYPE;
drop index ACT_IDX_EVENT_SUBSCR_EVT_NAME;
drop index ACT_IDX_PROCDEF_DEPLOYMENT_ID;

drop index ACT_IDX_EXT_TASK_TENANT_ID;
drop index ACT_IDX_EXT_TASK_PRIORITY;
drop index ACT_IDX_EXT_TASK_ERR_DETAILS;
drop index ACT_IDX_INC_TENANT_ID;
drop index ACT_IDX_JOBDEF_TENANT_ID;
drop index ACT_IDX_JOB_TENANT_ID;
drop index ACT_IDX_EVENT_SUBSCR_TENANT_ID;
drop index ACT_IDX_VARIABLE_TENANT_ID;
drop index ACT_IDX_TASK_TENANT_ID;
drop index ACT_IDX_EXEC_TENANT_ID;
drop index ACT_IDX_PROCDEF_TENANT_ID;
drop index ACT_IDX_DEPLOYMENT_TENANT_ID;

drop index ACT_IDX_JOB_JOB_DEF_ID;
drop index ACT_IDX_BATCH_SEED_JOB_DEF;
drop index ACT_IDX_BATCH_MONITOR_JOB_DEF;
drop index ACT_IDX_BATCH_JOB_DEF;

drop index ACT_IDX_PROCDEF_VER_TAG;

drop index ACT_IDX_JOB_EXECUTION_ID;
drop index ACT_IDX_JOB_HANDLER;

drop index ACT_IDX_AUTH_ROOT_PI;
drop index ACT_IDX_AUTH_RM_TIME;

drop index ACT_IDX_BATCH_ID;

drop table ACT_GE_PROPERTY if exists;
drop table ACT_GE_BYTEARRAY if exists;
drop table ACT_RE_DEPLOYMENT if exists;
drop table ACT_RU_EXECUTION if exists;
drop table ACT_RU_JOB if exists;
drop table ACT_RU_JOBDEF if exists;
drop table ACT_RE_PROCDEF if exists;
drop table ACT_RE_CAMFORMDEF if exists;
drop table ACT_RU_TASK if exists;
drop table ACT_RU_IDENTITYLINK if exists;
drop table ACT_RU_VARIABLE if exists;
drop table ACT_RU_EVENT_SUBSCR if exists;
drop table ACT_RU_INCIDENT if exists;
drop table ACT_RU_AUTHORIZATION if exists;
drop table ACT_RU_FILTER if exists;
drop table ACT_RU_METER_LOG if exists;
drop table ACT_RU_TASK_METER_LOG if exists;
drop table ACT_RU_EXT_TASK if exists;
drop table ACT_RU_BATCH if exists;
drop table ACT_GE_SCHEMA_LOG if exists;


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Annotation to annotate list of static headers sent to a REST endpoint.
 *
 *
Headers are comma separated strings, with each in the format of "header name: header value1,header value2".

 *
 *
Examples:

 *
 *

 * {@literal @}Headers({ "Content-Type: application/json; charset=utf-8", "accept-language: en-US" })
 * {@literal @}POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft
 * .CustomerInsights/hubs/{hubName}/images/getEntityTypeImageUploadUrl")
 *  void getUploadUrlForEntityType(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String
 *  hubName, @Path("subscriptionId") String subscriptionId, @Body GetImageUploadUrlInputInner parameters);

 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface Headers {
    /**
     * List of static headers.
     * @return List of static headers.
     */
    String[] value();
}


text:
package resolvers

import (
	"github.com/enmasseproject/enmasse/pkg/apis/enmasse/v1beta1"
	"github.com/enmasseproject/enmasse/pkg/consolegraphql"
	"github.com/google/uuid"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
)

func getMetric(name string, metrics []*consolegraphql.Metric) *consolegraphql.Metric {
	for _, m := range metrics {
		if m.Name == name {
			return m
		}
	}
	return nil
}

func createAddressSpace(addressspace, namespace string) *consolegraphql.AddressSpaceHolder {
	return &consolegraphql.AddressSpaceHolder{
		AddressSpace: v1beta1.AddressSpace{
			TypeMeta: metav1.TypeMeta{
				Kind: "AddressSpace",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name:      addressspace,
				Namespace: namespace,
				UID:       types.UID(uuid.New().String()),
			},
		},
	}
}

func createConnection(host, namespace, addressspace string, metrics ...*consolegraphql.Metric) *consolegraphql.Connection {
	return &consolegraphql.Connection{
		TypeMeta: metav1.TypeMeta{
			Kind: "Connection",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      host,
			Namespace: namespace,
			UID:       types.UID(uuid.New().String()),
		},
		Spec: consolegraphql.ConnectionSpec{
			AddressSpace: addressspace,
		},
		Metrics: metrics,
	}
}

type addressHolderOption func(*consolegraphql.AddressHolder)

func withAddressAnnotation(name, value string) addressHolderOption {
	return func(ah *consolegraphql.AddressHolder) {

		if ah.Annotations == nil {
			ah.Annotations = make(map[string]string)
		}
		ah.Annotations[name] = value
	}
}

func withAddressMetrics(metrics ...*consolegraphql.Metric) addressHolderOption {
	return func(ah *consolegraphql.AddressHolder) {
		if ah.Metrics == nil {
			ah.Metrics = metrics
		} else {
			ah.Metrics = append(ah.Metrics, metrics...)
		}
	}
}

func withAddress(address string) addressHolderOption {
	return func(ah *consolegraphql.AddressHolder) {
		ah.Spec.Address = address
	}
}

func createAddress(namespace, name string, addressHolderOptions ...addressHolderOption) *consolegraphql.AddressHolder {
	ah := &consolegraphql.AddressHolder{
		Address: v1beta1.Address{
			TypeMeta: metav1.TypeMeta{
				Kind: "Address",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name:      name,
				Namespace: namespace,
				UID:       types.UID(uuid.New().String()),
			},
		},
	}

	for _, holderOptions := range addressHolderOptions {
		holderOptions(ah)
	}
	return ah
}


text:
package com.google.caliper.runner.worker;

import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.Map;

/** A simple representation of a command that can be run to start a process on a device. */
@AutoValue
public abstract class Command {

  /** Returns a new builder for creating {@link Command} objects. */
  public static Builder builder() {
    return new AutoValue_Command.Builder();
  }

  /**
   * Returns a map of key-value pairs that should be added to the environment when executing this
   * command.
   */
  public abstract ImmutableMap<String, String> environment();

  /** Returns the full list of arguments that make up this command, including the binary to run. */
  public abstract ImmutableList<String> arguments();

  private static final Joiner SPACE_JOINER = Joiner.on(' ');

  /**
   * Returns the full list of arguments that make up this command, including the binary to run, as a
   * single string with a space between each argument.
   */
  public final String argumentsString() {
    return SPACE_JOINER.join(arguments());
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(Command.class.getSimpleName())
        .add("environment", environment())
        .add("arguments", argumentsString())
        .toString();
  }

  /** Builder for creating {@link Command} objects. */
  @AutoValue.Builder
  public abstract static class Builder {

    /** Adds the given argument to the command. */
    public final Builder addArgument(Object arg) {
      argumentsBuilder().add(arg.toString());
      return this;
    }

    /** Adds the given arguments to the command. */
    public final Builder addArguments(Iterable<?> args) {
      for (Object arg : args) {
        argumentsBuilder().add(arg.toString());
      }
      return this;
    }

    /** Returns a builder that can be used for adding arguments to the command. */
    abstract ImmutableList.Builder<String> argumentsBuilder();

    /** Puts the given environment variable into the environment for the command. */
    public final Builder putEnvironmentVariable(String key, String value) {
      environmentBuilder().put(key, value);
      return this;
    }

    /** Puts the given variables into the environment for the command. */
    public final Builder putAllEnvironmentVariables(Map<String, String> variables) {
      environmentBuilder().putAll(variables);
      return this;
    }

    /** Returns a builder that can be used for adding entries to the environment for the command. */
    abstract ImmutableMap.Builder<String, String> environmentBuilder();

    /** Builds a new {@link Command}. */
    abstract Command build();
  }
}


text:
class Admin::BaseController < ApplicationController
  before_filter :verify_admin_user

  layout 'admin'

private

  def verify_admin_user
    redirect_to("/home") unless current_user.admin?
  end

end


text:
package git

import (
	"errors"
	"io"
	"regexp"
	"strings"

	git "gopkg.in/src-d/go-git.v4"
)

// Client has helpful functions to help deal with git.
type Client struct {
	Path string
}

// TagExists confirms if a given tag exists in the git repo.
func (c *Client) TagExists(tag string) (bool, error) {
	repo, err := git.PlainOpen(c.Path)
	if err != nil {
		return false, err
	}

	_, err = repo.Tag(tag)
	if err != nil {
		return false, err
	}

	return true, nil
}

// Changelog returns an array of changes since the given tag.
func (c *Client) Changelog(sinceTag string) ([]string, error) {
	repo, err := git.PlainOpen(c.Path)
	if err != nil {
		return nil, err
	}

	tag, err := repo.Tag(sinceTag)
	if err != nil {
		return nil, err
	}

	tagobj, err := repo.TagObject(tag.Hash())
	if err != nil {
		return nil, err
	}

	commit, err := tagobj.Commit()
	if err != nil {
		return nil, err
	}

	cIter, err := repo.Log(&git.LogOptions{Order: git.LogOrderCommitterTime})
	if err != nil {
		return nil, err
	}

	var result []string

	foundTagCommit := false
	for c, err := cIter.Next(); err != io.EOF; c, err = cIter.Next() {
		if c.Hash == commit.Hash {
			foundTagCommit = true
			break
		}
		if isMergeCommit(c.Message) {
			change := formatCommitMessage(strings.TrimSpace(c.Message))
			result = append(result, change)
		}

	}

	if !foundTagCommit {
		return nil, errors.New("Tag not found in this branch")
	}

	return result, nil
}

func isMergeCommit(msg string) bool {
	return strings.HasPrefix(strings.TrimSpace(msg), "Merge pull request")
}

func formatCommitMessage(msg string) string {
	re := regexp.MustCompile("Merge pull request ([#0-9]*)")
	matches := re.FindSubmatch([]byte(msg))
	if matches == nil {
		return ""
	}

	pullRequestNumber := string(matches[1])

	lines := strings.Split(msg, "\n")
	if len(lines) < 2 {
		return ""
	}

	commitMessage := lines[2]

	return pullRequestNumber + " " + commitMessage
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trav. Inst. Sci. Cherifien, Ser. Bot. 28: 37 (1963)

#### Original name
Puccinia brachypodii-phoenicoidis Guyot & Malençon

### Remarks
null


text:
module.exports = function(){
	console.log.apply(console,arguments);
}


text:
package client

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/version"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
	"github.com/golang/glog"
)

// Interface holds the methods for clients of Kubenetes,
// an interface to allow mock testing.
// TODO: split this up by resource?
// TODO: these should return/take pointers.
type Interface interface {
	ListPods(selector labels.Selector) (api.PodList, error)
	GetPod(name string) (api.Pod, error)
	DeletePod(name string) error
	CreatePod(api.Pod) (api.Pod, error)
	UpdatePod(api.Pod) (api.Pod, error)

	ListReplicationControllers(selector labels.Selector) (api.ReplicationControllerList, error)
	GetReplicationController(name string) (api.ReplicationController, error)
	CreateReplicationController(api.ReplicationController) (api.ReplicationController, error)
	UpdateReplicationController(api.ReplicationController) (api.ReplicationController, error)
	DeleteReplicationController(string) error
	WatchReplicationControllers(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error)

	GetService(name string) (api.Service, error)
	CreateService(api.Service) (api.Service, error)
	UpdateService(api.Service) (api.Service, error)
	DeleteService(string) error
}

// StatusErr might get returned from an api call if your request is still being processed
// and hence the expected return data is not available yet.
type StatusErr struct {
	Status api.Status
}

func (s *StatusErr) Error() string {
	return fmt.Sprintf("Status: %v (%#v)", s.Status.Status, s.Status)
}

// AuthInfo is used to store authorization information
type AuthInfo struct {
	User     string
	Password string
}

// Client is the actual implementation of a Kubernetes client.
// Host is the http://... base for the URL
type Client struct {
	host       string
	auth       *AuthInfo
	httpClient *http.Client
	Sync       bool
	PollPeriod time.Duration
	Timeout    time.Duration
}

// New creates a new client object.
func New(host string, auth *AuthInfo) *Client {
	return &Client{
		auth: auth,
		host: host,
		httpClient: &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		},
		Sync:       false,
		PollPeriod: time.Second * 2,
		Timeout:    time.Second * 20,
	}
}

// Execute a request, adds authentication (if auth != nil), and HTTPS cert ignoring.
func (c *Client) doRequest(request *http.Request) ([]byte, error) {
	if c.auth != nil {
		request.SetBasicAuth(c.auth.User, c.auth.Password)
	}
	response, err := c.httpClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return body, err
	}

	// Did the server give us a status response?
	isStatusResponse := false
	var status api.Status
	if err := api.DecodeInto(body, &status); err == nil && status.Status != "" {
		isStatusResponse = true
	}

	switch {
	case response.StatusCode == http.StatusConflict:
		// Return error given by server, if there was one.
		if isStatusResponse {
			return nil, &StatusErr{status}
		}
		fallthrough
	case response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPartialContent:
		return nil, fmt.Errorf("request [%#v] failed (%d) %s: %s", request, response.StatusCode, response.Status, string(body))
	}

	// If the server gave us a status back, look at what it was.
	if isStatusResponse && status.Status != api.StatusSuccess {
		// "Working" requests need to be handled specially.
		// "Failed" requests are clearly just an error and it makes sense to return them as such.
		return nil, &StatusErr{status}
	}
	return body, err
}

// Underlying base implementation of performing a request.
// method is the HTTP method (e.g. "GET")
// path is the path on the host to hit
// requestBody is the body of the request. Can be nil.
// target the interface to marshal the JSON response into.  Can be nil.
func (c *Client) rawRequest(method, path string, requestBody io.Reader, target interface{}) ([]byte, error) {
	request, err := http.NewRequest(method, c.makeURL(path), requestBody)
	if err != nil {
		return nil, err
	}
	body, err := c.doRequest(request)
	if err != nil {
		return body, err
	}
	if target != nil {
		err = api.DecodeInto(body, target)
	}
	if err != nil {
		glog.Infof("Failed to parse: %s\n", string(body))
		// FIXME: no need to return err here?
	}
	return body, err
}

func (c *Client) makeURL(path string) string {
	return c.host + "/api/v1beta1/" + path
}

// ListPods takes a selector, and returns the list of pods that match that selector
func (c *Client) ListPods(selector labels.Selector) (result api.PodList, err error) {
	err = c.Get().Path("pods").SelectorParam("labels", selector).Do().Into(&result)
	return
}

// GetPod takes the name of the pod, and returns the corresponding Pod object, and an error if it occurs
func (c *Client) GetPod(name string) (result api.Pod, err error) {
	err = c.Get().Path("pods").Path(name).Do().Into(&result)
	return
}

// DeletePod takes the name of the pod, and returns an error if one occurs
func (c *Client) DeletePod(name string) error {
	return c.Delete().Path("pods").Path(name).Do().Error()
}

// CreatePod takes the representation of a pod.  Returns the server's representation of the pod, and an error, if it occurs
func (c *Client) CreatePod(pod api.Pod) (result api.Pod, err error) {
	err = c.Post().Path("pods").Body(pod).Do().Into(&result)
	return
}

// UpdatePod takes the representation of a pod to update.  Returns the server's representation of the pod, and an error, if it occurs
func (c *Client) UpdatePod(pod api.Pod) (result api.Pod, err error) {
	if pod.ResourceVersion == 0 {
		err = fmt.Errorf("invalid update object, missing resource version: %v", pod)
		return
	}
	err = c.Put().Path("pods").Path(pod.ID).Body(pod).Do().Into(&result)
	return
}

// ListReplicationControllers takes a selector, and returns the list of replication controllers that match that selector
func (c *Client) ListReplicationControllers(selector labels.Selector) (result api.ReplicationControllerList, err error) {
	err = c.Get().Path("replicationControllers").SelectorParam("labels", selector).Do().Into(&result)
	return
}

// GetReplicationController returns information about a particular replication controller
func (c *Client) GetReplicationController(name string) (result api.ReplicationController, err error) {
	err = c.Get().Path("replicationControllers").Path(name).Do().Into(&result)
	return
}

// CreateReplicationController creates a new replication controller
func (c *Client) CreateReplicationController(controller api.ReplicationController) (result api.ReplicationController, err error) {
	err = c.Post().Path("replicationControllers").Body(controller).Do().Into(&result)
	return
}

// UpdateReplicationController updates an existing replication controller
func (c *Client) UpdateReplicationController(controller api.ReplicationController) (result api.ReplicationController, err error) {
	if controller.ResourceVersion == 0 {
		err = fmt.Errorf("invalid update object, missing resource version: %v", controller)
		return
	}
	err = c.Put().Path("replicationControllers").Path(controller.ID).Body(controller).Do().Into(&result)
	return
}

// DeleteReplicationController deletes an existing replication controller.
func (c *Client) DeleteReplicationController(name string) error {
	return c.Delete().Path("replicationControllers").Path(name).Do().Error()
}

// WatchReplicationControllers returns a watch.Interface that watches the requested controllers.
func (c *Client) WatchReplicationControllers(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error) {
	return c.Get().
		Path("watch").
		Path("replicationControllers").
		UintParam("resourceVersion", resourceVersion).
		SelectorParam("labels", label).
		SelectorParam("fields", field).
		Watch()
}

// GetService returns information about a particular service.
func (c *Client) GetService(name string) (result api.Service, err error) {
	err = c.Get().Path("services").Path(name).Do().Into(&result)
	return
}

// CreateService creates a new service.
func (c *Client) CreateService(svc api.Service) (result api.Service, err error) {
	err = c.Post().Path("services").Body(svc).Do().Into(&result)
	return
}

// UpdateService updates an existing service.
func (c *Client) UpdateService(svc api.Service) (result api.Service, err error) {
	if svc.ResourceVersion == 0 {
		err = fmt.Errorf("invalid update object, missing resource version: %v", svc)
		return
	}
	err = c.Put().Path("services").Path(svc.ID).Body(svc).Do().Into(&result)
	return
}

// DeleteService deletes an existing service.
func (c *Client) DeleteService(name string) error {
	return c.Delete().Path("services").Path(name).Do().Error()
}

// ServerVersion retrieves and parses the server's version.
func (c *Client) ServerVersion() (*version.Info, error) {
	body, err := c.Get().AbsPath("/version").Do().Raw()
	if err != nil {
		return nil, err
	}
	var info version.Info
	err = json.Unmarshal(body, &info)
	if err != nil {
		return nil, fmt.Errorf("Got '%s': %v", string(body), err)
	}
	return &info, nil
}


text:
namespace bard {
namespace events {

HeapFreeEvent::HeapFreeEvent(uint32_t stack_trace_id,
                             HANDLE trace_heap,
                             DWORD flags,
                             LPVOID trace_alloc,
                             BOOL trace_succeeded)
    : stack_trace_id_(stack_trace_id),
      trace_heap_(trace_heap),
      flags_(flags),
      trace_alloc_(trace_alloc),
      trace_succeeded_(trace_succeeded) {
}

bool HeapFreeEvent::Save(const EventInterface* const event,
                         core::OutArchive* out_archive) {
  DCHECK_NE(static_cast<EventInterface*>(nullptr), event);

  const HeapFreeEvent* derived_event =
      reinterpret_cast<const HeapFreeEvent*>(event);

  return out_archive->Save(derived_event->stack_trace_id_) &&
         out_archive->Save(
             reinterpret_cast<uintptr_t>(derived_event->trace_heap_)) &&
         out_archive->Save(derived_event->flags_) &&
         out_archive->Save(
             reinterpret_cast<uintptr_t>(derived_event->trace_alloc_)) &&
         out_archive->Save(derived_event->trace_succeeded_);
}

std::unique_ptr<HeapFreeEvent> HeapFreeEvent::Load(
    core::InArchive* in_archive) {
  uint32_t stack_trace_id = 0;
  uintptr_t trace_heap = 0;
  DWORD flags = 0;
  uintptr_t trace_alloc = 0;
  BOOL trace_succeeded = 0;
  if (in_archive->Load(&stack_trace_id) && in_archive->Load(&trace_heap) &&
      in_archive->Load(&flags) && in_archive->Load(&trace_alloc) &&
      in_archive->Load(&trace_succeeded)) {
    return std::unique_ptr<HeapFreeEvent>(new HeapFreeEvent(
        stack_trace_id, reinterpret_cast<HANDLE>(trace_heap), flags,
        reinterpret_cast<LPVOID>(trace_alloc), trace_succeeded));
  }
  return nullptr;
}

bool HeapFreeEvent::Play(void* backdrop) {
  DCHECK_NE(static_cast<void*>(nullptr), backdrop);

  using bard::backdrops::HeapBackdrop;
  HeapBackdrop* heap_backdrop = reinterpret_cast<HeapBackdrop*>(backdrop);

  HANDLE live_heap = INVALID_HANDLE_VALUE;
  LPVOID live_alloc = nullptr;

  if (!heap_backdrop->heap_map().GetLiveFromTrace(trace_heap_, &live_heap) ||
      !heap_backdrop->alloc_map().GetLiveFromTrace(trace_alloc_, &live_alloc)) {
    return false;
  }

  uint64_t timing = 0;
  BOOL live_succeeded =
      InvokeOnBackdrop(stack_trace_id_, &timing, heap_backdrop,
                       &HeapBackdrop::HeapFree, live_heap, flags_, live_alloc);

  if (live_succeeded != trace_succeeded_) {
    LOG(ERROR) << "HeapFree " << (live_succeeded ? "succeeded" : "failed")
               << " when it was supposed to "
               << (trace_succeeded_ ? "succeed" : "fail") << ".";
    return false;
  }

  if (live_succeeded &&
      !heap_backdrop->alloc_map().RemoveMapping(trace_alloc_, live_alloc)) {
    return false;
  }

  heap_backdrop->UpdateStats(type(), timing);

  return true;
}

bool HeapFreeEvent::Equals(const EventInterface* rhs) const {
  DCHECK_NE(static_cast<EventInterface*>(nullptr), rhs);

  if (rhs->type() != kHeapFreeEvent)
    return false;

  const auto e = reinterpret_cast<const HeapFreeEvent*>(rhs);
  if (stack_trace_id_ != e->stack_trace_id_ || trace_heap_ != e->trace_heap_ ||
      flags_ != e->flags_ || trace_alloc_ != e->trace_alloc_ ||
      trace_succeeded_ != e->trace_succeeded_) {
    return false;
  }

  return true;
}

}  // namespace events
}  // namespace bard


text:
/**
 */
package com.example.example.references.untyped.impl;

import com.example.example.references.untyped.OrderDetail1;
import com.example.example.references.untyped.UntypedPackage;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

/**
 *
 * An implementation of the model object 'Order Detail1'.
 *
 *

 * The following features are implemented:
 *

 *
{@link com.example.example.references.untyped.impl.OrderDetail1Impl#getCustomerAddress Customer Address}

 *
{@link com.example.example.references.untyped.impl.OrderDetail1Impl#getCustomerContact Customer Contact}

 *
{@link com.example.example.references.untyped.impl.OrderDetail1Impl#getCustomerName Customer Name}

 *
{@link com.example.example.references.untyped.impl.OrderDetail1Impl#getOrderID Order ID}

 *

 *

 *
 * @generated
 */
public class OrderDetail1Impl extends MinimalEObjectImpl.Container implements OrderDetail1 {
	/**
	 * The default value of the '{@link #getCustomerAddress() Customer Address}' attribute.
	 *
	 *
	 * @see #getCustomerAddress()
	 * @generated
	 * @ordered
	 */
	protected static final String CUSTOMER_ADDRESS_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getCustomerAddress() Customer Address}' attribute.
	 *
	 *
	 * @see #getCustomerAddress()
	 * @generated
	 * @ordered
	 */
	protected String customerAddress = CUSTOMER_ADDRESS_EDEFAULT;

	/**
	 * The default value of the '{@link #getCustomerContact() Customer Contact}' attribute.
	 *
	 *
	 * @see #getCustomerContact()
	 * @generated
	 * @ordered
	 */
	protected static final String CUSTOMER_CONTACT_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getCustomerContact() Customer Contact}' attribute.
	 *
	 *
	 * @see #getCustomerContact()
	 * @generated
	 * @ordered
	 */
	protected String customerContact = CUSTOMER_CONTACT_EDEFAULT;

	/**
	 * The default value of the '{@link #getCustomerName() Customer Name}' attribute.
	 *
	 *
	 * @see #getCustomerName()
	 * @generated
	 * @ordered
	 */
	protected static final String CUSTOMER_NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getCustomerName() Customer Name}' attribute.
	 *
	 *
	 * @see #getCustomerName()
	 * @generated
	 * @ordered
	 */
	protected String customerName = CUSTOMER_NAME_EDEFAULT;

	/**
	 * The default value of the '{@link #getOrderID() Order ID}' attribute.
	 *
	 *
	 * @see #getOrderID()
	 * @generated
	 * @ordered
	 */
	protected static final String ORDER_ID_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getOrderID() Order ID}' attribute.
	 *
	 *
	 * @see #getOrderID()
	 * @generated
	 * @ordered
	 */
	protected String orderID = ORDER_ID_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected OrderDetail1Impl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return UntypedPackage.Literals.ORDER_DETAIL1;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getCustomerAddress() {
		return customerAddress;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setCustomerAddress(String newCustomerAddress) {
		String oldCustomerAddress = customerAddress;
		customerAddress = newCustomerAddress;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UntypedPackage.ORDER_DETAIL1__CUSTOMER_ADDRESS, oldCustomerAddress, customerAddress));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getCustomerContact() {
		return customerContact;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setCustomerContact(String newCustomerContact) {
		String oldCustomerContact = customerContact;
		customerContact = newCustomerContact;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UntypedPackage.ORDER_DETAIL1__CUSTOMER_CONTACT, oldCustomerContact, customerContact));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getCustomerName() {
		return customerName;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setCustomerName(String newCustomerName) {
		String oldCustomerName = customerName;
		customerName = newCustomerName;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UntypedPackage.ORDER_DETAIL1__CUSTOMER_NAME, oldCustomerName, customerName));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getOrderID() {
		return orderID;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setOrderID(String newOrderID) {
		String oldOrderID = orderID;
		orderID = newOrderID;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, UntypedPackage.ORDER_DETAIL1__ORDER_ID, oldOrderID, orderID));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_ADDRESS:
				return getCustomerAddress();
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_CONTACT:
				return getCustomerContact();
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_NAME:
				return getCustomerName();
			case UntypedPackage.ORDER_DETAIL1__ORDER_ID:
				return getOrderID();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_ADDRESS:
				setCustomerAddress((String)newValue);
				return;
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_CONTACT:
				setCustomerContact((String)newValue);
				return;
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_NAME:
				setCustomerName((String)newValue);
				return;
			case UntypedPackage.ORDER_DETAIL1__ORDER_ID:
				setOrderID((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_ADDRESS:
				setCustomerAddress(CUSTOMER_ADDRESS_EDEFAULT);
				return;
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_CONTACT:
				setCustomerContact(CUSTOMER_CONTACT_EDEFAULT);
				return;
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_NAME:
				setCustomerName(CUSTOMER_NAME_EDEFAULT);
				return;
			case UntypedPackage.ORDER_DETAIL1__ORDER_ID:
				setOrderID(ORDER_ID_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_ADDRESS:
				return CUSTOMER_ADDRESS_EDEFAULT == null ? customerAddress != null : !CUSTOMER_ADDRESS_EDEFAULT.equals(customerAddress);
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_CONTACT:
				return CUSTOMER_CONTACT_EDEFAULT == null ? customerContact != null : !CUSTOMER_CONTACT_EDEFAULT.equals(customerContact);
			case UntypedPackage.ORDER_DETAIL1__CUSTOMER_NAME:
				return CUSTOMER_NAME_EDEFAULT == null ? customerName != null : !CUSTOMER_NAME_EDEFAULT.equals(customerName);
			case UntypedPackage.ORDER_DETAIL1__ORDER_ID:
				return ORDER_ID_EDEFAULT == null ? orderID != null : !ORDER_ID_EDEFAULT.equals(orderID);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (customerAddress: ");
		result.append(customerAddress);
		result.append(", customerContact: ");
		result.append(customerContact);
		result.append(", customerName: ");
		result.append(customerName);
		result.append(", orderID: ");
		result.append(orderID);
		result.append(')');
		return result.toString();
	}

} //OrderDetail1Impl


text:
package com.imgix.test;

import com.imgix.Validator;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TestValidator {
  private static final int LESS_THAN_ZERO = -1;
  /** Test `validateMinWidth` throws if passed a value less than zero. */
  @Test(expected = RuntimeException.class)
  public void testValidateMinWidth() {
    Validator.validateMinWidth(LESS_THAN_ZERO);
  }

  /** Test `validateMaxWidth` throws if passed a value less than zero. */
  @Test(expected = RuntimeException.class)
  public void testValidateMaxWidth() {
    Validator.validateMaxWidth(LESS_THAN_ZERO);
  }

  /** Test `validateRange` throws if passed an invalid range, ie. if `BEGIN > END`. */
  @Test(expected = RuntimeException.class)
  public void testValidateRange() {
    final int BEGIN = 100;
    final int END = 99;
    Validator.validateRange(BEGIN, END);
  }

  /** Test `validateTolerance` throws if passed a `tol`erance that is less than one percent. */
  @Test(expected = RuntimeException.class)
  public void testValidateTolerance() {
    final double LESS_THAN_ONE_PERCENT = 0.001;
    Validator.validateTolerance(LESS_THAN_ONE_PERCENT);
  }

  /** Test `validateWidths` throws if a negative width value has been found. */
  @Test(expected = RuntimeException.class)
  public void testValidateWidths() {
    Integer[] widths = new Integer[] {100, 200, 300, -400};
    Validator.validateWidths(widths);
  }

  /** Test `validateWidths` throws if passed a `null` array. */
  @Test(expected = RuntimeException.class)
  public void testValidateWidthsNullArray() {
    Validator.validateWidths(null);
  }

  /** Test `validateWidths` throws if passed an empty array. */
  @Test(expected = RuntimeException.class)
  public void testValidateWidthsEmptyArray() {
    Validator.validateWidths(new Integer[] {});
  }
}


text:
export default function filterProps(propKeys, props, nextProps) {
    return propKeys.reduce(
        (filtered, key) => {
            filtered.props[key] = props[key];
            filtered.nextProps[key] = nextProps[key];
            return filtered;
        },
        {
            props: {},
            nextProps: {}
        }
    );
}


text:
package org.apache.sshd.git.transport;

import java.io.IOException;
import java.util.Objects;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.session.ClientSessionHolder;
import org.apache.sshd.common.session.SessionHolder;
import org.apache.sshd.common.util.GenericUtils;
import org.eclipse.jgit.errors.TransportException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.RemoteSession;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.util.FS;

/**
 * TODO Add javadoc
 *
 * @author Apache MINA SSHD Project
 */
public class GitSshdSessionFactory
        extends SshSessionFactory
        implements SessionHolder<ClientSession>, ClientSessionHolder {
    public static final GitSshdSessionFactory INSTANCE = new GitSshdSessionFactory();

    private final SshClient client;
    private final ClientSession session;

    public GitSshdSessionFactory() {
        this(null, null);
    }

    /**
     * Used to provide an externally managed {@link SshClient} instance. In this case, the
     * caller is responsible for start/stop-ing the client once no longer needed.
     *
     * @param client The (never {@code null}) client instance
     */
    public GitSshdSessionFactory(SshClient client) {
        this(Objects.requireNonNull(client, "No client instance provided"), null);
    }

    /**
     * Used to provide an externally managed {@link ClientSession} instance. In this case, the
     * caller is responsible for connecting and disconnecting the session once no longer needed.
     * Note: in this case, the connection and authentication phase are skipped - i.e.,
     * any specific host/port/user/password(s) specified in the GIT URI are not used.
     *
     * @param session The (never {@code null}) client session instance
     */
    public GitSshdSessionFactory(ClientSession session) {
        this(null, session);
    }

    protected GitSshdSessionFactory(SshClient client, ClientSession session) {
        this.client = client;
        this.session = session;
    }

    @Override
    public RemoteSession getSession(
            URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms)
                throws TransportException {
        try {
            return new GitSshdSession(uri, credentialsProvider, fs, tms) {
                @Override
                protected SshClient createClient() {
                    SshClient thisClient = getClient();
                    if (thisClient != null) {
                        return thisClient;
                    }

                    return super.createClient();
                }

                @Override
                protected ClientSession createClientSession(
                        SshClient clientInstance, String host, String username, int port, String... passwords)
                            throws IOException, InterruptedException {
                    ClientSession thisSession = getClientSession();
                    if (thisSession != null) {
                        return thisSession;
                    }

                    return super.createClientSession(clientInstance, host, username, port, passwords);
                }

                @Override
                protected void disconnectSession(ClientSession sessionInstance) {
                    ClientSession thisSession = getClientSession();
                    if (GenericUtils.isSameReference(thisSession, sessionInstance)) {
                        return; // do not use the session instance we were given
                    }

                    super.disconnectSession(sessionInstance);
                }

                @Override
                protected void disconnectClient(SshClient clientInstance) {
                    SshClient thisClient = getClient();
                    if (GenericUtils.isSameReference(thisClient, clientInstance)) {
                        return; // do not close the client the user gave us
                    }

                    super.disconnectClient(clientInstance);
                }
            };
        } catch (Exception e) {
            throw new TransportException("Unable to connect", e);
        }
    }

    protected SshClient getClient() {
        return client;
    }

    @Override
    public ClientSession getClientSession() {
        return session;
    }

    @Override
    public ClientSession getSession() {
        return getClientSession();
    }
}


text:
<?php
if ($callbacks)
{
	if (!is_array($callbacks)) $callbacks = (array)$callbacks;
	foreach ($callbacks as $callback)
	{
		if (is_callable($callback)) $body = call_user_func($callback, $body);
	}
}

$is_truncated = false;
if (!$options['is_detail'])
{
	if ($options['line'])
	{
		list($body, $is_truncated4line) = Util_string::truncate4line($body, $options['line'], '', $options['is_rtrim'], $options['encoding']);
	}
	if ($options['width'])
	{
		list($body, $is_truncated4count) = Util_string::truncate($body, $options['width'], '', true);
	}
	$is_truncated = $is_truncated4line || $is_truncated4count;
}

if ($is_truncated && $options['trimmarker'])
{
	if (!Str::ends_with($body, "\n")) $body .= ' ';
	$body .= $options['trimmarker'];
}
?>

<?php echo $body; ?>

<?php if ($is_truncated && $options['read_more_uri']): ?>

<?php echo Html::anchor($options['read_more_uri'], 'もっとみる'); ?>

<?php endif; ?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using XamarinFormsApi.Dependencies;

namespace XamarinFormsApi.Views
{
    public partial class SpeakPage
    {
        public SpeakPage()
        {
            InitializeComponent();

            SpeakButton.Clicked += (sender, args) => DependencyService.Get<ITextToSpeech>().Speak(SpeakEntry.Text);
        }
    }
}


text:
'use strict';

var PLUGIN_NAME = 'gulp-compass',
  spawn = require('child_process').spawn,
  gutil = require('gulp-util'),
  path = require('path'),
  which = require('which').sync,
  defaults = {
    style: false,
    comments: true,
    relative: true,
    css: 'css',
    sass: 'sass',
    image: false,
    javascript: false,
    font: false,
    import_path: false,
    config_file: false,
    require: false,
    logging: true,
    load_all: false,
    project: process.cwd(),
    bundle_exec: false,
    debug: false,
    time: false,
    sourcemap: false,
    boring: false
  },
  isArray = Array.isArray || function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  };

module.exports = function(file, opts, callback) {
  opts = opts || {};

  for (var key in defaults) {
    if (opts[key] === undefined) {
      opts[key] = defaults[key];
    }
  }

  var compassExecutable = 'compass',
    file_path = file.replace(/\\/g, '/'),
    relative_file_name = path.relative(path.join(opts.project || process.cwd(), opts.sass), file);

  // check command exist
  try {
    if (opts.bundle_exec) {
      compassExecutable = which('bundle');
    } else {
      compassExecutable = which(compassExecutable);
    }
  } catch (err) {
    if(callback){
      callback(127, '', String(err), '');
    }
    return;
  }

  var options = [];
  if (opts.bundle_exec) {
    options.push('exec', 'compass');
  }
  options.push('compile');
  if (process.platform === 'win32') {
    options.push(opts.project.replace(/\\/g, '/'));
  } else {
    options.push(opts.project);
  }
  options.push(file_path);

  // set compass setting
  if (opts.environment) { options.push('--environment', opts.environment); }
  if (opts.config_file) { options.push('-c', opts.config_file); }
  if (!opts.comments) { options.push('--no-line-comments'); }
  if (opts.relative) { options.push('--relative-assets'); }
  if (opts.debug) { options.push('--debug-info'); }
  if (opts.time) { options.push('--time'); }
  if (opts.boring) { options.push('--boring'); }
  if (opts.sourcemap) { options.push('--sourcemap'); }
  if (opts.font) { options.push('--fonts-dir', opts.font); }
  if (opts.style) { options.push('--output-style', opts.style); }
  if (opts.image) { options.push('--images-dir', opts.image); }
  if (opts.javascript) { options.push('--javascripts-dir', opts.javascript); }
  options.push('--css-dir', opts.css);
  options.push('--sass-dir', opts.sass);

  if (opts.import_path) {
    if(isArray(opts.import_path)) {
      opts.import_path.forEach(function(i) {
        options.push('-I', i);
      });
    } else {
      options.push('-I', opts.import_path);
    }
  }
  if (opts.load_all) { options.push('--load-all', opts.load_all); }
  if (opts.require) {
    if (isArray(opts.require)) {
      for (var i = 0, len = opts.require.length; i < len; i++) {
        options.push('--require', opts.require[i]);
      }
    } else {
      options.push('--require', opts.require);
    }
  }

  if (opts.debug) {
    gutil.log(PLUGIN_NAME + ':', 'Running command:', compassExecutable, options.join(' '));
  }

  var child = spawn(compassExecutable, options, {cwd: opts.project || process.cwd()}),
    stdout = '',
    stderr = '';
  if (opts.logging) {
    child.stdout.setEncoding('utf8');
    child.stdout.on('data', function (data) {
      stdout += data;
      console.log(data);
    });

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function (data) {
      stderr += data;
      if (!data.match(/^\u001b\[\d+m$/)) {
        gutil.log(data);
      }
    });
  }

  // support callback
  child.on('close', function(code) {
    var new_path;
    new_path = path.join(opts.project, opts.css, relative_file_name);
    if(callback){
      callback(code, stdout, stderr, new_path);
    }
  });
};


text:
enum Interpolation {
    None,
    Linear
}


text:
struct _persona
{
    int matricula;
    char nombre[20];
    char apellido[20];
    struct _persona *siguiente;
};

struct _persona *lista = NULL;
clock_t start, end;

void ordenarListaIncrementalmentePorMatricula(struct _persona *lista, int cont)
{

}

int main(int argc, const char *argv[])
{
    struct _persona *nuevoNodo;
    struct _persona *nodo;
    int mat;
    do{
        printf("Dame tu matricula: ");
        scanf("%d", &mat);

        if(mat > 0){
            nuevoNodo = (struct _persona*)malloc(sizeof(struct _persona));
            nuevoNodo->matricula = mat;

            printf("Dame tu nombre: ");
            scanf("%s", &nuevoNodo->nombre[0]);
            printf("Dame tu apellido: ");
            scanf("%s", &nuevoNodo->apellido[0]);
            nuevoNodo->siguiente = lista;
            lista = nuevoNodo;
        }

    }while(!mat);

    return 0;
}


text:
<?php

namespace Pagekit\Comment\Event;

use Pagekit\Comment\Model\CommentInterface;
use Pagekit\Comment\SpamDetection\SpamMarkerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * A listener that tells spam markers to mark comments as spam or ham
 */
class SpamMarkerListener implements EventSubscriberInterface
{
    /**
     * @var SpamMarkerInterface
     */
    protected $marker;

    /**
     * Constructor.
     *
     * @param SpamMarkerInterface $marker
     */
    public function __construct(SpamMarkerInterface $marker)
    {
        $this->marker = $marker;
    }

    public function mark(MarkSpamEvent $event)
    {
        $comment = $event->getComment();

        if ($comment->getStatus() == $event->getPreviousStatus()) {
            return;
        }

        if ($comment->getStatus() == CommentInterface::STATUS_SPAM) {
            $this->marker->markSpam($comment);
        } elseif ($event->getPreviousStatus() == CommentInterface::STATUS_SPAM) {
            $this->marker->markHam($comment);
        }
    }

    public static function getSubscribedEvents()
    {
        return ['system.comment.spam_mark' => 'mark'];
    }
}


text:
namespace content {

CompositorExternalBeginFrameSource::CompositorExternalBeginFrameSource(
    CompositorForwardingMessageFilter* filter,
    IPC::SyncMessageFilter* sync_message_filter,
    int routing_id)
    : external_begin_frame_source_(this),
      begin_frame_source_filter_(filter),
      message_sender_(sync_message_filter),
      routing_id_(routing_id) {
  DCHECK(begin_frame_source_filter_);
  DCHECK(message_sender_);
  DetachFromThread();
}

CompositorExternalBeginFrameSource::~CompositorExternalBeginFrameSource() {
  DCHECK(CalledOnValidThread());
  if (begin_frame_source_proxy_) {
    begin_frame_source_proxy_->ClearBeginFrameSource();
    begin_frame_source_filter_->RemoveHandlerOnCompositorThread(
                                    routing_id_,
                                    begin_frame_source_filter_handler_);
  }
}

void CompositorExternalBeginFrameSource::AddObserver(
    cc::BeginFrameObserver* obs) {
  DCHECK(CalledOnValidThread());

  if (!begin_frame_source_proxy_) {
    begin_frame_source_proxy_ =
        new CompositorExternalBeginFrameSourceProxy(this);
    begin_frame_source_filter_handler_ =
        base::Bind(&CompositorExternalBeginFrameSourceProxy::OnMessageReceived,
                   begin_frame_source_proxy_);
    begin_frame_source_filter_->AddHandlerOnCompositorThread(
        routing_id_, begin_frame_source_filter_handler_);
  }

  external_begin_frame_source_.AddObserver(obs);
}

void CompositorExternalBeginFrameSource::RemoveObserver(
    cc::BeginFrameObserver* obs) {
  external_begin_frame_source_.RemoveObserver(obs);
}

bool CompositorExternalBeginFrameSource::IsThrottled() const {
  return true;
}

void CompositorExternalBeginFrameSource::OnNeedsBeginFrames(
    bool needs_begin_frames) {
  Send(new ViewHostMsg_SetNeedsBeginFrames(routing_id_, needs_begin_frames));
}

void CompositorExternalBeginFrameSource::OnMessageReceived(
    const IPC::Message& message) {
  DCHECK(CalledOnValidThread());
  DCHECK(begin_frame_source_proxy_);
  IPC_BEGIN_MESSAGE_MAP(CompositorExternalBeginFrameSource, message)
    IPC_MESSAGE_HANDLER(ViewMsg_SetBeginFramePaused,
                        OnSetBeginFrameSourcePaused)
    IPC_MESSAGE_HANDLER(ViewMsg_BeginFrame, OnBeginFrame)
  IPC_END_MESSAGE_MAP()
}

void CompositorExternalBeginFrameSource::OnSetBeginFrameSourcePaused(
    bool paused) {
  external_begin_frame_source_.OnSetBeginFrameSourcePaused(paused);
}

void CompositorExternalBeginFrameSource::OnBeginFrame(
    const cc::BeginFrameArgs& args) {
  external_begin_frame_source_.OnBeginFrame(args);
}

bool CompositorExternalBeginFrameSource::Send(IPC::Message* message) {
  return message_sender_->Send(message);
}

}  // namespace content


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-04-06"

---

{:codeblock:.codeblock}

**Important: The {{site.data.keyword.amafull}} service is replaced with the {{site.data.keyword.appid_full}} service.**

# Configuring custom authentication for your Mobile Client Access iOS (Swift SDK) app
{: #custom-ios}

Configure your iOS application that is using custom authentication to use the {{site.data.keyword.amafull}} client SDK and connect your application to {{site.data.keyword.Bluemix}}.

## Before you begin
{: #before-you-begin}

Before you begin you must have:

* A resource that is protected by an instance of the {{site.data.keyword.amashort}} service that is configured to use a custom identity provider (see [Configuring custom authentication](custom-auth-config-mca.html)).
* Your **TenantID** value. Open your service in the  {{site.data.keyword.amashort}} dashboard. Click the **Mobile Options** button. The `tenantId` (also known as `appGUID`)  value is displayed in the **App GUID / TenantId** field. You will need this value for intializing the Authorization Manager.
* Your **Realm** name. This is the value you you specificed in the **Realm Name** field of the **Custom** section in the **Management** tab of the {{site.data.keyword.amashort}} dashboard.
* The URL of your back-end application (**App Route**). You will need this values for sending requests to the protected endpoints of your back-end application.
* Your {{site.data.keyword.Bluemix_notm}} **Region**. You can find your current {{site.data.keyword.Bluemix_notm}} region in the header, next to the **Avatar** icon ![Avatar icon](images/face.jpg "Avatar icon"). The region value that appears should be one of the following: **US South**, **United Kingdom**, or **Sydney**, and correspond to the constants required in the code:  `BMSClient.Region.usSouth`, `BMSClient.Region.unitedKingdom`, or `BMSClient.Region.sydney`.

For more information, see the following information:
 * [Getting started with {{site.data.keyword.amashort}}](index.html)
 * [Setting up the iOS Swift SDK](getting-started-ios-swift-sdk.html)
 * [Using a custom identity provider](custom-auth.html)
 * [Creating a custom identity provider](custom-auth-identity-provider.html)
 * [Configuring {{site.data.keyword.amashort}} for custom authentication](custom-auth-config-mca.html)

### Enable Keychain Sharing for iOS
{: #enable_keychain}

Enable `Keychain Sharing`. Go to the `Capabilities` tab and switch the `Keychain Sharing` to `On` in your Xcode project.

### Initializing the client SDK
{: #custom-ios-sdk-initialize}

Initialize the SDK by passing the `applicationGUID` (**TenantId**) parameter. A common, though not mandatory, place to put the initialization code is in the `application:didFinishLaunchingWithOptions` method of your application delegate.

1. Import the required frameworks in the class where you want to use {{site.data.keyword.amashort}} client SDK.

	```Swift
	import UIKit
	import BMSCore
	import BMSSecurity
	```
	{: codeblock}

1. Initialize the {{site.data.keyword.amashort}} client SDK, change the authorization manager to the  `MCAAuthorizationManager`, and define and register an authentication delegate.

```Swift

	let tenantId = "<serviceTenantID>"
	let regionName = <applicationBluemixRegion>
	let customRealm = "<yourProtectedRealm>"

	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
		[UIApplicationLaunchOptionsKey: Any]?) -> Bool {

		let mcaAuthManager = MCAAuthorizationManager.sharedInstance
	    		mcaAuthManager.initialize(tenantId: tenantId, bluemixRegion: regionName)
	 //the regionName should be one of the following BMSClient.Region constants: BMSClient.Region.usSouth, BMSClient.Region.unitedKingdom, or BMSClient.Region.sydney
		BMSClient.sharedInstance.authorizationManager = mcaAuthManager

	//Auth delegate for handling custom challenge
	     class MyAuthDelegate : AuthenticationDelegate {
		func onAuthenticationChallengeReceived(_ authContext: AuthenticationContext, challenge: AnyObject){
		    print("onAuthenticationChallengeReceived")
		    let answer = try? Utils.parseJsonStringtoDictionary( "{\"userName\":\"" + "test" + "\",\"password\":\"" + "test" + "\"}")
			authContext.submitAuthenticationChallengeAnswer(answer)
		}

		func onAuthenticationSuccess(_ info: AnyObject?) {
		    print("onAuthenticationSuccess info = \(info)")
		    print("onAuthenticationSuccess")
		}

		func onAuthenticationFailure(_ info: AnyObject?){
		     print("onAuthenticationFailure info = \(info)")
		     print("onAuthenticationFailure")
		}
	     }

	     let delegate = MyAuthDelegate()
	     mcaAuthManager.registerAuthenticationDelegate(delegate, realm: customRealm)

	     return true
	}

```
{: codeblock}

In the code:
* Replace `MCAServiceTenantId` with the **TenantId** value and `<applicationBluemixRegion>` with your {{site.data.keyword.amashort}} **Region** (see [Before you begin](##before-you-begin)).
* Use the `realmName` that you specified in the {{site.data.keyword.amashort}} dashboard (see [Configuring custom authentication](custom-auth-config-mca.html)).
* Replace `<applicationBluemixRegion>` with the region where your {{site.data.keyword.Bluemix_notm}} application is hosted. To view your {{site.data.keyword.Bluemix_notm}} region, click the Avatar icon ![Avatar icon](images/face.jpg "Avatar icon")  in the menu bar to open the **Account and Support** widget.  The region value that appears should be one of the following: **US South**, **United Kingdom**, or **Sydney**, and correspond to the constants required in the code:  `BMSClient.Region.usSouth`, `BMSClient.Region.unitedKingdom`, or `BMSClient.Region.sydney`.

## Testing the authentication
{: #custom-ios-testing}

After you initialize the client SDK and register a custom authentication delegate, you can start making requests to your mobile back-end application.

### Before you begin
{: #custom-ios-testing-before}

 You must have an application that was created with the {{site.data.keyword.mobilefirstbp}} boilerplate, and have a resource that is protected by {{site.data.keyword.amashort}} at the `/protected` endpoint.

1. Send a request to protected endpoint of your mobile back-end application in your browser by opening `{applicationRoute}/protected`. Replace the   `{applicationRoute}` with the value retrieved from the **Mobile options** (see [Configuring Mobile Client Access for custom authentication](#custom-auth-ios-configmca)). For example `http://my-mobile-backend.mybluemix.net/protected`.

 The `/protected` endpoint of a mobile back-end application that is created with the {{site.data.keyword.mobilefirstbp}} boilerplate is protected with {{site.data.keyword.amashort}}. The endpoint can  be accessed by only mobile applications that are instrumented with the {{site.data.keyword.amashort}} client SDK. As a result, an `Unauthorized` message displays in your browser.

1. Use your iOS application to make request to the same endpoint. Add the following code after you initialize `BMSClient` and register your custom authentication delegate:

    ```Swift

	let protectedResourceURL = "<your protected resource absolute path>"
	let request = Request(url: protectedResourceURL, method: HttpMethod.GET)

	let callBack:BMSCompletionHandler = {(response: Response?, error: Error?) in
	   if error == nil {
	       print ("response:\(response?.responseText), no error")
	    } else {
	       print ("error: \(error)")
	    }
	}

	request.send(completionHandler: callBack)
     ```
     {: codeblock}

1. When your requests succeeds, you see the following output in the Xcode console:

	 ```
	 onAuthenticationSuccess info = Optional({
	     attributes =     {
	     };
	     deviceId = don;
	     displayName = "Don+Lon";
	     isUserAuthenticated = 1;
	     userId = don;
	 })
	 response:Optional("Hello Don Lon"), no error
	 ```
	 {: codeblock}

1. You can also add logout functionality by adding the following code:

	 ```
	 MCAAuthorizationManager.sharedInstance.logout(callBack)
	 ```
	 {: codeblock}

 If you call this code after a user is logged in, the user is logged out. When the user tries to log in again, they must answer the challenge received from the server again.

 Passing `callBack` to the logout function is optional. You can also pass `nil`.


text:
package org.uclab.scl.framework.recbuilder;

import static org.junit.Assert.assertEquals;

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

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uclab.scl.datamodel.FiredRule;

public class PatternMatcherTest {
  private static Map<String, List<Map<String, Object>>> rules;
  private static PatternMatcher patternMatcher;

  @BeforeClass
  public static void setup() {
    ObjectMapper mapper = new ObjectMapper();
    try {
      rules = mapper.readValue(TestHelper.loadStringRules(), new TypeReference<Map<String, List<Map<String, Object>>>>() {});
      patternMatcher = new PatternMatcher();

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  @AfterClass
  public static void afterClass() {
    // . TODO afterClass stuff
  }

  @Test
  public void rulesLoaded() {
    int expected = 19;
    int actual = (rules.get("rules")).size();
    assertEquals(expected, actual);
  }
  public void fireRuleTest1() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\",\"Activity Environment\":\"BedRest\",\"Activity Status\":\"Non-continuous\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);
    int expected = 2;
    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.size());
    }catch(UnsupportedTypeException e){e.printStackTrace();}
  }

  @Test
  public void fireRuleTest2() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);

    String expected = "19";

    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.get(0).getRuleId());
    }catch(UnsupportedTypeException e){}
  }

  @Test
  public void fireRuleTest3() {
    String jsonFact = "{\"Current Activity\":\"LyingDown\",\"Activity Duration\":\"1h\"}";
    Map<String, Object> fact = TestHelper.buildFact(jsonFact);

    int expected = 0;
    fact.put("Current Activity", "Nothing");
    try{
      List<FiredRule> firedRules = patternMatcher.fireRule(fact, rules.get("rules"));
      assertEquals(expected, firedRules.size());
    }catch(UnsupportedTypeException e){}
  }

}