text:
namespace boost { namespace intrusive { namespace test {

#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5, class O6>
#else
template<class T, class ...Options>
#endif
struct is_unordered<boost::intrusive::unordered_multiset<T,
   #if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
   O1, O2, O3, O4, O5, O6
   #else
   Options...
   #endif
> >
{
   static const bool value = true;
};

}}}

using namespace boost::intrusive;

struct my_tag;

template<class VoidPointer>
struct hooks
{
   typedef unordered_set_base_hook<void_pointer<VoidPointer> >    base_hook_type;
   typedef unordered_set_base_hook
      < link_mode<auto_unlink>
      , void_pointer<VoidPointer>
      , tag<my_tag>
      , store_hash<true>
      >                                                           auto_base_hook_type;

   typedef unordered_set_member_hook
      < void_pointer<VoidPointer>
      , optimize_multikey<true>
      >                                                           member_hook_type;
   typedef unordered_set_member_hook
      < link_mode<auto_unlink>, void_pointer<VoidPointer>
      , store_hash<true>
      , optimize_multikey<true>
      >                                                           auto_member_hook_type;
   typedef nonhook_node_member< unordered_node_traits< VoidPointer, true, true >,
                                unordered_algorithms
                              > nonhook_node_member_type;
};

static const std::size_t BucketSize = 8;

template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
struct test_unordered_multiset
{
   typedef typename ValueTraits::value_type value_type;
   static void test_all (std::vector<value_type>& values);
   static void test_sort(std::vector<value_type>& values);
   static void test_insert(std::vector<value_type>& values);
   static void test_swap(std::vector<value_type>& values);
   static void test_rehash(std::vector<value_type>& values, detail::true_);
   static void test_rehash(std::vector<value_type>& values, detail::false_);
   static void test_find(std::vector<value_type>& values);
   static void test_impl();
   static void test_clone(std::vector<value_type>& values);
};

template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>::
   test_all (std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      < value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   {
      typedef typename unordered_multiset_type::bucket_traits bucket_traits;
      typename unordered_multiset_type::bucket_type buckets [BucketSize];
      unordered_multiset_type testset
         (bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>::
            pointer_to(buckets[0]), BucketSize));
      testset.insert(values.begin(), values.end());
      test::test_container(testset);
      testset.clear();
      testset.insert(values.begin(), values.end());
      test::test_common_unordered_and_associative_container(testset, values);
      testset.clear();
      testset.insert(values.begin(), values.end());
      test::test_unordered_associative_container(testset, values);
      testset.clear();
      testset.insert(values.begin(), values.end());
      test::test_non_unique_container(testset, values);
   }
   test_sort(values);
   test_insert(values);
   test_swap(values);
   test_rehash(values, detail::bool_<Incremental>());
   test_find(values);
   test_impl();
   test_clone(values);
}

//test case due to an error in tree implementation:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_impl()
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;

   std::vector<value_type> values (5);
   for (int i = 0; i < 5; ++i)
      values[i].value_ = i;

   typename unordered_multiset_type::bucket_type buckets [BucketSize];
   unordered_multiset_type testset(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets[0]), BucketSize));

   for (int i = 0; i < 5; ++i)
      testset.insert (values[i]);

   testset.erase (testset.iterator_to (values[0]));
   testset.erase (testset.iterator_to (values[1]));
   testset.insert (values[1]);

   testset.erase (testset.iterator_to (values[2]));
   testset.erase (testset.iterator_to (values[3]));
}

//test: constructor, iterator, clear, reverse_iterator, front, back, size:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_sort(std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;

   typename unordered_multiset_type::bucket_type buckets [BucketSize];
   unordered_multiset_type testset1
      (values.begin(), values.end(), bucket_traits
         (pointer_traits<typename unordered_multiset_type::bucket_ptr>::
            pointer_to(buckets[0]), BucketSize));

   if(Incremental){
      {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   }
   else{
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   }
   testset1.clear();
   BOOST_TEST (testset1.empty());
}

//test: insert, const_iterator, const_reverse_iterator, erase, iterator_to:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_insert(std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;
   typedef typename unordered_multiset_type::iterator iterator;
   {
      typename unordered_multiset_type::bucket_type buckets [BucketSize];
      unordered_multiset_type testset(bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
               pointer_to(buckets[0]), BucketSize));

      testset.insert(&values[0] + 2, &values[0] + 5);

      const unordered_multiset_type& const_testset = testset;

      if(Incremental){
         {
            {  int init_values [] = { 4, 5, 1 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }

            typename unordered_multiset_type::iterator i = testset.begin();
            BOOST_TEST (i->value_ == 4);

            i = testset.insert (values[0]);
            BOOST_TEST (&*i == &values[0]);

            i = testset.iterator_to (values[2]);
            BOOST_TEST (&*i == &values[2]);
            testset.erase(i);

            {  int init_values [] = { 5, 1, 3 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }
            testset.clear();
            testset.insert(&values[0], &values[0] + values.size());

            {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }

            BOOST_TEST (testset.erase(1) == 1);
            BOOST_TEST (testset.erase(2) == 2);
            BOOST_TEST (testset.erase(3) == 1);
            BOOST_TEST (testset.erase(4) == 1);
            BOOST_TEST (testset.erase(5) == 1);
            BOOST_TEST (testset.empty() == true);

            //Now with a single bucket
            typename unordered_multiset_type::bucket_type single_bucket[1];
            unordered_multiset_type testset2(bucket_traits(
               pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                  pointer_to(single_bucket[0]), 1));
            testset2.insert(&values[0], &values[0] + values.size());
            BOOST_TEST (testset2.erase(5) == 1);
            BOOST_TEST (testset2.erase(2) == 2);
            BOOST_TEST (testset2.erase(1) == 1);
            BOOST_TEST (testset2.erase(4) == 1);
            BOOST_TEST (testset2.erase(3) == 1);
            BOOST_TEST (testset2.empty() == true);
         }
      }
      else{
         {
            {  int init_values [] = { 1, 4, 5 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }

            typename unordered_multiset_type::iterator i = testset.begin();
            BOOST_TEST (i->value_ == 1);

            i = testset.insert (values[0]);
            BOOST_TEST (&*i == &values[0]);

            i = testset.iterator_to (values[2]);
            BOOST_TEST (&*i == &values[2]);
            testset.erase(i);

            {  int init_values [] = { 1, 3, 5 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }
            testset.clear();
            testset.insert(&values[0], &values[0] + values.size());

            {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
               TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() );  }

            BOOST_TEST (testset.erase(1) == 1);
            BOOST_TEST (testset.erase(2) == 2);
            BOOST_TEST (testset.erase(3) == 1);
            BOOST_TEST (testset.erase(4) == 1);
            BOOST_TEST (testset.erase(5) == 1);
            BOOST_TEST (testset.empty() == true);

            //Now with a single bucket
            typename unordered_multiset_type::bucket_type single_bucket[1];
            unordered_multiset_type testset2(bucket_traits(
               pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                  pointer_to(single_bucket[0]), 1));
            testset2.insert(&values[0], &values[0] + values.size());
            BOOST_TEST (testset2.erase(5) == 1);
            BOOST_TEST (testset2.erase(2) == 2);
            BOOST_TEST (testset2.erase(1) == 1);
            BOOST_TEST (testset2.erase(4) == 1);
            BOOST_TEST (testset2.erase(3) == 1);
            BOOST_TEST (testset2.empty() == true);
         }
      }
      {
         //Now erase just one per loop
         const int random_init[] = { 3, 2, 4, 1, 5, 2, 2 };
         const unsigned int random_size = sizeof(random_init)/sizeof(random_init[0]);
         typename unordered_multiset_type::bucket_type single_bucket[1];
         for(unsigned int i = 0, max = random_size; i != max; ++i){
            std::vector<typename ValueTraits::value_type> data (random_size);
            for (unsigned int j = 0; j < random_size; ++j)
               data[j].value_ = random_init[j];
            unordered_multiset_type testset_new(bucket_traits(
               pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                  pointer_to(single_bucket[0]), 1));
            testset_new.insert(&data[0], &data[0]+max);
            testset_new.erase(testset_new.iterator_to(data[i]));
            BOOST_TEST (testset_new.size() == (max -1));
         }
      }
   }
   {
      typename unordered_multiset_type::bucket_type buckets [BucketSize];
      const unsigned int NumBucketSize = BucketSize;
      const unsigned int LoadFactor    = 3;
      const unsigned int NumIterations = NumBucketSize*LoadFactor;
      std::vector<value_type> random_init(NumIterations);//Preserve memory
      std::vector<value_type> set_tester;
      set_tester.reserve(NumIterations);

      //Initialize values
      for (unsigned int i = 0; i < NumIterations; ++i){
         random_init[i].value_ = i*2;//(i/LoadFactor)*LoadFactor;
      }

      for(unsigned int initial_pos = 0; initial_pos != (NumIterations+1); ++initial_pos){
         for(unsigned int final_pos = initial_pos; final_pos != (NumIterations+1); ++final_pos){

            //Create intrusive container inserting values
            unordered_multiset_type testset
               ( &random_init[0]
               , &random_init[0] + random_init.size()
               , bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                  pointer_to(buckets[0]), NumBucketSize));

            BOOST_TEST (testset.size() == random_init.size());

            //Obtain the iterator range to erase
            iterator it_beg_pos = testset.begin();
            for(unsigned int it_beg_pos_num = 0; it_beg_pos_num != initial_pos; ++it_beg_pos_num){
               ++it_beg_pos;
            }
            iterator it_end_pos(it_beg_pos);
            for(unsigned int it_end_pos_num = 0; it_end_pos_num != (final_pos - initial_pos); ++it_end_pos_num){
               ++it_end_pos;
            }

            //Erase the same values in both the intrusive and original vector
            std::size_t erased_cnt = std::distance(it_beg_pos, it_end_pos);

            //Erase values from the intrusive container
            testset.erase(it_beg_pos, it_end_pos);

            BOOST_TEST (testset.size() == (random_init.size()-(final_pos - initial_pos)));

            //Now test...
            BOOST_TEST ((random_init.size() - erased_cnt) == testset.size());

            //Create an ordered copy of the intrusive container
            set_tester.insert(set_tester.end(), testset.begin(), testset.end());
            std::sort(set_tester.begin(), set_tester.end());
            {
               typename std::vector<value_type>::iterator it = set_tester.begin(), itend = set_tester.end();
               typename std::vector<value_type>::iterator random_init_it(random_init.begin());
               for( ; it != itend; ++it){
                  while(!random_init_it->is_linked())
                     ++random_init_it;
                  BOOST_TEST(*it == *random_init_it);
                  ++random_init_it;
               }
            }
            set_tester.clear();
         }
      }
   }
}

//test: insert (seq-version), swap, erase (seq-version), size:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>::
   test_swap(std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;
   typename unordered_multiset_type::bucket_type buckets [BucketSize];

   typename unordered_multiset_type::bucket_type buckets2 [BucketSize];
   unordered_multiset_type testset1(&values[0], &values[0] + 2,
      bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets[0]), BucketSize));
   unordered_multiset_type testset2(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                  pointer_to(buckets2[0]), BucketSize));

   testset2.insert (&values[0] + 2, &values[0] + 6);
   testset1.swap (testset2);

   if(Incremental){
      {  int init_values [] = { 4, 5, 1, 2 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

      {  int init_values [] = { 2, 3 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() );  }
      testset1.erase (testset1.iterator_to(values[4]), testset1.end());
      BOOST_TEST (testset1.size() == 1);
      //  BOOST_TEST (&testset1.front() == &values[3]);
      BOOST_TEST (&*testset1.begin() == &values[2]);
   }
   else{
      {  int init_values [] = { 1, 2, 4, 5 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

      {  int init_values [] = { 2, 3 };
         TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() );  }
      testset1.erase (testset1.iterator_to(values[5]), testset1.end());
      BOOST_TEST (testset1.size() == 1);
      //  BOOST_TEST (&testset1.front() == &values[3]);
      BOOST_TEST (&*testset1.begin() == &values[3]);
   }
}

//test: rehash:

template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::true_)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;
   //Build a uset
   typename unordered_multiset_type::bucket_type buckets1 [BucketSize];
   typename unordered_multiset_type::bucket_type buckets2 [BucketSize*2];
   unordered_multiset_type testset1(&values[0], &values[0] + values.size(),
      bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
   //Test current state
   BOOST_TEST(testset1.split_count() == BucketSize/2);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Incremental rehash step
   BOOST_TEST (testset1.incremental_rehash() == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
   {  int init_values [] = { 5, 1, 2, 2, 3, 4 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Rest of incremental rehashes should lead to the same sequence
   for(std::size_t split_bucket = testset1.split_count(); split_bucket != BucketSize; ++split_bucket){
      BOOST_TEST (testset1.incremental_rehash() == true);
      BOOST_TEST(testset1.split_count() == (split_bucket+1));
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   }
   //This incremental rehash should fail because we've reached the end of the bucket array
   BOOST_TEST (testset1.incremental_rehash() == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //
   //Try incremental hashing specifying a new bucket traits pointing to the same array
   //
   //This incremental rehash should fail because the new size is not twice the original
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                              pointer_to(buckets1[0]), BucketSize)) == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //
   //Try incremental hashing specifying a new bucket traits pointing to the same array
   //
   //This incremental rehash should fail because the new size is not twice the original
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
               pointer_to(buckets2[0]), BucketSize)) == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //This incremental rehash should success because the new size is twice the original
   //and split_count is the same as the old bucket count
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                     pointer_to(buckets2[0]), BucketSize*2)) == true);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //This incremental rehash should also success because the new size is half the original
   //and split_count is the same as the new bucket count
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
                           pointer_to(buckets1[0]), BucketSize)) == true);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //Full shrink rehash
   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), 4));
   BOOST_TEST (testset1.size() == values.size());
   BOOST_TEST (testset1.incremental_rehash() == false);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Full shrink rehash again
   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), 2));
   BOOST_TEST (testset1.size() == values.size());
   BOOST_TEST (testset1.incremental_rehash() == false);
   {  int init_values [] = { 2, 2, 4, 3, 5, 1 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Full growing rehash
   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
   BOOST_TEST (testset1.size() == values.size());
   BOOST_TEST (testset1.incremental_rehash() == false);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Incremental rehash shrinking
   //First incremental rehashes should lead to the same sequence
   for(std::size_t split_bucket = testset1.split_count(); split_bucket > 6; --split_bucket){
      BOOST_TEST (testset1.incremental_rehash(false) == true);
      BOOST_TEST(testset1.split_count() == (split_bucket-1));
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   }
   //Incremental rehash step
   BOOST_TEST (testset1.incremental_rehash(false) == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
   {  int init_values [] = { 5, 1, 2, 2, 3, 4 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //Incremental rehash step 2
   BOOST_TEST (testset1.incremental_rehash(false) == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2));
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
   //This incremental rehash should fail because we've reached the half of the bucket array
   BOOST_TEST(testset1.incremental_rehash(false) == false);
   BOOST_TEST(testset1.split_count() == BucketSize/2);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
   TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
}
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::false_)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;

   typename unordered_multiset_type::bucket_type buckets1 [BucketSize];
   typename unordered_multiset_type::bucket_type buckets2 [2];
   typename unordered_multiset_type::bucket_type buckets3 [BucketSize*2];

   unordered_multiset_type testset1(&values[0], &values[0] + 6, bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
   BOOST_TEST (testset1.size() == values.size());
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets2[0]), 2));
   BOOST_TEST (testset1.size() == values.size());
   {  int init_values [] = { 4, 2, 2, 5, 3, 1 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets3[0]), BucketSize*2));
   BOOST_TEST (testset1.size() == values.size());
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //Now rehash reducing the buckets
   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets3[0]), 2));
   BOOST_TEST (testset1.size() == values.size());
   {  int init_values [] = { 4, 2, 2, 5, 3, 1 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }

   //Now rehash increasing the buckets
   testset1.rehash(bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets3[0]), BucketSize*2));
   BOOST_TEST (testset1.size() == values.size());
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() );  }
}

//test: find, equal_range (lower_bound, upper_bound):
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>::
   test_find(std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;

   typename unordered_multiset_type::bucket_type buckets[BucketSize];
   unordered_multiset_type testset(values.begin(), values.end(), bucket_traits(
      pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets[0]), BucketSize));

   typedef typename unordered_multiset_type::iterator iterator;

   value_type cmp_val;
   cmp_val.value_ = 2;
   iterator i = testset.find (cmp_val);
   BOOST_TEST (i->value_ == 2);
   BOOST_TEST ((++i)->value_ == 2);
   std::pair<iterator,iterator> range = testset.equal_range (cmp_val);

   BOOST_TEST (range.first->value_ == 2);
   BOOST_TEST (range.second->value_ == 3);
   BOOST_TEST (std::distance (range.first, range.second) == 2);

   cmp_val.value_ = 7;
   BOOST_TEST (testset.find (cmp_val) == testset.end());
}

template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>
   ::test_clone(std::vector<typename ValueTraits::value_type>& values)
{
   typedef typename ValueTraits::value_type value_type;
   typedef unordered_multiset
      <value_type
      , value_traits<ValueTraits>
      , constant_time_size<value_type::constant_time_size>
      , cache_begin<CacheBegin>
      , compare_hash<CompareHash>
      , incremental<Incremental>
      > unordered_multiset_type;
   typedef typename unordered_multiset_type::bucket_traits bucket_traits;
   {
      //Test with equal bucket arrays
      typename unordered_multiset_type::bucket_type buckets1 [BucketSize];
      typename unordered_multiset_type::bucket_type buckets2 [BucketSize];
      unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
      unordered_multiset_type testset2 (bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets2[0]), BucketSize));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std::multiset<typename ValueTraits::value_type>
         src(testset1.begin(), testset1.end());
      std::multiset<typename ValueTraits::value_type>
         dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
   {
      //Test with bigger source bucket arrays
      typename unordered_multiset_type::bucket_type buckets1 [BucketSize*2];
      typename unordered_multiset_type::bucket_type buckets2 [BucketSize];
      unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize*2));
      unordered_multiset_type testset2 (bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets2[0]), BucketSize));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std::multiset<typename ValueTraits::value_type>
         src(testset1.begin(), testset1.end());
      std::multiset<typename ValueTraits::value_type>
         dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
   {
      //Test with smaller source bucket arrays
      typename unordered_multiset_type::bucket_type buckets1 [BucketSize];
      typename unordered_multiset_type::bucket_type buckets2 [BucketSize*2];
      unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
      unordered_multiset_type testset2 (bucket_traits(
         pointer_traits<typename unordered_multiset_type::bucket_ptr>::
         pointer_to(buckets2[0]), BucketSize*2));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      //Ordering is not guaranteed in the cloning so insert data in a set and test
      std::multiset<typename ValueTraits::value_type>
         src(testset1.begin(), testset1.end());
      std::multiset<typename ValueTraits::value_type>
         dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
}

template<class VoidPointer, bool constant_time_size, bool Incremental>
class test_main_template
{
   public:
   int operator()()
   {
      typedef testvalue<hooks<VoidPointer> , constant_time_size> value_type;
      static const int random_init[6] = { 3, 2, 4, 1, 5, 2 };
      std::vector<testvalue<hooks<VoidPointer> , constant_time_size> > data (6);
      for (int i = 0; i < 6; ++i)
         data[i].value_ = random_init[i];

      test_unordered_multiset < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::base_hook_type
                  >::type
                , true
                , false
                , Incremental
                >::test_all(data);

      test_unordered_multiset < typename detail::get_member_value_traits
                  < member_hook< value_type
                               , typename hooks<VoidPointer>::member_hook_type
                               , &value_type::node_
                               >
                  >::type
                , false
                , false
                , Incremental
                >::test_all(data);
      test_unordered_multiset < nonhook_node_member_value_traits< value_type,
                                                                  typename hooks<VoidPointer>::nonhook_node_member_type,
                                                                  &value_type::nhn_member_,
                                                                  safe_link
                                                                >,
                                false,
                                false,
                                Incremental
                              >::test_all(data);
      return 0;
   }
};

template<class VoidPointer, bool Incremental>
class test_main_template<VoidPointer, false, Incremental>
{
   public:
   int operator()()
   {
      typedef testvalue<hooks<VoidPointer> , false> value_type;
      static const int random_init[6] = { 3, 2, 4, 1, 5, 2 };
      std::vector<testvalue<hooks<VoidPointer> , false> > data (6);
      for (int i = 0; i < 6; ++i)
         data[i].value_ = random_init[i];

      test_unordered_multiset < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::base_hook_type
                  >::type
                , false
                , false
                , Incremental
                >::test_all(data);

      test_unordered_multiset < typename detail::get_member_value_traits
                  < member_hook< value_type
                               , typename hooks<VoidPointer>::member_hook_type
                               , &value_type::node_
                               >
                  >::type
                , true
                , false
                , Incremental
                >::test_all(data);

      test_unordered_multiset < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::auto_base_hook_type
                  >::type
                , false
                , false
                , Incremental
                >::test_all(data);

      test_unordered_multiset < typename detail::get_member_value_traits
                  < member_hook< value_type
                               , typename hooks<VoidPointer>::auto_member_hook_type
                               , &value_type::auto_node_
                               >
                  >::type
                , false
                , true
                , Incremental
                >::test_all(data);
      return 0;
   }
};

int main()
{
   test_main_template<void*, false, true>()();
   test_main_template<smart_ptr<void>, false, true>()();
   test_main_template<void*, true, true>()();
   test_main_template<smart_ptr<void>, true, true>()();
   test_main_template<void*, false, false>()();
   test_main_template<smart_ptr<void>, false, false>()();
   test_main_template<void*, true, true>()();
   test_main_template<smart_ptr<void>, true, false>()();
   return boost::report_errors();
}


text:
package org.beanio.internal.parser.format.xml;

import javax.xml.XMLConstants;

import org.beanio.internal.parser.*;
import org.beanio.internal.util.DebugUtil;
import org.beanio.stream.xml.XmlWriter;
import org.w3c.dom.*;

/**
 * A {@link FieldFormat} for a field in an XML formatted stream parsed as
 * an element of its parent.
 *
 * @author Kevin Seim
 * @since 2.0
 */
public class XmlElementField extends XmlFieldFormat {

    private boolean repeating = false;

    private String localName;
    private String prefix;
    private String namespace;
    private boolean namespaceAware;
    private boolean nillable;

    /**
     * Constructs a new <tt>XmlElementField</tt>.
     */
    public XmlElementField() { }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlFieldFormat#extractText(org.beanio.internal.parser.format.xml.XmlUnmarshallingContext)
     */
    public String extractText(XmlUnmarshallingContext context) {
        Element node = context.findElement(this);
        if (node == null) {
            return null;
        }

        // check for nil elements
        if (XmlNodeUtil.isNil(node)) {
            return Value.NIL;
        }

        String fieldText = XmlNodeUtil.getText(node);
        if (fieldText == null) {
            fieldText = "";
        }
        return fieldText;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlFieldFormat#insertText(org.beanio.internal.parser.format.xml.XmlMarshallingContext, java.lang.String)
     */
    public void insertText(XmlMarshallingContext ctx, String fieldText) {
        if (fieldText == null && isLazy()) {
            return;
        }
        if (fieldText == Value.NIL) {
            fieldText = null;
        }

        Document document = ctx.getDocument();

        Element element = document.createElementNS(getNamespace(), getLocalName());
        if (!isNamespaceAware()) {
            element.setUserData(XmlWriter.IS_NAMESPACE_IGNORED, Boolean.TRUE, null);
        }
        else {
            if ("".equals(getPrefix())) {
                element.setUserData(XmlWriter.IS_DEFAULT_NAMESPACE, Boolean.TRUE, null);
            }
            else {
                element.setPrefix(getPrefix());
            }
        }

        if (fieldText == null && isNillable()) {
            element.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true");
        }
        else if (fieldText != null && fieldText.length() > 0) {
            element.appendChild(document.createTextNode(fieldText));
        }

        Element parent = (Element) ctx.getParent();
        parent.appendChild(element);
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#isRepeating()
     */
    public boolean isRepeating() {
        return repeating;
    }

    /**
     * Sets whether this element repeats within the context of its parent.
     * @param repeating true if repeating, false otherwise
     */
    public void setRepeating(boolean repeating) {
        this.repeating = repeating;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#getType()
     */
    public int getType() {
        return XmlNode.XML_TYPE_ELEMENT;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#getLocalName()
     */
    public String getLocalName() {
        return localName;
    }

    /**
     * Sets the element name.
     * @param localName the element name
     */
    public void setLocalName(String localName) {
        this.localName = localName;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#getNamespace()
     */
    public String getNamespace() {
        return namespace;
    }

    /**
     * Sets the namespace of this element.
     * @param namespace the namespace
     */
    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#getPrefix()
     */
    public String getPrefix() {
        return prefix;
    }

    /**
     * Sets a prefix to use for the namespace during marshalling.
     * @param prefix the namespace prefix
     */
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.FieldFormat#isNillable()
     */
    public boolean isNillable() {
        return nillable;
    }

    /**
     * Sets whether this element is nillable.
     * @param nillable true if nillable, false otherwise
     */
    public void setNillable(boolean nillable) {
        this.nillable = nillable;
    }

    /*
     * (non-Javadoc)
     * @see org.beanio.internal.parser.format.xml.XmlNode#isNamespaceAware()
     */
    public boolean isNamespaceAware() {
        return namespaceAware;
    }

    /**
     * Sets whether this element is namespace aware.
     * @param namespaceAware true if namespace aware, false otherwise
     */
    public void setNamespaceAware(boolean namespaceAware) {
        this.namespaceAware = namespaceAware;
    }

    @Override
    public void toParamString(StringBuilder s) {
        super.toParamString(s);
        s.append(", localName=").append(localName);
        if (prefix != null) {
            s.append(", prefix=").append(prefix);
        }
        if (namespace != null) {
            s.append(", xmlns=").append(isNamespaceAware() ? namespace : "*");
        }
        s.append(", ").append(DebugUtil.formatOption("nillable", nillable));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <title>Code coverage report for js/IPlugin.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../prettify.css" />
    <link rel="stylesheet" href="../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / js/ IPlugin.js

        66.67%
        Statements
        4/6

        100%
        Branches
        0/0

        25%
        Functions
        1/4

        66.67%
        Lines
        4/6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31	4×

4×

4×

4×

define(['utils', 'errors'], function(Utils, Errors) {
    "use strict";

    /**
     * @class
     * Интерфейс для плагина. Плагины, расширяющие функционал панели должны наследоваться от этого интерфейса.
     * @constructor IPlugin
     * @interface
     */
    function IPlugin() {
    }

    /**
     * Применить конфигурацию.
     * @param {Moving~config} config - конфигурация
     * @memberOf IPlugin
     */
    IPlugin.prototype.configure = function(config) {
        throw new Errors.NotRealizedError('IPlugin', 'configure');
    };

    /**
     * Уничтожить экземпляр интерфейса.
     * @memberOf IPlugin
     */
    IPlugin.prototype.destroy = function() {
        throw new Errors.NotRealizedError('IPlugin', 'destroy');
    };

    return IPlugin;
});

  Code coverage
  generated by istanbul at Mon Mar 27 2017 01:49:59 GMT+0300 (MSK)


text:
package com.draagon.meta.key;

public class PrimaryKey extends MetaKey {

    public final static String SUBTYPE = "primary";
    public final static String NAME = "primary";

    public PrimaryKey() {
        super(SUBTYPE, NAME);
    }

    @Override
    public ObjectKey getObjectKey(Object o) {
        return getObjectKeyForKeyFields( getDeclaringObject(), KeyTypes.PRIMARY, getKeyFields(), o );
    }
}


text:
#ifndef __itkFileListVideoIO_h
#define __itkFileListVideoIO_h

// Define support for FileListVideo
#ifndef ITK_VIDEO_USE_FILE_LIST
#define ITK_VIDEO_USE_FILE_LIST
#endif

#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

#include "itkVideoIOBase.h"

namespace itk
{
/** \class FileListVideoIO
 *
 * \brief VideoIO object for reading and writing videos as a sequence of frame
 *        files
 *
 * This VideoIO treats a sequential list of file names as the frames of a
 * video. The frames must be specified in a comma-separated list. Also, the
 * SplitFileNames(...) static method is made public in order to allow the
 * splitting functionality to be accessed publically.
 *
 * \ingroup Video-IO-FileList
 *
 */
class ITK_EXPORT FileListVideoIO:public VideoIOBase
{
public:
  /** Standard class typedefs. */
  typedef FileListVideoIO        Self;
  typedef VideoIOBase          Superclass;
  typedef SmartPointer< Self > Pointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(FileListVideoIO, Superclass);

  /** Close the reader and writer and reset members */
  virtual void FinishReadingOrWriting();

  /** Split up the input file names -- This is public so that places where
   * FileListVideoIO is used can access the individual file names. This is
   * mostly an issue for testing. */
  static std::vector<std::string> SplitFileNames(const char* fileList);

  /*-------- This part of the interface deals with reading data. ------ */

  /** Set to reading from file */
  virtual void SetReadFromFile();

  /** Set to reading from a camera */
  virtual void SetReadFromCamera();

  /** Determine the file type. Returns true if this ImageIO can read the
   * file specified. */
  virtual bool CanReadFile(const char *);

  /** Return whether or not the VideoIO can read from a camera */
  virtual bool CanReadCamera( unsigned long cameraID );

  /** Set the spacing and dimension information for the set filename. */
  virtual void ReadImageInformation();

  /** Reads the data from disk into the memory buffer provided. */
  virtual void Read(void *buffer);

  /** Set the next frame that should be read. Return true if you operation
   * succesful */
  virtual bool SetNextFrameToRead(unsigned long frameNumber);

  /** Accessor functions for video specific information */
  virtual double GetPositionInMSec();
  virtual double GetRatio();
  virtual unsigned long GetFrameTotal();
  virtual double GetFpS();
  virtual unsigned long GetCurrentFrame();
  virtual unsigned int GetIFrameInterval();
  virtual unsigned long GetLastIFrame();

  /** Override SetFileName to do parsing */
  virtual void SetFileName(const char* fileList);

  /** Override Accessors to pass through to internal image reader */
  virtual double GetSpacing(unsigned int i) const;
  virtual double GetOrigin(unsigned int i) const;
  virtual std::vector< double > GetDirection(unsigned int i) const;

  /*-------- This part of the interfaces deals with writing data. ----- */

  /** Determine the file type. Returns true if this ImageIO can write the
   * file specified. */
  virtual bool CanWriteFile(const char *);

  /** Writes the spacing and dimentions of the image.
   * Assumes SetFileName has been called with a valid file name. */
  virtual void WriteImageInformation();

  /** Writes the data to disk from the memory buffer provided. Make sure
   * that the IORegion has been set properly. */
  virtual void Write(const void *buffer);

  /** Set Writer Parameters */
  virtual void SetWriterParameters(double fps, std::vector<SizeValueType> dim, const char* fourCC,
                                   unsigned int nChannels, IOComponentType componentType);

protected:
  FileListVideoIO();
  ~FileListVideoIO();

  void PrintSelf(std::ostream & os, Indent indent) const;

  /** Reset member variables to empty state closed */
  void ResetMembers();

  /** Open the reader iff the writer is not open */
  void OpenReader();

  /** Open the writer iff the reader is not open */
  void OpenWriter();

private:
  FileListVideoIO(const Self &);     //purposely not implemented
  void operator=(const Self &); //purposely not implemented

  /** Member Variables */
  ImageIOBase::Pointer m_ImageIO;

  /** List of files to read */
  std::vector<std::string> m_FileNames;

};
} // end namespace itk

#endif // __itkFileListVideoIO_h


text:
using GalaSoft.MvvmLight.Messaging;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using WindowsIoTDashboard.App.Helpers;
using WindowsIoTDashboard.App.Pages;
using WindowsIoTDashboard.App.Services;

namespace WindowsIoTDashboard.App
{
    public sealed partial class MainPage : BasePage
    {
        public MainPage()
        {
            this.InitializeComponent();
            Messenger.Default.Register<Exception>(this, UserInterfaceService.Commands.HideFeedback, _ => FeedbackFlyout.Hide());
            Messenger.Default.Register<string>(this, UserInterfaceService.Commands.ShowSettings, _ => SettingsFlyout.ShowAt(SettingsButton));
            Messenger.Default.Register<string>(this, UserInterfaceService.Commands.HideRunCommand, _ => RunFlyout.Hide());
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            NavMenu.SelectedIndex = 0;
        }

        private void NavMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = (ListBox)sender;
            if (listBox.SelectedIndex == -1) return;
            NavStrip.IsPaneOpen = false;
            ContentFrame.Navigate(((NavItem)listBox.SelectedItem).Page);
        }
    }
}


text:
name: Lauren
id: lauren
---
I like music

[Twitter](https://twitter.com/ItzLaurennn_)


text:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define sizeN sizeof(stackNode2)

/**
 * NOTE: this program can only handle input with numbers less than 10
 * only. This is because the input cannot contain spaces. This was done
 * so that this program can match the input/output as given by the
 * assignment handout.
 */

/** Node structures and types for use with the stack */
struct stackNode2 {
int data;
struct stackNode2 *nextPtr;
};
typedef struct stackNode2 stackNode2;
typedef stackNode2 *stackNode2Ptr;

/** Evaluate the postfix expression. */
int evaluatePostfixExpression( char *expr );

/** Evaluate the expression op1 operator op2. */
int calculate2( int op1, int op2, char operator );

/** push2 a value on the stack.  */
void push2( stackNode2Ptr *topPtr, int value );

/** pop2 a value off the stack.  */
int pop2( stackNode2Ptr *topPtr );

/** Determine if the stack is empty.  */
int isEmpty2( stackNode2Ptr topPtr );

/** external funtion in clab_p2 */
int computePostfix(char* postfix);

void push2( stackNode2Ptr *topPtr, int value ){
	stackNode2Ptr stack = *topPtr;
	//get pointer to the first node (which will soon be the second)
	stackNode2Ptr temp = stack->nextPtr;
	//create new node
	stack->nextPtr = malloc(sizeN);
	stack->nextPtr->data = value;
	//add the rest of the stack to the end of the new node
	stack->nextPtr->nextPtr = temp;
}

int pop2( stackNode2Ptr *topPtr ){
	stackNode2Ptr stack = *topPtr;
	if (isEmpty2(stack)){
		return 0;
	}
	//get the node to be deleted
	stackNode2Ptr temp = stack->nextPtr;
	//set the new top of the stack
	stack->nextPtr = temp->nextPtr;
	//get the data to return
	int pop2 = temp->data;
	//free the memory
	free(temp);
	return pop2;
}

int isEmpty2( stackNode2Ptr topPtr ){
	if (topPtr->nextPtr == NULL){
		return 1;
	}
	return 0;
}

/** assumes given postfix expression is valid */
int evaluatePostfixExpression( char *expr ){
	//create the stack
	stackNode2Ptr stack = malloc(sizeN);

	int x, y;
	int i = 0;
	char c = expr[i];
	//read entire expression
	while (c != '\0' && i < 80){

		//check what if c is digit or operator
		if (isdigit(c)){
			// c is a number, so push2 it onto stack
			x = c - '0';
			push2(&stack, x);
		} else {
			/* c must be an operator,
			 * so have to pop2 two elements from the stack and
			 * apply the operation */
			 x = pop2(&stack);
			 y = pop2(&stack);
			 push2(&stack, calculate2(x, y, c));
		}
		c = expr[++i];
	}
	return pop2(&stack);
}

int calculate2( int op1, int op2, char operator ){
	int ans = 0;
	/* check operator and apply appropriate operation
	 * NOTE: i decided to use a loop to apply the exponent
	 * function as opposed to using pow() in the c math
	 * library which would require additional compile flags */
	switch (operator){
		case ('+'):	{
			ans = (op2 + op1);
			break;
		}

		case ('-'): {
			ans = (op2 - op1);
			break;
		}

		case ('*'): {
			ans = (op2 * op1);
			break;
		}

		case ('/'): {
			ans = (op2 / op1);
			break;
		}

		case ('^'): {
			int i = 0;
			ans = 1;
			//loop to apply exponent operation
			for (i = 0; i < op1; i++){
				ans = ans * op2;
			}
			break;
		}

		case ('%'): {
			ans = (op2 % op1);
			break;
		}
	}
	return ans;
}

int computePostfix(char* postfix){
	return evaluatePostfixExpression(postfix);;
}


text:
package org.apache.jena.sparql.core ;

import java.util.ArrayList ;
import java.util.Collection ;
import java.util.List ;

import org.apache.jena.graph.Node ;
import org.apache.jena.graph.Node_Variable ;
import org.apache.jena.sparql.ARQConstants ;
import org.apache.jena.sparql.ARQInternalErrorException ;
import org.apache.jena.sparql.engine.binding.Binding ;
import org.apache.jena.sparql.expr.ExprVar ;

/** A SPARQL variable */

public class Var extends Node_Variable
{
    /* Variable used to indicate "don't bind"
     * Each use is unique.
     */

    // Legal SPARQL variable name but note it must be exactly this
    // object, not just the same name, to be anonymous.
    public static Var ANON = new Var("?_") ;

    public static Var alloc(String varName) {
//        if ( varName.equals("_") )
//            return ANON ;
        return new Var(varName) ;
    }

    public static Var alloc(Node_Variable v) // asVar?
    {
        if ( v instanceof Var )
            return (Var)v;
        return new Var(v);
    }

    public static Var alloc(Node v) {
        if ( v instanceof Var )
            return (Var)v;
        if ( v instanceof Node_Variable )
            return new Var((Node_Variable)v);
        throw new NotAVariableException("Node: " + v);
    }

    public static Var alloc(Var v) {
        return v;
    }

    public static Var alloc(ExprVar nv)         { return new Var(nv) ; }

    /** Return the value in the binding (if node is a Var) or the node itself. */
    public static Node lookup(Binding binding, Node node) {
        if ( !Var.isVar(node) )
            return node;
        Var var = Var.alloc(node);
        return lookup(binding, var);
    }

    /** Return the value in the binding or the variable itself. */
    public static Node lookup(Binding binding, Var var) {
        Node n = binding.get(var);
        if ( n != null )
            return n;
        return var;
    }

    // Precalulated the hash code because hashCode() is used so heavily with Var's
    private final int hashCodeValue ;

    private Var(String varName)      { super(varName) ; hashCodeValue = super.hashCode() ; }

    private Var(Node_Variable v)     { this(v.getName()) ; }

    private Var(ExprVar v)           { this(v.getVarName()) ; }

    // Not needed
    public Node asNode() { return this ; }

    public String getVarName() { return getName() ; }

    static class NotAVariableException extends ARQInternalErrorException {
        NotAVariableException(String msg) { super(msg) ; }
    }

    @Override
    public final int hashCode() { return hashCodeValue ; }

    @Override
    public final boolean equals(Object other) {
        if ( this == other ) return true ;
        if ( ! ( other instanceof Var ) ) return false ;
        return super.equals(other) ;
    }

//    @Override
//    public String toString() { return node.toString() ; }

    public boolean isNamedVar() { return isNamedVarName(getName()) ; }

    public boolean isBlankNodeVar() { return isBlankNodeVarName(getName()) ; }

    public boolean isAllocVar() { return isAllocVarName(getName()) ; }

    public boolean isAnonVar() { return isAnonVar(this) ; }

    // -------

    public static String canonical(String x) {
        if ( x.startsWith("?") )
            return x.substring(1);
        if ( x.startsWith("$") )
            return x.substring(1);
        return x;
    }

    public static boolean isVar(Node node) {
        if ( node instanceof Var )
            return true;
        if ( node != null && node.isVariable() )
            throw new NotAVariableException("Node_variable (not a Var) found");
        return false;
    }

    public static boolean isRenamedVar(Node node)
    { return node.isVariable() && isRenamedVar(node.getName()) ; }

    public static boolean isRenamedVar(String x)
    { return x.startsWith(ARQConstants.allocVarScopeHiding) ; }

    public static boolean isNamedVar(Node node)
    { return node.isVariable() && isNamedVarName(node.getName()) ; }

    public static boolean isNamedVarName(String x)
    { return ! isBlankNodeVarName(x) && ! isAllocVarName(x) ; }

    public static boolean isBlankNodeVar(Node node)
    { return node.isVariable() && isBlankNodeVarName(node.getName()) ; }

    public static boolean isBlankNodeVarName(String x)
    { return x.startsWith(ARQConstants.allocVarAnonMarker) ; }

    public static boolean isAllocVar(Node node)
    { return node.isVariable() && isAllocVarName(node.getName()) ; }

    public static boolean isAllocVarName(String x)
    { return x.startsWith(ARQConstants.allocVarMarker) ; }

    /** Convert a collection of variable names to variables */
    public static List<Var> varList(Collection<String> varNames) {
        List<Var> x = new ArrayList<>();
        for ( String obj : varNames )
            x.add(Var.alloc(obj));
        return x;
    }

    public static boolean isAnonVar(Var var) {
        return var == ANON;
    }

    /** Return a list of String names from a collection of variables */
    public static List<String> varNames(Collection<Var> vars) {
        List<String> x = new ArrayList<>();
        for ( Var var : vars )
            x.add(var.getVarName());
        return x;
    }
}


text:
package com.ets.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ets.EndecaQueryProcessor;
import com.ets.model.ResponseBean;

import utils.ParameterUtils;

/**
 * Servlet implementation class MainServlet
 */
@WebServlet(description = "EndecaServlet Description", urlPatterns = { "/search" })
public class EndecaServlet extends HttpServlet {

	/* Get actual class name to be printed on */
	static Logger log = Logger.getLogger(EndecaServlet.class.getName());

	private static final long serialVersionUID = 1L;
	private String nextJSP = "/index.jsp";
	private String BEAN = "bean";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EndecaServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//		response.getWriter().append("1. Served at: ").append(request.getContextPath());
//		log.error("ERROR - LOGGING MESSAGE TEST:" + log.getLevel());
//		log.info("INFO - LOGGING MESSAGE TEST:" + log.getLevel());
//		log.debug("DEBUG - LOGGING MESSAGE TEST:" + log.getLevel());

		EndecaQueryProcessor eqp = new EndecaQueryProcessor();
		ResponseBean bean = getBean(request);

		bean.setParameterMap(request.getParameterMap());
		bean.setReferringURL(request.getHeader("referer"));
		bean.setRequestParameters(ParameterUtils.getEndecaQueryString(request.getParameterMap()));
		bean.setRequestUrl(request.getRequestURL().toString());
		eqp.run(bean);
		request.getSession().setAttribute(BEAN, bean);
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
		dispatcher.forward(request, response);
//		response.getWriter().append("1. Served at: ").append(request.getContextPath());
	}

	private ResponseBean getBean(HttpServletRequest request) {
		if (request.getSession().getAttribute(BEAN) == null)
			return new ResponseBean();
		return (ResponseBean) request.getSession().getAttribute(BEAN);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


text:
namespace alinous {namespace remote {namespace region {namespace server {namespace lock {

bool RegionTableLockManager::__init_done = __init_static_variables();
bool RegionTableLockManager::__init_static_variables(){
	Java2CppSystem::getSelf();
	ThreadContext* ctx = ThreadContext::newThreadContext();
	{
		GCNotifier __refobj1(ctx, __FILEW__, __LINE__, L"RegionTableLockManager", L"__init_static_variables");
	}
	ctx->localGC();
	delete ctx;
	return true;
}
 RegionTableLockManager::RegionTableLockManager(ThreadContext* ctx) throw()  : IObject(ctx), lockContext(GCUtils<Map<Long,RemoteTrxLockContext> >::ins(this, (new(ctx) HashMap<Long,RemoteTrxLockContext>(ctx)), ctx, __FILEW__, __LINE__, L"")), ctxlock(__GC_INS(this, (new(ctx) LockObject(ctx)), LockObject)), locks(GCUtils<Map<String,IRemoteTableLock> >::ins(this, (new(ctx) HashMap<String,IRemoteTableLock>(ctx)), ctx, __FILEW__, __LINE__, L""))
{
}
void RegionTableLockManager::__construct_impl(ThreadContext* ctx) throw()
{
}
 RegionTableLockManager::~RegionTableLockManager() throw()
{
	ThreadContext *ctx = ThreadContext::getCurentContext();
	if(ctx != nullptr){ctx->incGcDenial();}
	__releaseRegerences(false, ctx);
	if(ctx != nullptr){ctx->decGcDenial();}
}
void RegionTableLockManager::__releaseRegerences(bool prepare, ThreadContext* ctx) throw()
{
	ObjectEraser __e_obj1(ctx, __FILEW__, __LINE__, L"RegionTableLockManager", L"~RegionTableLockManager");
	__e_obj1.add(this->lockContext, this);
	lockContext = nullptr;
	__e_obj1.add(this->ctxlock, this);
	ctxlock = nullptr;
	__e_obj1.add(this->locks, this);
	locks = nullptr;
	if(!prepare){
		return;
	}
}
void RegionTableLockManager::lockTable(String* schema, String* table, int lockMode, long long trxId, NodeRegionServer* server, ThreadContext* ctx)
{
	StringBuilder* buff = (new(ctx) StringBuilder(ctx));
	buff->append(schema, ctx)->append(ConstStr::getCNST_STR_953(), ctx)->append(table, ctx);
	Long* trxIdObj = (new(ctx) Long(trxId, ctx));
	String* fullName = buff->toString(ctx);
	{
		SynchronizedBlockObj __synchronized_2(this->ctxlock, ctx);
		RemoteTrxLockContext* context = this->lockContext->get(trxIdObj, ctx);
		if(context == nullptr)
		{
			context = (new(ctx) RemoteTrxLockContext(ctx));
			this->lockContext->put(trxIdObj, context, ctx);
		}
		IRemoteTableLock* tableLock = getLock(fullName, server, true, ctx);
		context->addLock(fullName, tableLock, lockMode, ctx);
	}
}
void RegionTableLockManager::unlockShared(String* schema, String* table, long long trxId, NodeRegionServer* server, ThreadContext* ctx)
{
	StringBuilder* buff = (new(ctx) StringBuilder(ctx));
	buff->append(schema, ctx)->append(ConstStr::getCNST_STR_953(), ctx)->append(table, ctx);
	String* fullName = buff->toString(ctx);
	Long* trxIdObj = (new(ctx) Long(trxId, ctx));
	{
		SynchronizedBlockObj __synchronized_2(this->ctxlock, ctx);
		RemoteTrxLockContext* context = this->lockContext->get(trxIdObj, ctx);
		if(context == nullptr)
		{
			return;
		}
		context->releaseLock(fullName, IndexScannerLockRequirement::INSTANT_SHARE, ctx);
	}
}
void RegionTableLockManager::clearLocks(long long trxId, ThreadContext* ctx) throw()
{
	Long* trxIdObj = (new(ctx) Long(trxId, ctx));
	{
		SynchronizedBlockObj __synchronized_2(this->ctxlock, ctx);
		RemoteTrxLockContext* context = this->lockContext->get(trxIdObj, ctx);
		this->lockContext->remove(trxIdObj, ctx);
		context->releaseAll(ctx);
	}
}
IRemoteTableLock* RegionTableLockManager::getLock(String* fullName, NodeRegionServer* server, bool create, ThreadContext* ctx) throw()
{
	IRemoteTableLock* lock = this->locks->get(fullName, ctx);
	if(lock == nullptr && create)
	{
		return createTableLock(server, ctx);
	}
	return lock;
}
IRemoteTableLock* RegionTableLockManager::createTableLock(NodeRegionServer* server, ThreadContext* ctx) throw()
{
	if(server->isScale(ctx))
	{
		return nullptr;
	}
	return (new(ctx) RemoteTableLock(ctx));
}
void RegionTableLockManager::__cleanUp(ThreadContext* ctx){
}
}}}}}


text:
package com.firelizzard.firecraft.block;

import com.firelizzard.firecraft.FireCraftMod;
import com.firelizzard.firecraft.initialization.FireCraftMaterials;
import com.firelizzard.firecraft.rendering.RenderStarfield;
import com.firelizzard.firecraft.tile.StarfieldTile;

import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

public class StarfieldBlock extends Block implements ITileEntityProvider {
	public static final String NAME = "starfield";

	static {
		ClientRegistry.bindTileEntitySpecialRenderer(StarfieldTile.class, RenderStarfield.instance);
	}

	public StarfieldBlock() {
		super(FireCraftMaterials.starfield);
		setHardness(15.0F);
		setResistance(2000.0F);
		setLightLevel(1);
		setStepSound(soundTypeGlass);
		setCreativeTab(FireCraftMod.TAB);
		setBlockName(NAME);

		setHarvestLevel("pickaxe", 3);
	}

    @Override
    @SideOnly(Side.CLIENT)
    public void registerBlockIcons(IIconRegister iconRegister)
    {
        blockIcon = iconRegister.registerIcon(FireCraftMod.getAssetLocation(NAME));
    }

	@Override
	public TileEntity createNewTileEntity(World world, int metadata)
	{
		return new StarfieldTile();
	}

    @Override
    @SideOnly(Side.CLIENT)
    public int getRenderBlockPass()
    {
        return 1;
    }

	@Override
	@SideOnly(Side.CLIENT)
    public int getRenderType()
    {
        return -1;
    }
}


text:
title: Particles
author:
    username: admin
    alias: RocketTheme
date: '2016-01-01 00:00:01'
published: true
publish_date: '2016-10-04 19:24:53'
taxonomy:
    category: 'Theme Features'
process:
    markdown: true
    twig: false
markdown:
  extra: true
---

##Particles {.entry-title}

Particles are incredibly simple building blocks that Gantry 5 themes thrive on. They are easy to set up, require no coding experience to configure, and are built on an intuitive and human-readable Twig and YAML file structure that makes developing them a breeze. You can use particles to set up your logo, display content in a way that complements the theme design, and more.


text:
<img src="order-entry-service/src/main/resources/static/images/ebss-logo.png" width="250px">

This project is a proof of concept for an event-based-shopping-system (EBSS) using Spring Boot and Apache Kafka. As a result of an article by Tobias Flohre, we decided to implement the event-based-system described in the blog. For more information I suggest you read up the article first.

### Links

- Blog article by Tobias Flohre https://blog.codecentric.de/2015/09/wer-microservices-richtig-macht-braucht-keine-workflow-engine-und-kein-bpmn/
- Inspiration: Movie Database https://github.com/tobiasflohre/movie-database
- Apache Kafka http://kafka.apache.org/

## Overview

The final infrastructure will look like the following diagram:

![Planned Shopping System](https://blog.codecentric.de/files/2015/08/BPMNVsMicroservices.png "Event Based Shopping System")

## Getting started

You can use docker to get Kafka and Zookeeper up and running, or install the tools manually.

### Automatically install Apache Kafka via docker

Clone repository:

```
git clone git@github.com:wurstmeister/kafka-docker.git
cd kafka-docker
```

Start a cluster:

```
docker-compose up -d
```

Add more brokers:

```
docker-compose scale kafka=3
```

Destroy a cluster:

```
docker-compose stop
```

### Manually install Apache Kafka

Download code

```
wget http://mirror.netcologne.de/apache.org/kafka/0.8.2.0/kafka_2.10-0.8.2.0.tgz
tar -xzf kafka_2.10-0.8.2.0.tgz
cd kafka_2.10-0.8.2.0
```

Start Zookeeper

```
bin/zookeeper-server-start.sh config/zookeeper.properties
```

Start Kafka server

```
bin/kafka-server-start.sh config/server.properties
```

### Use Kafka & Zookeeper

Before you can use Kafka and Zookeeper you need to figure out the right ports. Use *docker-compose ps* to find the dynamically created ports for all docker containers.

Each Spring Boot App contains a application.properties under *src/resources*. It is important that you update the port to match your local infrastructure, before using the Spring Boot Apps.

```
~/git/kafka-docker$ docker-compose ps
         Name                        Command               State                          Ports
----------------------------------------------------------------------------------------------------------------------
kafkadocker_kafka_1       /bin/sh -c start-kafka.sh        Up      0.0.0.0:32777->9092/tcp
kafkadocker_kafka_2       /bin/sh -c start-kafka.sh        Up      0.0.0.0:32778->9092/tcp
kafkadocker_kafka_3       /bin/sh -c start-kafka.sh        Up      0.0.0.0:32779->9092/tcp
kafkadocker_zookeeper_1   /bin/sh -c /usr/sbin/sshd  ...   Up      0.0.0.0:32776->2181/tcp, 22/tcp, 2888/tcp, 3888/tcp
```

Step 1: Create a topic

Let's create a topic named "test" with a single partition and only one replica:

```
bin/kafka-topics.sh --create --zookeeper 192.168.99.100:32776 --replication-factor 1 --partitions 1 --topic test
```

We can now see that topic if we run the list topic command:

```
bin/kafka-topics.sh --list --zookeeper 192.168.99.100:32770
test
```

Step 2: Run the produces to send some messages

Run the producer and then type a few messages into the console to send to the server.

```
bin/kafka-console-producer.sh --broker-list 192.168.99.100:32777 --topic test
This is a message
This is another message
```

Step 3: Start a consumer

```
bin/kafka-console-consumer.sh --zookeeper 192.168.99.100:32776 --topic test --from-beginning
This is a message
This is another message
```

For more details see http://kafka.apache.org/documentation.html#quickstart

## Maven projects

To build all Maven projects please run:

```
mvn clean install
```

To start the Spring Boot Apps use:

```
mvn spring-boot:run
```


text:
/*global makeAjaxCall, makeHttpCall */
class AjaxAdapter {
  constructor() {
    this.name = 'ajaxAdapter';
  }
}

class NodeAdapter {
  constructor() {
    this.name = 'nodeAdapter';
  }
}

class HttpRequester {
  constructor(adapter) {
    this.adapter = adapter;
  }

  fetch(url) {
    if (this.adapter.name === 'ajaxAdapter') {
      return makeAjaxCall(url).then((response) => {
        // transform response and return
      });
    } else if (this.adapter.name === 'nodeAdapter') {
      return makeHttpCall(url).then((response) => {
        // transform response and return
      });
    }
  }
}


text:
using namespace llvm;

#define DEBUG_TYPE "powerpc-selectiondag-info"

PPCSelectionDAGInfo::PPCSelectionDAGInfo(const DataLayout *DL)
    : TargetSelectionDAGInfo(DL) {}

PPCSelectionDAGInfo::~PPCSelectionDAGInfo() {}


text:
<?php

defined('ROKCOMMON') or die('Restricted access');

/**
 *
 */
class RokCommon_Reflection_DocComment
{
    /**
     * @var array
     */
    private static $classes = array();
    /**
     * @var array
     */
    private static $methods = array();
    /**
     * @var array
     */
    private static $fields = array();
    /**
     * @var array
     */
    private static $parsedFiles = array();

    /**
     * @static
     *
     */
    public static function clearCache()
    {
        self::$classes     = array();
        self::$methods     = array();
        self::$fields      = array();
        self::$parsedFiles = array();
    }

    /**
     * @param $reflection
     *
     * @return bool
     */
    public function get($reflection)
    {
        if ($reflection instanceof ReflectionClass) {
            return $this->forClass($reflection);
        } elseif ($reflection instanceof ReflectionMethod) {
            return $this->forMethod($reflection);
        } elseif ($reflection instanceof ReflectionProperty) {
            return $this->forProperty($reflection);
        }
    }

    /**
     * @param $reflection
     *
     * @return bool
     */
    public function forClass($reflection)
    {
        $this->process($reflection->getFileName());
        $name = $reflection->getName();
        return isset(self::$classes[$name]) ? self::$classes[$name] : false;
    }

    /**
     * @param $reflection
     *
     * @return bool
     */
    public function forMethod($reflection)
    {
        $this->process($reflection->getDeclaringClass()->getFileName());
        $class  = $reflection->getDeclaringClass()->getName();
        $method = $reflection->getName();
        return isset(self::$methods[$class][$method]) ? self::$methods[$class][$method] : false;
    }

    /**
     * @param $reflection
     *
     * @return bool
     */
    public function forProperty($reflection)
    {
        $this->process($reflection->getDeclaringClass()->getFileName());
        $class = $reflection->getDeclaringClass()->getName();
        $field = $reflection->getName();
        return isset(self::$fields[$class][$field]) ? self::$fields[$class][$field] : false;
    }

    /**
     * @param $file
     */
    private function process($file)
    {
        if (!isset(self::$parsedFiles[$file])) {
            $this->parse($file);
            self::$parsedFiles[$file] = true;
        }
    }

    /**
     * @param $file
     */
    protected function parse($file)
    {
        $tokens       = $this->getTokens($file);
        $currentClass = false;
        $currentBlock = false;
        $max          = count($tokens);
        $i            = 0;
        while ($i < $max) {
            $token = $tokens[$i];
            if (is_array($token)) {
                list($code, $value) = $token;
                switch ($code) {
                    case T_DOC_COMMENT:
                        $comment = $value;
                        break;

                    case T_CLASS:
                        $class = $this->getString($tokens, $i, $max);
                        if ($comment !== false) {
                            self::$classes[$class] = $comment;
                            $comment               = false;
                        }
                        break;

                    case T_VARIABLE:
                        if ($comment !== false) {
                            $field                        = substr($token[1], 1);
                            self::$fields[$class][$field] = $comment;
                            $comment                      = false;
                        }
                        break;

                    case T_FUNCTION:
                        if ($comment !== false) {
                            $function                         = $this->getString($tokens, $i, $max);
                            self::$methods[$class][$function] = $comment;
                            $comment                          = false;
                        }

                        break;

                    // ignore
                    case T_WHITESPACE:
                    case T_PUBLIC:
                    case T_PROTECTED:
                    case T_PRIVATE:
                    case T_ABSTRACT:
                    case T_FINAL:
                    case T_VAR:
                        break;

                    default:
                        $comment = false;
                        break;
                }
            } else {
                $comment = false;
            }
            $i++;
        }
    }

    /**
     * @param $tokens
     * @param $i
     * @param $max
     *
     * @return bool
     */
    private function getString($tokens, &$i, $max)
    {
        do {
            $token = $tokens[$i];
            $i++;
            if (is_array($token)) {
                if ($token[0] == T_STRING) {
                    return $token[1];
                }
            }
        } while ($i <= $max);
        return false;
    }

    /**
     * @param $file
     *
     * @return array
     */
    private function getTokens($file)
    {
        return token_get_all(file_get_contents($file));
    }
}


text:
<!DOCTYPE html>

    <title>Architectural Visualisation - KAMIL MODZELEWSKI</title>

    <meta content="" name="description"/>
    <meta content="" name="keywords"/>
    <meta charset="utf-8">
    <link rel="icon" href="img/gui/gui_favicon.png" sizes="16x16" type="image/png">
    <link rel="stylesheet" type="text/css" href="css/main.css" />

    <video id="video-play" autoplay loop preload>
        <source type="video/mp4" src="vid/viz-002-1080p.mp4"/>
        <source type="video/webm codecs=vp8,vorbis" src="vid/viz-002-720p.webm"/>
        <source type="video/ogg codecs=theora,vorbis" src="vid/viz-002-720p.ogg"/>
        <object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">
          <param name="video-play" value="flowplayer-3.2.1.swf" />
          <param name="allowfullscreen" value="true" />
          <param name="flashvars" value="config={'clip': {'url': 'http://kmodzelewski.com/vid/viz-002-1080p.mp4', 'autoPlay':false, 'autoBuffering':true}}" />
        </object>
        Your browser does not support the video tag.
    </video>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'bq_stream'
require 'pry'
require 'timecop'

ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'


text:
class AddAddressToPlaces < ActiveRecord::Migration
  def change
    add_column :places, :address, :string
  end
end


text:
package org.apache.tomcat.websocket;

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;

public class WsFrameClient extends WsFrameBase {

    private final Log log = LogFactory.getLog(WsFrameClient.class);
    private static final StringManager sm =
            StringManager.getManager(Constants.PACKAGE_NAME);

    private final AsyncChannelWrapper channel;
    private final CompletionHandler<Integer,Void> handler;
    // Not final as it may need to be re-sized
    private volatile ByteBuffer response;

    public WsFrameClient(ByteBuffer response, AsyncChannelWrapper channel,
            WsSession wsSession, Transformation transformation) {
        super(wsSession, transformation);
        this.response = response;
        this.channel = channel;
        this.handler = new WsFrameClientCompletionHandler();
    }

    void startInputProcessing() {
        try {
            processSocketRead();
        } catch (IOException e) {
            close(e);
        }
    }

    private void processSocketRead() throws IOException {

        while (response.hasRemaining()) {
            int remaining = response.remaining();

            int toCopy = Math.min(remaining, inputBuffer.length - writePos);

            // Copy remaining bytes read in HTTP phase to input buffer used by
            // frame processing
            response.get(inputBuffer, writePos, toCopy);
            writePos += toCopy;

            // Process the data we have
            processInputBuffer();
        }
        response.clear();

        // Get some more data
        if (isOpen()) {
            channel.read(response, null, handler);
        }
    }

    private final void close(Throwable t) {
        CloseReason cr;
        if (t instanceof WsIOException) {
            cr = ((WsIOException) t).getCloseReason();
        } else {
            cr = new CloseReason(
                CloseCodes.CLOSED_ABNORMALLY, t.getMessage());
        }

        try {
            wsSession.close(cr);
        } catch (IOException ignore) {
            // Ignore
        }
    }

    @Override
    protected boolean isMasked() {
        // Data is from the server so it is not masked
        return false;
    }

    private class WsFrameClientCompletionHandler
            implements CompletionHandler<Integer,Void> {

        @Override
        public void completed(Integer result, Void attachment) {
            if (result.intValue() == -1) {
                // BZ 57762. A dropped connection will get reported as EOF
                // rather than as an error so handle it here.
                if (isOpen()) {
                    // No close frame was received
                    close(new EOFException());
                }
                // No data to process
                return;
            }
            response.flip();
            try {
                processSocketRead();
            } catch (IOException e) {
                // Only send a close message on an IOException if the client
                // has not yet received a close control message from the server
                // as the IOException may be in response to the client
                // continuing to send a message after the server sent a close
                // control message.
                if (isOpen()) {
                    log.debug(sm.getString("wsFrameClient.ioe", e));
                    close(e);
                }
            }
        }

        @Override
        public void failed(Throwable exc, Void attachment) {
            if (exc instanceof ReadBufferOverflowException) {
                // response will be empty if this exception is thrown
                response = ByteBuffer.allocate(
                        ((ReadBufferOverflowException) exc).getMinBufferSize());
                response.flip();
                try {
                    processSocketRead();
                } catch (IOException e) {
                    close(e);
                }
            } else {
                close(exc);
            }
        }
    }
}


text:
package com.gemstone.gemfire.internal.logging.log4j;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
  AlertAppenderJUnitTest.class,
  ConfigLocatorJUnitTest.class,
  FastLoggerJUnitTest.class,
  FastLoggerWithDefaultConfigJUnitTest.class,
  LocalizedMessageJUnitTest.class,
  LogWriterAppenderJUnitTest.class,
})
public class Log4jUnitTestSuite {
}


text:
using System;

namespace EspaceClient.FrontOffice.Web.ViewModels.Composites
{
    public class BlocResult
    {
        public bool AffichagePopup { get; set; }
        public String Titre { get; set; }
        public long ContenuID { get; set; }
        public String Accroche { get; set; }
        public String Texte { get; set; }
        public long TypeContenu { get; set; }
        public String UrlDestination { get; set; }
        public String Ressource1 { get; set; }
        public long? TypeRessource1 { get; set; }
        public long? TypeRessource2 { get; set; }
        public String Ressource2 { get; set; }
        public long? PereID { get; set; }
        public long Ordre { get; set; }
        public long OrdreFrere { get; set; }
        public long NombreElements { get; set; }
        public String CodeFonctionnel { get; set; }
        public long? AutreRessourceID { get; set; }
        public long? RessourceID { get; set; }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Psilopezia myrothecioides Berk. & Broome, 1875

### Remarks
null


text:
//
//  Tools.cpp
//  snmpp
//
//  Created on 21/10/2017 at 15:08.
//  Copyright Alexandre Biguet © 2017. All rights reserved.
//  Distributed under the MIT Licence
//

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>

#include "Tools.hpp"

namespace snmpp { namespace utils {

namespace pt = boost::posix_time;

/*******************************************************************************
 * Returns a string containing the current date in the form :
 * YYYY-Month-DD-H-M-S
 * where Month is e.g. Nov for November
 */

std::string getCurrentDate(){

    pt::ptime now = pt::second_clock::local_time();

    std::stringstream ss;
    ss<<now.date().year()
      <<"-"<<now.date().month()
      <<"-"<<now.date().day()
      <<"-"<<now.time_of_day().hours()
      <<"-"<<now.time_of_day().minutes()
      <<"-"<<now.time_of_day().seconds();

    return ss.str();
}

/*******************************************************************************
 * Returns a string containing the input string to which a trailing '/' was
 * added if necessary
 */

std::string addTrailingSlash(const std::string &input) {

    if (input.empty()) {
        throw std::runtime_error("addTrailingSlash : empty input string");
    }

    if (input.back() == '/') {
        return input;
    }

    std::string output(input);
    output.push_back('/');
    return output;
}

/*******************************************************************************
 * Creates a directory e.g. non/existent/path/to/dir
 *  throw if the path already exists and is not a directory
 *  throw if impossible to create the directory
 */

void createDirectory(const std::string &input) {

    boost::filesystem::path p(input);

    if (boost::filesystem::exists(p)) {

        if (! boost::filesystem::is_directory(p)) {
            throw std::runtime_error
                ("Benchmark : a path with the name '" +input+  "' already "
                    "exist and is not a directory");
        }

    } else {

        boost::system::error_code err;
        if (!boost::filesystem::create_directories(p, err)) {
            std::string reason(err.message());
            throw std::runtime_error
                ("Benchmark : Could not create new '" +input + "' directory:"
                    " [" + reason + "]");
        }
    }
}

/**
 * Returns a string containing a human readable time unit
 * Template specification for seconds
 *
 */

template <>
std::string getTimeUnit<std::chrono::seconds>(){
    return "s";
}

/**
 * Returns a string containing a human readable time unit
 * Template specification for milliseconds
 *
 */

template <>
std::string getTimeUnit<std::chrono::milliseconds>() {
    return "ms";
}

/**
 * Returns a string containing a human readable time unit
 * Template specification for microseconds
 *
 */

template <>
std::string getTimeUnit<std::chrono::microseconds>() {
    return "us";
}

/**
 * Returns a string containing a human readable time unit
 * Template specification for nanoseconds
 *
 */

template <>
std::string getTimeUnit<std::chrono::nanoseconds>() {
    return "ns";
}

}} // namespace snmpp::utils

// Tools.cpp ends here


text:
type Callback = (...param: any[])=>void;

export class EventEmitter {
    listeners: any;
    supportEvents: any;

    constructor() {
        this.listeners = {}
        this.supportEvents = {}
    }

    /**
     *
     * @param {string} evtName
     */
    protected addSupportEvent(evtName: string|string[]): void {
        if(evtName instanceof Array) evtName.forEach(evtnm=>this.addSupportEvent(evtnm));
        else this.supportEvents[evtName] = true;
    }

    /**
     *
     * @param {string} evtName event name
     * @returns {boolean} 이벤트 지원 여부.
     */
    private checkSupport(evtName: string): boolean {
        return !!this.supportEvents[evtName]
    }

    protected getSupportedEventList() {
        return ""+this.supportEvents;
    }

    /**
     *
     * @param {string} eventName
     * @param {Callback} callback
     * @param ctx
     */
    on(eventName: string, callback: Callback, ctx: any): void {
        if(!this.checkSupport(eventName)) {
            console.error(`${eventName}은 지원하지 않는 event 입니다. 제공되는 이벤트는 ${Object.keys(this.supportEvents).join(',')} 입니다.`);
            return
        }

        let evtListeners = this.listeners[eventName];
        if(evtListeners ) {
            evtListeners.push({cb: callback, ctx:ctx})
        }else {
            this.listeners[eventName] = [{cb: callback, ctx:ctx}]
        }
    }

    off(eventName: string, callback: Callback) {
        let evtListeners = this.listeners[eventName];
        if(!evtListeners) return;
        let idx = evtListeners.findIndex((v)=>v.cb==callback)
        if(idx<0) return;

        evtListeners.splice(idx,1)
    }

    fire(eventName: string, ...param: any[]) {
        let evtListeners = this.listeners[eventName];
        if(!evtListeners) return;

        evtListeners.forEach((v)=>v.cb.apply(v.ctx,param))
    }
}


text:
package com.swfarm.biz.product.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.FtpUtils;
import com.swfarm.pub.utils.UUIDHexGenerator;

public class UploadProductImageController extends SimpleFormController {

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
		Map fileMap = multiRequest.getFileMap();
		if (fileMap.values().size() > 0) {
			MultipartFile file = (MultipartFile) fileMap.values().iterator()
					.next();
			String extension = getFileExtensionName(file.getOriginalFilename());
			if (file != null
					&& ("jpg".equalsIgnoreCase(extension) || "gif"
							.equalsIgnoreCase(extension))
					|| "png".equalsIgnoreCase(extension)) {
				String relativePath = "/upload/products/images";
				String fileName = UUIDHexGenerator.getUUID() + "." + extension;
				try {
					FtpUtils.uploadFile(Env.FILE_SERVER_HOST,
							Env.FILE_SERVER_PORT, Env.FILE_SERVER_USERNAME,
							Env.FILE_SERVER_PASSWORD, relativePath, fileName,
							file.getInputStream());
				} catch (IOException e) {
					logger.error(e);
				}
				return new ModelAndView("product/uploadsuccess", "imageName",
						Env.FILE_SERVER_DOMAIN + relativePath + "/" + fileName);
			}
			return new ModelAndView("product/uploadfailure");
		} else
			return new ModelAndView("product/uploadfailure");
	}

	protected String getFileExtensionName(String fileName) {
		int i = fileName.lastIndexOf(".");
		if ((i > 0) && (i < (fileName.length() - 1)))
			return fileName.substring(i + 1).toLowerCase();
		else
			return "";
	}
}


text:
import cgi
import logging
import threading
import Queue

from webkitpy.common.webkit_finder import WebKitFinder
from webkitpy.layout_tests.breakpad.dump_reader import DumpReader

_log = logging.getLogger(__name__)

class DumpReaderMultipart(DumpReader):
    """Base class for Linux and Android breakpad dump reader."""

    def __init__(self, host, build_dir):
        super(DumpReaderMultipart, self).__init__(host, build_dir)
        self._webkit_finder = WebKitFinder(host.filesystem)
        self._breakpad_tools_available = None
        self._generated_symbols = False

    def check_is_functional(self):
        return self._check_breakpad_tools_available()

    def _get_pid_from_dump(self, dump_file):
        dump = self._read_dump(dump_file)
        if not dump:
            return None
        if 'pid' in dump:
            return dump['pid'][0]
        return None

    def _get_stack_from_dump(self, dump_file):
        dump = self._read_dump(dump_file)
        if not dump:
            return None
        if not 'upload_file_minidump' in dump:
            return None

        self._generate_breakpad_symbols_if_necessary()
        f, temp_name = self._host.filesystem.open_binary_tempfile('dmp')
        f.write("\r\n".join(dump['upload_file_minidump']))
        f.close()

        cmd = [self._path_to_minidump_stackwalk(), temp_name, self._symbols_dir()]
        try:
            stack = self._host.executive.run_command(cmd, return_stderr=False)
        except:
            _log.warning('Failed to execute "%s"', ' '.join(cmd))
            stack = None
        finally:
            self._host.filesystem.remove(temp_name)
        return stack

    def _read_dump(self, dump_file):
        with self._host.filesystem.open_binary_file_for_reading(dump_file) as f:
            boundary = f.readline().strip()[2:]
            f.seek(0)
            try:
                data = cgi.parse_multipart(f, {'boundary': boundary})
                return data
            except:
                pass
        return None

    def _check_breakpad_tools_available(self):
        if self._breakpad_tools_available is not None:
            return self._breakpad_tools_available

        REQUIRED_BREAKPAD_TOOLS = [
            'dump_syms',
            'minidump_stackwalk',
        ]
        result = True
        for binary in REQUIRED_BREAKPAD_TOOLS:
            full_path = self._host.filesystem.join(self._build_dir, binary)
            if not self._host.filesystem.exists(full_path):
                result = False
                _log.error('Unable to find %s', binary)
                _log.error('    at %s', full_path)

        if not result:
            _log.error("    Could not find breakpad tools, unexpected crashes won't be symbolized")
            _log.error('    Did you build the target blink_tests?')
            _log.error('')

        self._breakpad_tools_available = result
        return self._breakpad_tools_available

    def _path_to_minidump_stackwalk(self):
        return self._host.filesystem.join(self._build_dir, "minidump_stackwalk")

    def _path_to_generate_breakpad_symbols(self):
        return self._webkit_finder.path_from_chromium_base(
            "components", "crash", "content", "tools", "generate_breakpad_symbols.py")

    def _symbols_dir(self):
        return self._host.filesystem.join(self._build_dir, 'content_shell.syms')

    def _generate_breakpad_symbols_if_necessary(self):
        if self._generated_symbols:
            return
        self._generated_symbols = True

        _log.debug("Generating breakpad symbols")
        queue = Queue.Queue()
        thread = threading.Thread(target=_symbolize_keepalive, args=(queue,))
        thread.start()
        try:
            for binary in self._binaries_to_symbolize():
                _log.debug('  Symbolizing %s', binary)
                full_path = self._host.filesystem.join(self._build_dir, binary)
                cmd = [
                    self._path_to_generate_breakpad_symbols(),
                    '--binary=%s' % full_path,
                    '--symbols-dir=%s' % self._symbols_dir(),
                    '--build-dir=%s' % self._build_dir,
                ]
                try:
                    self._host.executive.run_command(cmd)
                except:
                    _log.error('Failed to execute "%s"', ' '.join(cmd))
        finally:
            queue.put(None)
            thread.join()
        _log.debug("Done generating breakpad symbols")

    def _binaries_to_symbolize(self):
        """This routine must be implemented by subclasses.

        Returns an array of binaries that need to be symbolized.
        """
        raise NotImplementedError()

def _symbolize_keepalive(queue):
    while True:
        _log.debug("waiting for symbolize to complete")
        try:
            queue.get(block=True, timeout=60)
            return
        except Queue.Empty:
            pass

class DumpReaderLinux(DumpReaderMultipart):
    """Linux breakpad dump reader."""

    def _binaries_to_symbolize(self):
        return ['content_shell', 'libtest_netscape_plugin.so', 'libosmesa.so']

    def _file_extension(self):
        return 'dmp'

class DumpReaderAndroid(DumpReaderMultipart):
    """Android breakpad dump reader."""

    def _binaries_to_symbolize(self):
        return ['lib/libcontent_shell_content_view.so']

    def _file_extension(self):
        return 'dmp'


text:
/* @flow strict */

import PropTypes from 'prop-types';
import React, { type Node } from 'react';

import { cssModules } from '../../bpk-react-utils';
import BpkText, { TEXT_STYLES } from '../../bpk-component-text';

import STYLES from './BpkSectionListSection.module.scss';

const getClassName = cssModules(STYLES);

type Props = {
  children: Node,
  headerText: ?string,
};

const BpkSectionListSection = (props: Props) => {
  const { children, headerText, ...rest } = props;

  return (

      {headerText && (

          <BpkText textStyle={TEXT_STYLES.label1}>{headerText}</BpkText>

      )}

        {React.Children.map(children, (child) => (

{child}

        ))}

  );
};

BpkSectionListSection.propTypes = {
  children: PropTypes.node.isRequired,
  headerText: PropTypes.string,
};

BpkSectionListSection.defaultProps = {
  headerText: null,
};

export default BpkSectionListSection;


text:
import java.io.PrintStream;
//import java.net.MalformedURLException;
//import java.net.URL;

//import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.*;

public class XMLparser {

	public static void parseAndStream(Document doc, PrintStream stream){
		NodeList uris = doc.getElementsByTagName("a");
		for(int i = 0; i < uris.getLength(); ++i){
			Node a = uris.item(i);
			if( a.hasAttributes() ){
				NamedNodeMap nnm = a.getAttributes();
				Node href = nnm.getNamedItem("href");
				stream.println(href.getTextContent());
			}
		}
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;

namespace Microsoft.CodeAnalysis.Editor.Undo
{
    [ExportWorkspaceService(typeof(ISourceTextUndoService), ServiceLayer.Default), Shared]
    internal sealed class DefaultSourceTextUndoService : ISourceTextUndoService
    {
        [ImportingConstructor]
        public DefaultSourceTextUndoService()
        {
        }

        public ISourceTextUndoTransaction RegisterUndoTransaction(SourceText sourceText, string description)
        {
            return null;
        }

        public bool BeginUndoTransaction(ITextSnapshot snapshot)
        {
            return false;
        }

        public bool EndUndoTransaction(ISourceTextUndoTransaction transaction)
        {
            return false;
        }
    }
}