text:
package gen.model.test.converters;

import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.revenj.postgres.*;
import org.revenj.postgres.converters.*;

public class EntityConverter implements ObjectConverter<gen.model.test.Entity> {

	@SuppressWarnings("unchecked")
	public EntityConverter(List<ObjectConverter.ColumnInfo> allColumns) throws java.io.IOException {
		Optional<ObjectConverter.ColumnInfo> column;

		final java.util.List<ObjectConverter.ColumnInfo> columns =
				allColumns.stream().filter(it -> "test".equals(it.typeSchema) && "Entity_entity".equals(it.typeName))
				.collect(Collectors.toList());
		columnCount = columns.size();

		readers = new ObjectConverter.Reader[columnCount];
		for (int i = 0; i < readers.length; i++) {
			readers[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
		}

		final java.util.List<ObjectConverter.ColumnInfo> columnsExtended =
				allColumns.stream().filter(it -> "test".equals(it.typeSchema) && "-ngs_Entity_type-".equals(it.typeName))
				.collect(Collectors.toList());
		columnCountExtended = columnsExtended.size();

		readersExtended = new ObjectConverter.Reader[columnCountExtended];
		for (int i = 0; i < readersExtended.length; i++) {
			readersExtended[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
		}

		column = columns.stream().filter(it -> "money".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'money' column in test Entity_entity. Check if DB is in sync");
		__index___money = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "money".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'money' column in test Entity. Check if DB is in sync");
		__index__extended_money = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "id".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'id' column in test Entity_entity. Check if DB is in sync");
		__index___id = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "id".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'id' column in test Entity. Check if DB is in sync");
		__index__extended_id = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "compositeURI".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'compositeURI' column in test Entity_entity. Check if DB is in sync");
		__index___compositeURI = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "compositeURI".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'compositeURI' column in test Entity. Check if DB is in sync");
		__index__extended_compositeURI = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "compositeID".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'compositeID' column in test Entity_entity. Check if DB is in sync");
		__index___compositeID = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "compositeID".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'compositeID' column in test Entity. Check if DB is in sync");
		__index__extended_compositeID = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "detail1".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'detail1' column in test Entity_entity. Check if DB is in sync");
		__index___detail1 = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "detail1".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'detail1' column in test Entity. Check if DB is in sync");
		__index__extended_detail1 = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "detail2".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'detail2' column in test Entity_entity. Check if DB is in sync");
		__index___detail2 = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "detail2".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'detail2' column in test Entity. Check if DB is in sync");
		__index__extended_detail2 = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "Compositeid".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Compositeid' column in test Entity_entity. Check if DB is in sync");
		__index___Compositeid = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "Compositeid".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Compositeid' column in test Entity. Check if DB is in sync");
		__index__extended_Compositeid = (int)column.get().order - 1;

		column = columns.stream().filter(it -> "Index".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Index' column in test Entity_entity. Check if DB is in sync");
		__index___Index = (int)column.get().order - 1;

		column = columnsExtended.stream().filter(it -> "Index".equals(it.columnName)).findAny();
		if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Index' column in test Entity. Check if DB is in sync");
		__index__extended_Index = (int)column.get().order - 1;
	}

	public void configure(org.revenj.patterns.ServiceLocator locator) {

		__converter_detail1 = locator.resolve(gen.model.test.converters.Detail1Converter.class);
		__converter_detail2 = locator.resolve(gen.model.test.converters.Detail2Converter.class);

		gen.model.test.Entity.__configureConverter(readers, __index___money, __index___id, __index___compositeURI, __index___compositeID, __converter_detail1, __index___detail1, __converter_detail2, __index___detail2, __index___Compositeid, __index___Index);

		gen.model.test.Entity.__configureConverterExtended(readersExtended, __index__extended_money, __index__extended_id, __index__extended_compositeURI, __index__extended_compositeID, __converter_detail1, __index__extended_detail1, __converter_detail2, __index__extended_detail2, __index__extended_Compositeid, __index__extended_Index);
	}

	@Override
	public String getDbName() {
		return "\"test\".\"Entity_entity\"";
	}

	@Override
	public gen.model.test.Entity from(PostgresReader reader) throws java.io.IOException {
		return from(reader, 0);
	}

	private gen.model.test.Entity from(PostgresReader reader, int outerContext, int context, ObjectConverter.Reader<gen.model.test.Entity>[] readers) throws java.io.IOException {
		reader.read(outerContext);
		gen.model.test.Entity instance = new gen.model.test.Entity(reader, context, readers);
		reader.read(outerContext);
		return instance;
	}

	@Override
	public PostgresTuple to(gen.model.test.Entity instance) {
		if (instance == null) return null;
		PostgresTuple[] items = new PostgresTuple[columnCount];

		items[__index___money] = org.revenj.postgres.converters.DecimalConverter.toTuple(instance.getMoney());
		items[__index___id] = org.revenj.postgres.converters.StringConverter.toTuple(instance.getId());
		if (instance.getCompositeURI() != null)items[__index___compositeURI] = new org.revenj.postgres.converters.ValueTuple(instance.getCompositeURI());;
		items[__index___compositeID] = org.revenj.postgres.converters.UuidConverter.toTupleNullable(instance.getCompositeID());
		items[__index___detail1] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDetail1(), __converter_detail1::to);
		items[__index___detail2] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDetail2(), __converter_detail2::to);
		items[__index___Compositeid] = org.revenj.postgres.converters.UuidConverter.toTuple(instance.getCompositeid());
		items[__index___Index] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getIndex());
		return RecordTuple.from(items);
	}

	private final int columnCount;
	private final ObjectConverter.Reader<gen.model.test.Entity>[] readers;

	public gen.model.test.Entity from(PostgresReader reader, int context) throws java.io.IOException {
		int cur = reader.read();
		if (cur == ',' || cur == ')') return null;
		gen.model.test.Entity instance = from(reader, context, context == 0 ? 1 : context << 1, readers);
		reader.read();
		return instance;
	}

	public gen.model.test.Entity from(PostgresReader reader, int outerContext, int context) throws java.io.IOException {
		return from(reader, outerContext, context, readers);
	}

	public PostgresTuple toExtended(gen.model.test.Entity instance) {
		if (instance == null) return null;
		PostgresTuple[] items = new PostgresTuple[columnCountExtended];

		items[__index__extended_money] = org.revenj.postgres.converters.DecimalConverter.toTuple(instance.getMoney());
		items[__index__extended_id] = org.revenj.postgres.converters.StringConverter.toTuple(instance.getId());
		if (instance.getCompositeURI() != null)items[__index__extended_compositeURI] = new org.revenj.postgres.converters.ValueTuple(instance.getCompositeURI());;
		items[__index__extended_compositeID] = org.revenj.postgres.converters.UuidConverter.toTupleNullable(instance.getCompositeID());
		items[__index__extended_detail1] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDetail1(), __converter_detail1::toExtended);
		items[__index__extended_detail2] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDetail2(), __converter_detail2::toExtended);
		items[__index__extended_Compositeid] = org.revenj.postgres.converters.UuidConverter.toTuple(instance.getCompositeid());
		items[__index__extended_Index] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getIndex());
		return RecordTuple.from(items);
	}
	private final int columnCountExtended;
	private final ObjectConverter.Reader<gen.model.test.Entity>[] readersExtended;

	public gen.model.test.Entity fromExtended(PostgresReader reader, int context) throws java.io.IOException {
		int cur = reader.read();
		if (cur == ',' || cur == ')') return null;
		gen.model.test.Entity instance = from(reader, context, context == 0 ? 1 : context << 1, readersExtended);
		reader.read();
		return instance;
	}

	public gen.model.test.Entity fromExtended(PostgresReader reader, int outerContext, int context) throws java.io.IOException {
		return from(reader, outerContext, context, readersExtended);
	}
	private final int __index___money;
	private final int __index__extended_money;
	private final int __index___id;
	private final int __index__extended_id;
	private final int __index___compositeURI;
	private final int __index__extended_compositeURI;
	private final int __index___compositeID;
	private final int __index__extended_compositeID;
	private gen.model.test.converters.Detail1Converter __converter_detail1;
	private final int __index___detail1;
	private final int __index__extended_detail1;
	private gen.model.test.converters.Detail2Converter __converter_detail2;
	private final int __index___detail2;
	private final int __index__extended_detail2;
	private final int __index___Compositeid;
	private final int __index__extended_Compositeid;
	private final int __index___Index;
	private final int __index__extended_Index;

	public static String buildURI(org.revenj.postgres.PostgresBuffer _sw, gen.model.test.Entity instance) throws java.io.IOException {
		_sw.initBuffer();
		String _tmp;
		org.revenj.postgres.converters.UuidConverter.serializeURI(_sw, instance.getCompositeid());
		_sw.addToBuffer('/');org.revenj.postgres.converters.IntConverter.serializeURI(_sw, instance.getIndex());
		return _sw.bufferToString();
	}
}


text:
def extractHyruhhaserialWordpressCom(item):
	'''
	Parser for 'hyruhhaserial.wordpress.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
		('edict chapters', 'edict',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False

redpajama_set_name: RedPajamaGithub


text:
package com.bendb.dropwizard.jooq;

import com.codahale.metrics.health.HealthCheck;
import org.jooq.Configuration;
import org.jooq.TransactionalRunnable;
import org.jooq.impl.DSL;

public class JooqHealthCheck extends HealthCheck {
    private final Configuration configuration;
    private final String validationQuery;

    public JooqHealthCheck(Configuration configuration, String validationQuery) {
        this.configuration = configuration;
        this.validationQuery = validationQuery;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    @Override
    protected Result check() throws Exception {
        DSL.using(configuration).transaction(new TransactionalRunnable() {
            @Override
            public void run(Configuration configuration) throws Exception {
                DSL.using(configuration).execute(validationQuery);
            }
        });

        return Result.healthy();
    }
}


text:
<?php

namespace Mmi\BackBundle\Form;

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

class CreneauType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('cr_nom','text',array(
                'label' => 'Nom'
            ))
            ->add('cr_desc','text',array(
                'label' => 'Description'
            ))
            ->add('categorie','text',array(
                'label' => 'Catégorie'
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mmi\BackBundle\Entity\Creneau'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'mmi_backbundle_creneau';
    }
}


text:
class TaxTribs::StatisticsReport
  def self.cases_by_date_csv
    started_cases = TribunalCase.select("date(created_at) as date, count(*) as number")
                      .group("date(created_at)")
                      .map {|c| [c.date.strftime, c.number]}

    started_dates = started_cases.inject({})  do |hash, row|
      date, number = row
      hash[date] = { 'started' => number, 'submitted' => 0 }
      hash
    end

    submitted_cases = TribunalCase.select("date(updated_at) as date, count(*) as number")
                        .where(case_status: 'submitted')
                        .group("date(updated_at)")
                        .map {|c| [c.date.strftime, c.number]}

    combined_dates = submitted_cases.each_with_object(started_dates) do |row, hash|
      date, number = row
      hash[date] ||= { 'started' => 0 }
      hash[date]['submitted'] = number
    end

    combined_dates.keys.sort.each_with_object(['Date, Started, Submitted']) do |date, arr|
      data = combined_dates.fetch(date)
      arr.push [date, data.fetch('started'), data.fetch('submitted')].join(', ')
    end.join("\n")
  end
end


text:
namespace absl {
inline namespace lts_2018_06_20 {

namespace {

using ::testing::AssertionFailure;
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::MakeExceptionSafetyTester;

using Thrower = testing::ThrowingValue<testing::TypeSpec::kEverythingThrows>;
using Optional = absl::optional<Thrower>;

using MoveThrower = testing::ThrowingValue<testing::TypeSpec::kNoThrowMove>;
using MoveOptional = absl::optional<MoveThrower>;

constexpr int kInitialInteger = 5;
constexpr int kUpdatedInteger = 10;

template <typename OptionalT>
bool ValueThrowsBadOptionalAccess(const OptionalT& optional) try {
  return (static_cast<void>(optional.value()), false);
} catch (absl::bad_optional_access) {
  return true;
}

template <typename OptionalT>
AssertionResult CheckInvariants(OptionalT* optional_ptr) {
  // Check the current state post-throw for validity
  auto& optional = *optional_ptr;

  if (optional.has_value() && ValueThrowsBadOptionalAccess(optional)) {
    return AssertionFailure()
           << "Optional with value should not throw bad_optional_access when "
              "accessing the value.";
  }
  if (!optional.has_value() && !ValueThrowsBadOptionalAccess(optional)) {
    return AssertionFailure()
           << "Optional without a value should throw bad_optional_access when "
              "accessing the value.";
  }

  // Reset to a known state
  optional.reset();

  // Confirm that the known post-reset state is valid
  if (optional.has_value()) {
    return AssertionFailure()
           << "Optional should not contain a value after being reset.";
  }
  if (!ValueThrowsBadOptionalAccess(optional)) {
    return AssertionFailure() << "Optional should throw bad_optional_access "
                                 "when accessing the value after being reset.";
  }

  return AssertionSuccess();
}

template <typename OptionalT>
AssertionResult CheckDisengaged(OptionalT* optional_ptr) {
  auto& optional = *optional_ptr;

  if (optional.has_value()) {
    return AssertionFailure()
           << "Expected optional to not contain a value but a value was found.";
  }

  return AssertionSuccess();
}

template <typename OptionalT>
AssertionResult CheckEngaged(OptionalT* optional_ptr) {
  auto& optional = *optional_ptr;

  if (!optional.has_value()) {
    return AssertionFailure()
           << "Expected optional to contain a value but no value was found.";
  }

  return AssertionSuccess();
}

TEST(OptionalExceptionSafety, ThrowingConstructors) {
  auto thrower_nonempty = Optional(Thrower(kInitialInteger));
  testing::TestThrowingCtor<Optional>(thrower_nonempty);

  auto integer_nonempty = absl::optional<int>(kInitialInteger);
  testing::TestThrowingCtor<Optional>(integer_nonempty);
  testing::TestThrowingCtor<Optional>(std::move(integer_nonempty));  // NOLINT

  testing::TestThrowingCtor<Optional>(kInitialInteger);
  using ThrowerVec = std::vector<Thrower, testing::ThrowingAllocator<Thrower>>;
  testing::TestThrowingCtor<absl::optional<ThrowerVec>>(
      absl::in_place,
      std::initializer_list<Thrower>{Thrower(), Thrower(), Thrower()},
      testing::ThrowingAllocator<Thrower>());
}

TEST(OptionalExceptionSafety, NothrowConstructors) {
  // This constructor is marked noexcept. If it throws, the program will
  // terminate.
  testing::TestThrowingCtor<MoveOptional>(MoveOptional(kUpdatedInteger));
}

TEST(OptionalExceptionSafety, Emplace) {
  // Test the basic guarantee plus test the result of optional::has_value()
  // is false in all cases
  auto disengaged_test = MakeExceptionSafetyTester().WithInvariants(
      CheckInvariants<Optional>, CheckDisengaged<Optional>);
  auto disengaged_test_empty = disengaged_test.WithInitialValue(Optional());
  auto disengaged_test_nonempty =
      disengaged_test.WithInitialValue(Optional(kInitialInteger));

  auto emplace_thrower_directly = [](Optional* optional_ptr) {
    optional_ptr->emplace(kUpdatedInteger);
  };
  EXPECT_TRUE(disengaged_test_empty.Test(emplace_thrower_directly));
  EXPECT_TRUE(disengaged_test_nonempty.Test(emplace_thrower_directly));

  auto emplace_thrower_copy = [](Optional* optional_ptr) {
    auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
    optional_ptr->emplace(thrower);
  };
  EXPECT_TRUE(disengaged_test_empty.Test(emplace_thrower_copy));
  EXPECT_TRUE(disengaged_test_nonempty.Test(emplace_thrower_copy));
}

TEST(OptionalExceptionSafety, EverythingThrowsSwap) {
  // Test the basic guarantee plus test the result of optional::has_value()
  // remains the same
  auto test =
      MakeExceptionSafetyTester().WithInvariants(CheckInvariants<Optional>);
  auto disengaged_test_empty = test.WithInitialValue(Optional())
                                   .WithInvariants(CheckDisengaged<Optional>);
  auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
                                   .WithInvariants(CheckEngaged<Optional>);

  auto swap_empty = [](Optional* optional_ptr) {
    auto empty = Optional();
    optional_ptr->swap(empty);
  };
  EXPECT_TRUE(engaged_test_nonempty.Test(swap_empty));

  auto swap_nonempty = [](Optional* optional_ptr) {
    auto nonempty =
        Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
    optional_ptr->swap(nonempty);
  };
  EXPECT_TRUE(disengaged_test_empty.Test(swap_nonempty));
  EXPECT_TRUE(engaged_test_nonempty.Test(swap_nonempty));
}

TEST(OptionalExceptionSafety, NoThrowMoveSwap) {
  // Tests the nothrow guarantee for optional of T with non-throwing move
  {
    auto empty = MoveOptional();
    auto nonempty = MoveOptional(kInitialInteger);
    EXPECT_TRUE(testing::TestNothrowOp([&]() { nonempty.swap(empty); }));
  }
  {
    auto nonempty = MoveOptional(kUpdatedInteger);
    auto empty = MoveOptional();
    EXPECT_TRUE(testing::TestNothrowOp([&]() { empty.swap(nonempty); }));
  }
  {
    auto nonempty_from = MoveOptional(kUpdatedInteger);
    auto nonempty_to = MoveOptional(kInitialInteger);
    EXPECT_TRUE(
        testing::TestNothrowOp([&]() { nonempty_to.swap(nonempty_from); }));
  }
}

TEST(OptionalExceptionSafety, CopyAssign) {
  // Test the basic guarantee plus test the result of optional::has_value()
  // remains the same
  auto test =
      MakeExceptionSafetyTester().WithInvariants(CheckInvariants<Optional>);
  auto disengaged_test_empty = test.WithInitialValue(Optional())
                                   .WithInvariants(CheckDisengaged<Optional>);
  auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
                                   .WithInvariants(CheckEngaged<Optional>);

  auto copyassign_nonempty = [](Optional* optional_ptr) {
    auto nonempty =
        Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
    *optional_ptr = nonempty;
  };
  EXPECT_TRUE(disengaged_test_empty.Test(copyassign_nonempty));
  EXPECT_TRUE(engaged_test_nonempty.Test(copyassign_nonempty));

  auto copyassign_thrower = [](Optional* optional_ptr) {
    auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
    *optional_ptr = thrower;
  };
  EXPECT_TRUE(disengaged_test_empty.Test(copyassign_thrower));
  EXPECT_TRUE(engaged_test_nonempty.Test(copyassign_thrower));
}

TEST(OptionalExceptionSafety, MoveAssign) {
  // Test the basic guarantee plus test the result of optional::has_value()
  // remains the same
  auto test =
      MakeExceptionSafetyTester().WithInvariants(CheckInvariants<Optional>);
  auto disengaged_test_empty = test.WithInitialValue(Optional())
                                   .WithInvariants(CheckDisengaged<Optional>);
  auto engaged_test_nonempty = test.WithInitialValue(Optional(kInitialInteger))
                                   .WithInvariants(CheckEngaged<Optional>);

  auto moveassign_empty = [](Optional* optional_ptr) {
    auto empty = Optional();
    *optional_ptr = std::move(empty);
  };
  EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_empty));

  auto moveassign_nonempty = [](Optional* optional_ptr) {
    auto nonempty =
        Optional(absl::in_place, kUpdatedInteger, testing::nothrow_ctor);
    *optional_ptr = std::move(nonempty);
  };
  EXPECT_TRUE(disengaged_test_empty.Test(moveassign_nonempty));
  EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_nonempty));

  auto moveassign_thrower = [](Optional* optional_ptr) {
    auto thrower = Thrower(kUpdatedInteger, testing::nothrow_ctor);
    *optional_ptr = std::move(thrower);
  };
  EXPECT_TRUE(disengaged_test_empty.Test(moveassign_thrower));
  EXPECT_TRUE(engaged_test_nonempty.Test(moveassign_thrower));
}

TEST(OptionalExceptionSafety, NothrowMoveAssign) {
  // Tests the nothrow guarantee for optional of T with non-throwing move
  {
    auto empty = MoveOptional();
    auto nonempty = MoveOptional(kInitialInteger);
    EXPECT_TRUE(testing::TestNothrowOp([&]() { nonempty = std::move(empty); }));
  }
  {
    auto nonempty = MoveOptional(kInitialInteger);
    auto empty = MoveOptional();
    EXPECT_TRUE(testing::TestNothrowOp([&]() { empty = std::move(nonempty); }));
  }
  {
    auto nonempty_from = MoveOptional(kUpdatedInteger);
    auto nonempty_to = MoveOptional(kInitialInteger);
    EXPECT_TRUE(testing::TestNothrowOp(
        [&]() { nonempty_to = std::move(nonempty_from); }));
  }
  {
    auto thrower = MoveThrower(kUpdatedInteger);
    auto empty = MoveOptional();
    EXPECT_TRUE(testing::TestNothrowOp([&]() { empty = std::move(thrower); }));
  }
  {
    auto thrower = MoveThrower(kUpdatedInteger);
    auto nonempty = MoveOptional(kInitialInteger);
    EXPECT_TRUE(
        testing::TestNothrowOp([&]() { nonempty = std::move(thrower); }));
  }
}

}  // namespace

}  // inline namespace lts_2018_06_20
}  // namespace absl


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Renaming model 'BrandGroup' into 'BrandOwner'
        db.rename_table(u'brand_group', u'brand_owner')

        # Renaming 'group_cd' field to 'owner_cd'
        db.rename_column('brand_owner', 'GROUP_CD', 'OWNER_CD')

        # Renaming 'group_nm' field to 'owner_nm'
        db.rename_column('brand_owner', 'GROUP_NM', 'OWNER_NM')

        # Renaming 'group_link' field to 'owner_link'
        db.rename_column('brand_owner', 'GROUP_LINK', 'OWNER_LINK')

        # Renaming 'group_wiki_en' field to 'owner_wiki_en'
        db.rename_column('brand_owner', 'GROUP_WIKI_EN', 'OWNER_WIKI_EN')

        # Deleting field 'Brand.group_cd'
        db.rename_column('brand', 'GROUP_CD', 'OWNER_CD')

    def backwards(self, orm):

        # No backward compatibility
        raise RuntimeError("No backwards.")

    models = {
        u'brand.brand': {
            'Meta': {'object_name': 'Brand', 'db_table': "u'brand'"},
            'brand_link': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'BRAND_LINK'", 'blank': 'True'}),
            'brand_nm': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'BRAND_NM'"}),
            'brand_type_cd': ('django.db.models.fields.IntegerField', [], {'db_column': "u'BRAND_TYPE_CD'"}),
            'bsin': ('django.db.models.fields.CharField', [], {'max_length': '6', 'primary_key': 'True', 'db_column': "u'BSIN'"}),
            'crea_dt': ('django.db.models.fields.DateTimeField', [], {'db_column': "u'CREA_DT'"}),
            'modif_dt': ('django.db.models.fields.DateTimeField', [], {'db_column': "u'MODIF_DT'"}),
            'owner_cd': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_column': "u'OWNER_CD'", 'blank': 'True'}),
            'suppr_dt': ('django.db.models.fields.DateTimeField', [], {'db_column': "u'SUPPR_DT'"}),
            'suppr_flag': ('django.db.models.fields.IntegerField', [], {'db_column': "u'SUPPR_FLAG'"})
        },
        u'brand.brandowner': {
            'Meta': {'object_name': 'BrandOwner', 'db_table': "u'brand_owner'"},
            'owner_cd': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True', 'db_column': "u'OWNER_CD'"}),
            'owner_link': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'OWNER_LINK'"}),
            'owner_nm': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'OWNER_NM'"}),
            'owner_wiki_en': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'OWNER_WIKI_EN'"})
        },
        u'brand.brandtype': {
            'Meta': {'object_name': 'BrandType', 'db_table': "u'brand_type'"},
            'brand_type_cd': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True', 'db_column': "u'BRAND_TYPE_CD'"}),
            'brand_type_nm': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "u'BRAND_TYPE_NM'"})
        }
    }

    complete_apps = ['brand']


text:
<!DOCTYPE html>

    <title>Squigglish! – Blog – Projects by Olivia Walch</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Squigglish! is an iOS drawing app that makes the lines you draw wiggle. You can draw on a solid color canvas or on photos, and your creations can be exported to movies or GIFs. Like other projects of mine with Matt, it's powered by the magic of Fourier series. You can download the app here, and look below for some sample outputs. I'll be updating this gallery with some of my favorite Squigglish creations, and anyone who's interested should feel encouraged to submit their faves!

" />
    <meta property="og:description" content="Squigglish! is an iOS drawing app that makes the lines you draw wiggle. You can draw on a solid color canvas or on photos, and your creations can be exported to movies or GIFs. Like other projects of mine with Matt, it's powered by the magic of Fourier series. You can download the app here, and look below for some sample outputs. I'll be updating this gallery with some of my favorite Squigglish creations, and anyone who's interested should feel encouraged to submit their faves!

" />

    <meta name="author" content="Blog" />

    <meta property="og:title" content="Squigglish!" />
    <meta property="twitter:title" content="Squigglish!" />

    <link rel="stylesheet" href="../../main.css">

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Blog - Projects by Olivia Walch" href="/feed.xml" />

Blog

Projects by Olivia Walch

            Blog
            About

      <link rel="stylesheet" href="../../main.css">

Squigglish!

Squigglish! is an iOS drawing app that makes the lines you draw wiggle. You can draw on a solid color canvas or on photos, and your creations can be exported to movies or GIFs. Like other projects of mine with Matt, it's powered by the magic of Fourier series. You can download the app here, and look below for some sample outputs. I'll be updating this gallery with some of my favorite Squigglish creations, and anyone who's interested should feel encouraged to submit their faves!

    Written on February 15, 2017


text:
package alma.acs.nc.sm.generated;

import alma.ACSErrTypeCommon.wrappers.AcsJIllegalStateEventEx;
import alma.ACSErrTypeCommon.wrappers.AcsJStateMachineActionEx;

/**
 * Interface to send events to the SM, similar
 * to the IDL-generated component "Operations" interface
 * <p>
 * TODO: A code-generator option should decide whether the named
 * event methods delegate to {@link #fireSignal(Enum)}
 * or to {@link #fireSignalWithErrorFeedback(Enum)},
 * and add the declared exceptions accordingly.
 * Currently we use fireSignalWithErrorFeedback.
 * @author hsommer
 */
public interface EventSubscriberSignalHandler
{
	boolean setUpEnvironment() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean startReceivingEvents() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean suspend() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean resume() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean stopReceivingEvents() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean cleanUpEnvironment() throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

	boolean fireSignal(EventSubscriberSignal signal);

	boolean fireSignalWithErrorFeedback(EventSubscriberSignal signal)
			throws AcsJIllegalStateEventEx, AcsJStateMachineActionEx;

}


text:
package cgeo.geocaching.network;

import org.junit.Test;

import static org.assertj.core.api.Java6Assertions.assertThat;

public class NetworkTest {

    @Test
    public void testRfc3986URLEncode() {
        assertThat(Network.rfc3986URLEncode("*")).isEqualTo("*");
        assertThat(Network.rfc3986URLEncode("~")).isEqualTo("~");
        assertThat(Network.rfc3986URLEncode(" ")).isEqualTo("%20");
        assertThat(Network.rfc3986URLEncode("foo @+%/")).isEqualTo("foo%20%40%2B%25%2F");
        assertThat(Network.rfc3986URLEncode("sales and marketing/Miami")).isEqualTo("sales%20and%20marketing%2FMiami");
    }

}


text:
@implementation IKNaviData

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//@synthesize address;
- (IKMkNaviData *)data {
  return &_data;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (id)data {
  IKMkNaviData data;
  memset(&data, 1, sizeof(data));
  return [[IKNaviData alloc] initWithData:[NSData dataWithBytesNoCopy:&data length:sizeof(data) freeWhenDone:NO]];
}

+ (id)dataWithData:(NSData *)data {
  return [[IKNaviData alloc] initWithData:data];
}

- (id)initWithData:(NSData *)data {
  self = [super init];
  if (self != nil) {
    memcpy(&_data, [data bytes], sizeof(_data));
//    NSLog(@"Roll %d",_data.AngleRoll);
  }
  return self;
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#define kDEGREE_FACTOR 10000000.0
#define kALTITUDE_FACTOR 1000.0

@interface IKGPSPos ()

@property(nonatomic, retain) CLLocation *location;

@end

@implementation IKGPSPos

@synthesize latitude;
@synthesize location;
@synthesize longitude;
@synthesize altitude;
@synthesize status;

- (CLLocationCoordinate2D)coordinate {
  return CLLocationCoordinate2DMake(self.latitude / kDEGREE_FACTOR, self.longitude / kDEGREE_FACTOR);
}

- (void)setCoordinate:(CLLocationCoordinate2D)coordinate {
  self.longitude = (NSInteger) (coordinate.longitude * kDEGREE_FACTOR);
  self.latitude = (NSInteger) (coordinate.latitude * kDEGREE_FACTOR);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (id)positionWithMkPos:(IKMkGPSPos *)pos {
  return [[IKGPSPos alloc] initWithMkPos:pos];
}

- (id)initWithMkPos:(IKMkGPSPos *)pos {
  self = [super init];
  if (self != nil) {
    latitude = pos->Latitude;
    longitude = pos->Longitude;
    altitude = pos->Altitude;
    status = pos->Status;
  }
  return self;
}

- (id)initWithCoordinate:(CLLocationCoordinate2D)theCoordinate {
  self = [super init];
  if (self != nil) {
    self.coordinate = theCoordinate;
    altitude = 0;
    status = 0;
  }
  return self;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSCoding
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)encodeWithCoder:(NSCoder *)aCoder {
  [aCoder encodeInteger:self.latitude forKey:@"latitude"];
  [aCoder encodeInteger:self.longitude forKey:@"longitude"];
  [aCoder encodeInteger:self.altitude forKey:@"altitude"];
  [aCoder encodeInteger:self.status forKey:@"status"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
  if ((self = [super init])) {
    latitude = [aDecoder decodeIntegerForKey:@"latitude"];
    longitude = [aDecoder decodeIntegerForKey:@"longitude"];
    altitude = [aDecoder decodeIntegerForKey:@"altitude"];
    status = [aDecoder decodeIntegerForKey:@"status"];
  }
  return self;
}

- (NSString *)description {
  return [NSString stringWithFormat:@"%ld:%ld:%ld:%ld", (long)self.latitude, (long)self.longitude, (long)self.altitude, (long)self.status];
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation IKGPSPosDev

@synthesize distance;
@synthesize bearing;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (id)positionWithMkPosDev:(IKMkGPSPosDev *)pos {
  return [[IKGPSPosDev alloc] initWithMkPosDev:pos];
}

- (id)initWithMkPosDev:(IKMkGPSPosDev *)pos {
  self = [super init];
  if (self != nil) {
    self.distance = pos->Distance;
    self.bearing = pos->Bearing;
  }
  return self;
}

- (NSString *)description {
  return [NSString stringWithFormat:@"%lu:%ld", (unsigned long)self.distance, (long)self.bearing];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSCoding
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)encodeWithCoder:(NSCoder *)aCoder {
  [aCoder encodeInteger:self.distance forKey:@"distance"];
  [aCoder encodeInteger:self.bearing forKey:@"bearing"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
  if ((self = [super init])) {
    self.distance = [aDecoder decodeIntegerForKey:@"distance"];
    self.bearing = [aDecoder decodeIntegerForKey:@"bearing"];
  }
  return self;
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark IKMotorData
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation IKMotorData : NSObject

@synthesize current, temperature, maxPWM, state;

+ (id)dataWithData:(NSData *)data {
  return [[IKMotorData alloc] initWithData:data];
}

- (id)initWithData:(NSData *)data {
  self = [super init];
  if (self != nil) {
    IKMkMotor *motorData = (IKMkMotor *) [data bytes];
    self.current = motorData->Current;
    self.temperature = motorData->Temperature;
    self.maxPWM = motorData->MaxPWM;
    self.state = motorData->State;
  }
  return self;
}

@end


text:
import unittest

# multiple classes defined in one file can be imported simply by providing a tuple
from myimports.boo.geyman import (Boogeyman, OogieBoogie)

class TestMultipleClassesPerFile(unittest.TestCase):

    def test_boogeyman(self, ):
        assert 78 == Boogeyman().echo(78)

    def test_oogieboogey(self,):
        assert 89 == OogieBoogie().echo(89)


text:
var Map = require('./collection');
var Message = require('./message');

/**
 * @type {int} type (ROOM or PRIVATE)
 * @id {string} id
 */
var Channel = function(type, id, info) {
    this.type = type;
    this.id = id;
    this.info = info;
    this.sessions = new Map();

    var self = this;
    this.onclosed = function(session) {
        self.unsubscribe(session);
    };

    if (type == Channel.Type.ROOM) {
        this.info.count = 0;
    }
}

Channel.Type = {
    ROOM: 0,
    PRIVATE: 1
}

Channel.Mode = {
    PUBLIC: 0,
    PRIVATE: 1
}

module.exports = Channel;

/**
 * Add the given session to the conversation
 * @session {Session} session
 */
Channel.prototype.subscribe = function(session) {
    if (this.type === Channel.Type.ROOM && !this.has(session)) {
        session.on('closed', this.onclosed);
        this.info.count++;
        this._notify(Message.JOIN, session);
    }
    this.sessions.add(session);
}

/**
 * Remove the given session from the conversation
 * @session {Session} session
 */
Channel.prototype.unsubscribe = function(session) {
    if (this.type === Channel.Type.ROOM && this.has(session)) {
        session.removeListener('closed', this.onclosed);
        this.info.count--;
        this._notify(Message.LEAVE, session);
    }
    this.sessions.remove(session);
}

/**
 * Notify all users in this channel about the action
 */
Channel.prototype._notify = function(action, session) {
    var self = this;
    var metadata = {
        session: session,
        channel: self.id
    };
    var message = Message.create(action, metadata);
    this.publish(message, metadata);
}

/**
 * Check if the given session has been joined to the channel
 */
Channel.prototype.has = function(session) {
    return (this.sessions.lookup(session.id) !== undefined);
}

/**
 * Deliver the given message to all sessions excluding
 * the excluded session.
 * @message {Object} message
 * @metadata {Object} metadata (excluded session...)
 */
Channel.prototype.publish = function(message, metadata) {
    this.sessions.forEach(function (session) {
        session.send(message, metadata);
    });
}


text:
import logging

from alerta.plugins import PluginBase

LOG = logging.getLogger('alerta.plugins.normalise')

class NormaliseAlert(PluginBase):

    def pre_receive(self, alert):

        LOG.info("Normalising alert...")

        # prepend severity to alert text
        alert.text = '%s: %s' % (alert.severity.upper(), alert.text)

        # supply different default values if missing
        if not alert.group or alert.group == 'Misc':
            alert.group = 'Unknown'
        if not alert.value or alert.value == 'n/a':
            alert.value = '--'

        return alert

    def post_receive(self, alert):
        return

    def status_change(self, alert, status, text):
        return


text:
package etcd

import (
	"encoding/json"
	"strings"

	etcderr "github.com/coreos/etcd/error"
	"github.com/coreos/go-etcd/etcd"

	"github.com/st3v/discovery"
)

const (
	wildcard  = "*"
	separator = "/"
)

type EtcdClient interface {
	Set(key string, value string, ttl uint64) (*etcd.Response, error)
	Get(key string, sort, recursive bool) (*etcd.Response, error)
}

type registry struct {
	namespace string
	client    EtcdClient
}

var etcdClient = func(machines []string) EtcdClient {
	return EtcdClient(etcd.NewClient(machines))
}

func NewRegistry(machines []string, namespace string) *registry {
	return &registry{
		namespace: namespace,
		client:    etcdClient(machines),
	}
}

func (r *registry) Register(i discovery.Instance, ttl uint64) error {
	_, err := r.client.Set(
		r.storePath(i),
		i.String(),
		ttl,
	)
	return err
}

func errKeyNotFound(err error) bool {
	if etcdErr, ok := err.(*etcd.EtcdError); ok {
		return etcdErr.ErrorCode == etcderr.EcodeKeyNotFound
	}
	return false
}

func (r *registry) Lookup(name, env, region string) ([]discovery.Instance, error) {
	instances := []discovery.Instance{}

	key := r.lookupPath(name, env, region)

	resp, err := r.client.Get(key, false, true)
	if err != nil {
		if errKeyNotFound(err) {
			return []discovery.Instance{}, nil
		}
		return instances, err
	}

	return lift(resp.Node, r.wildcardPath(name, env, region), 0)
}

func (r *registry) storePath(i discovery.Instance) string {
	path := path("", false, r.namespace, i.Region, i.Env, i.Name, i.ID)
	return strings.Join(path, separator)
}

func (r *registry) lookupPath(name, env, region string) string {
	path := path("", true, r.namespace, region, env, name)
	return strings.Join(path, separator)
}

func (r *registry) wildcardPath(name, env, region string) []string {
	return path(wildcard, false, "", r.namespace, region, env, name, wildcard)
}

func path(def string, skip bool, parts ...string) []string {
	var path []string

	for _, s := range parts {
		if s == "" {
			if skip {
				break
			} else if def != "" {
				s = def
			}
		}
		path = append(path, s)
	}

	return path

}

func lift(node *etcd.Node, path []string, depth int) ([]discovery.Instance, error) {
	result := []discovery.Instance{}

	for i, s := range strings.Split(node.Key, separator) {
		if path[i] != s && path[i] != wildcard {
			return result, nil
		}
	}

	if node.Dir {
		for _, n := range node.Nodes {
			instances, err := lift(n, path, depth+1)
			if err != nil {
				return []discovery.Instance{}, err
			}
			result = append(result, instances...)
		}

		return result, nil
	}

	instance := discovery.Instance{}
	if err := json.Unmarshal([]byte(node.Value), &instance); err != nil {
		return []discovery.Instance{}, err
	}

	result = append(result, instance)

	return result, nil
}


text:
use strict;
use warnings;

BEGIN { use lib '../lib'; }

use Benchmark   qw(cmpthese timethese);

use Mail::Pine::Pinerc;

my $path = '../t/pinerc';

my $std_heavy_pinerc = Mail::Pine::Pinerc->new(Path => $path);
my $std_light_pinerc = Mail::Pine::Pinerc->new(
    Path => $path,
    Opts => [
    'user-domain', 'personal-name', 'address-book',
    'feature-list', 'alt-addresses'
    ]
);
my $custom_heavy_pinerc = Mail::Pine::Pinerc->new();
my $custom_light_pinerc = Mail::Pine::Pinerc->new(
    Opts => [
    'user-domain', 'personal-name', 'address-book',
    'feature-list', 'alt-addresses'
    ]
);

cmpthese(100, {
        'Fresh Full'    =>  sub { $std_heavy_pinerc->parse() },
        'Fresh Part'    =>  sub { $std_light_pinerc->parse() },
        'Custom Full'   =>  sub { $custom_heavy_pinerc->parse() },
        'Custom Part'   =>  sub { $custom_light_pinerc->parse() },
    } );

# EOF


text:
CGFloat FBDistanceBetweenPoints(NSPoint point1, NSPoint point2)
{
    CGFloat xDelta = point2.x - point1.x;
    CGFloat yDelta = point2.y - point1.y;
    return sqrtf(xDelta * xDelta + yDelta * yDelta);
}

CGFloat FBDistancePointToLine(NSPoint point, NSPoint lineStartPoint, NSPoint lineEndPoint)
{
    CGFloat lineLength = FBDistanceBetweenPoints(lineStartPoint, lineEndPoint);
    if ( lineLength == 0 )
        return 0;
    CGFloat u = ((point.x - lineStartPoint.x) * (lineEndPoint.x - lineStartPoint.x) + (point.y - lineStartPoint.y) * (lineEndPoint.y - lineStartPoint.y)) / (lineLength * lineLength);
    NSPoint intersectionPoint = NSMakePoint(lineStartPoint.x + u * (lineEndPoint.x - lineStartPoint.x), lineStartPoint.y + u * (lineEndPoint.y - lineStartPoint.y));
    return FBDistanceBetweenPoints(point, intersectionPoint);
}

NSPoint FBAddPoint(NSPoint point1, NSPoint point2)
{
    return NSMakePoint(point1.x + point2.x, point1.y + point2.y);
}

NSPoint FBUnitScalePoint(NSPoint point, CGFloat scale)
{
    NSPoint result = point;
    CGFloat length = FBPointLength(point);
    if ( length != 0.0 ) {
        result.x *= scale/length;
        result.y *= scale/length;
    }
    return result;
}

NSPoint FBScalePoint(NSPoint point, CGFloat scale)
{
    return NSMakePoint(point.x * scale, point.y * scale);
}

CGFloat FBDotMultiplyPoint(NSPoint point1, NSPoint point2)
{
    return point1.x * point2.x + point1.y * point2.y;
}

NSPoint FBSubtractPoint(NSPoint point1, NSPoint point2)
{
    return NSMakePoint(point1.x - point2.x, point1.y - point2.y);
}

CGFloat FBPointLength(NSPoint point)
{
    return sqrtf((point.x * point.x) + (point.y * point.y));
}

CGFloat FBPointSquaredLength(NSPoint point)
{
    return (point.x * point.x) + (point.y * point.y);
}

NSPoint FBNormalizePoint(NSPoint point)
{
    NSPoint result = point;
    CGFloat length = FBPointLength(point);
    if ( length != 0.0 ) {
        result.x /= length;
        result.y /= length;
    }
    return result;
}

NSPoint FBNegatePoint(NSPoint point)
{
    return NSMakePoint(-point.x, -point.y);
}


text:
// =================================================================================================
//
//    Hammerc Framework
//    Copyright 2018 hammerc.org All Rights Reserved.
//
//    See LICENSE for full license information.
//
// =================================================================================================

namespace hammerc {
    /**
     * RESP 类定义了带有优先级的资源管理类, 作为 RES 的加载补充.
     * 底层加载仍然是基于 RES 的加载方法.
     * @author wizardc
     */
    export namespace RESP {
        /**
         * 设置最大并发加载线程数量, 默认值是 2.
         * @param thread 要设置的并发加载数.
         */
        export function setMaxLoadingThread(thread: number): void {
            instance.setMaxLoadingThread(thread);
        }

        /**
         * 异步方式获取配置里的资源. 只要是配置文件里存在的资源, 都可以通过异步方式获取.
         * @param key 对应配置文件里的 name 属性或 sbuKeys 属性的一项.
         * @param compFunc 回调函数. 示例: compFunc(data,url):void.
         * @param thisObject 回调函数的 this 引用.
         * @param priority 加载优先级, 数值越大越优先进行加载.
         */
        export function getResAsync(key: string, compFunc: Function, thisObject: any, priority: number = 0): void {
            instance.getResAsync(key, compFunc, thisObject, priority);
        }

        /**
         * 异步加载资源的 Promise 方式.
         * 注意: 如果当前的加载项的优先级比较低, 会等待到所有优先级高的对象都加载完毕才会继续向下执行, 如果已经加载好了则立即向下执行.
         * @param key 对应配置文件里的 name 属性或 sbuKeys 属性的一项.
         * @param priority 加载优先级, 数值越大越优先进行加载.
         * @returns 异步加载的 Promise 对象.
         */
        export function getResAsyncAsync(key: string, priority: number = 0): Promise<any> {
            return instance.getResAsyncAsync(key, priority);
        }

        /**
         * 通过完整 URL 方式获取外部资源.
         * @param url 要加载文件的外部路径.
         * @param compFunc 回调函数. 示例: compFunc(data,url):void.
         * @param thisObject 回调函数的 this 引用.
         * @param type 文件类型 (可选). 请使用 ResourceItem 类中定义的静态常量. 若不设置将根据文件扩展名生成.
         * @param priority 加载优先级, 数值越大越优先进行加载.
         */
        export function getResByUrl(url: string, compFunc: Function, thisObject: any, type?: string, priority: number = 0): void {
            instance.getResByUrl(url, compFunc, thisObject, type, priority);
        }

        /**
         * 异步加载资源的 Promise 方式.
         * 注意: 如果当前的加载项的优先级比较低, 会等待到所有优先级高的对象都加载完毕才会继续向下执行, 如果已经加载好了则立即向下执行.
         * @param url 要加载文件的外部路径.
         * @param type 文件类型 (可选). 请使用 ResourceItem 类中定义的静态常量. 若不设置将根据文件扩展名生成.
         * @param priority 加载优先级, 数值越大越优先进行加载.
         * @returns 异步加载的 Promise 对象.
         */
        export function getResByUrlAsync(url: string, type?: string, priority: number = 0): Promise<any> {
            return instance.getResByUrlAsync(url, type, priority);
        }

        interface ResourceItem {
            inConfig: boolean;
            key?: string;
            url?: string;
            compFunc: Function;
            thisObject: any;
            type?: string;
        }

        class Resource {
            private _maxLoadingThread: number = 2;
            private _nowLoadingThread: number = 0;

            private _priorityList: number[];
            private _priorityMap: {[priority: number]: ResourceItem[]};

            public constructor() {
                this._priorityList = [];
                this._priorityMap = {};
            }

            public setMaxLoadingThread(thread: number): void {
                this._maxLoadingThread = Math.max(thread, 1);
            }

            public getResAsync(key: string, compFunc: Function, thisObject: any, priority: number = 0): void {
                if (!this._priorityMap[priority]) {
                    this._priorityList.push(priority);
                    this._priorityList.sort(this.sortFunc);
                    this._priorityMap[priority] = [];
                }
                let list = this._priorityMap[priority];
                list.push({inConfig: true, key, compFunc, thisObject});
                this.loadNext();
            }

            public getResAsyncAsync(key: string, priority: number = 0): Promise<any> {
                return new Promise((resolve: (value?: any) => void, reject: (reason?: any) => void) => {
                    RESP.getResAsync(key, (data, url) => {
                        resolve(data);
                    }, this, priority);
                });
            }

            public getResByUrl(url: string, compFunc: Function, thisObject: any, type?: string, priority: number = 0): void {
                if (!this._priorityMap[priority]) {
                    this._priorityList.push(priority);
                    this._priorityList.sort(this.sortFunc);
                    this._priorityMap[priority] = [];
                }
                let list = this._priorityMap[priority];
                list.push({inConfig: false, url, compFunc, thisObject, type});
                this.loadNext();
            }

            public getResByUrlAsync(url: string, type?: string, priority: number = 0): Promise<any> {
                return new Promise((resolve: (value?: any) => void, reject: (reason?: any) => void) => {
                    RESP.getResByUrl(url, (data, url) => {
                        resolve(data);
                    }, this, type, priority);
                });
            }

            private sortFunc(a: number, b: number): number {
                return b - a;
            }

            private loadNext(): void {
                if (this._nowLoadingThread >= this._maxLoadingThread) {
                    return;
                }
                this._nowLoadingThread++;
                let item: ResourceItem;
                for (let priority of this._priorityList) {
                    let list = this._priorityMap[priority];
                    if (list.length > 0) {
                        item = list.shift();
                    }
                }
                if (item) {
                    if (item.inConfig) {
                        RES.getResAsync(item.key, (data: any, url: string) => {
                            this._nowLoadingThread--;
                            if (item.compFunc) {
                                // RES.getResAsync 中如果发现已经存在数据的话回调已经加过 egret.$callAsync 所以我们这里就不用加了直接回调即可
                                // egret.$callAsync(item.compFunc, item.thisObject, data, url);
                                item.compFunc.call(item.thisObject, data, url);
                            }
                            this.loadNext();
                        }, this);
                    } else {
                        RES.getResByUrl(item.url, (data: any, url: string) => {
                            this._nowLoadingThread--;
                            if (item.compFunc) {
                                // RES.getResByUrl 中如果发现已经存在数据的话回调已经加过 egret.$callAsync 所以我们这里就不用加了直接回调即可
                                // egret.$callAsync(item.compFunc, item.thisObject, data, url);
                                item.compFunc.call(item.thisObject, data, url);
                            }
                            this.loadNext();
                        }, this, item.type);
                    }
                }
            }
        }

        let instance = new Resource();
    }
}


text:
function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
	  this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
  this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual("eat a tire");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(3);
    expect(this.gonzo.hobby).toEqual("daredevil performer");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual("eat a tire");
  });
});


text:
package org.sablecc.sablecc.automaton;

import java.util.*;

import org.sablecc.exception.*;
import org.sablecc.sablecc.alphabet.*;
import org.sablecc.util.*;

class DeterministicOperation {

    private Automaton newAutomaton;

    private SortedMap<State, SortedSet<State>> stateMap = new TreeMap<>();

    private Map<SortedSet<State>, State> oldStatesToNewStateMap
            = new HashMap<>();

    private Map<State, SortedSet<State>> newStateToOldStatesMap
            = new HashMap<>();

    DeterministicOperation(
            Automaton oldAutomaton) {

        if (oldAutomaton == null) {
            throw new InternalException("oldAutomaton may not be null");
        }

        if (oldAutomaton.hasMarkers()) {
            throw new InternalException("oldAutomaton is invalid");
        }

        oldAutomaton = oldAutomaton.withoutUnreachableStates();

        this.newAutomaton = new Automaton(oldAutomaton.getAlphabet());
        WorkSet<State> workSet = new WorkSet<>();

        {
            SortedSet<State> epsilonReach
                    = oldAutomaton.getStartState().getEpsilonReach();
            State newState = this.newAutomaton.getStartState();

            map(epsilonReach, newState);

            workSet.add(newState);
        }

        while (workSet.hasNext()) {
            State newFromState = workSet.next();

            SortedSet<State> oldFromStates = getOldStates(newFromState);
            SortedMap<RichSymbol, SortedSet<State>> newTransitions
                    = new TreeMap<>();

            for (State oldFromState : oldFromStates) {
                for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldFromState
                        .getTransitions().entrySet()) {
                    RichSymbol richSymbol = entry.getKey();

                    if (richSymbol != null) {
                        SortedSet<State> newTargetStates
                                = newTransitions.get(richSymbol);

                        if (newTargetStates == null) {

                            newTargetStates = new TreeSet<>();
                            newTransitions.put(richSymbol, newTargetStates);
                        }

                        newTargetStates.addAll(entry.getValue());
                    }
                }
            }

            for (Map.Entry<RichSymbol, SortedSet<State>> entry : newTransitions
                    .entrySet()) {
                State newToState = getNewState(entry.getValue());
                newFromState.addTransition(entry.getKey(), newToState);

                workSet.add(newToState);
            }
        }

        for (Acceptation acceptation : oldAutomaton.getAcceptations()) {
            this.newAutomaton.addAcceptation(acceptation);
        }

        for (State oldState : oldAutomaton.getStates()) {
            for (Acceptation acceptation : oldState.getAcceptations()) {
                for (State newState : getNewStates(oldState)) {
                    newState.addAcceptation(acceptation);
                }
            }
        }

        this.newAutomaton.stabilize();
    }

    private State getNewState(
            SortedSet<State> oldStates) {

        SortedSet<State> epsilonReach = new TreeSet<>();

        for (State oldState : oldStates) {
            epsilonReach.addAll(oldState.getEpsilonReach());
        }

        State newState = this.oldStatesToNewStateMap.get(epsilonReach);

        if (newState == null) {
            newState = new State(this.newAutomaton);
        }

        map(epsilonReach, newState);

        return newState;
    }

    private SortedSet<State> getOldStates(
            State newState) {

        return this.newStateToOldStatesMap.get(newState);
    }

    private void map(
            SortedSet<State> oldStates,
            State newState) {

        if (oldStates == null) {
            throw new InternalException("oldStates may not be null");
        }

        if (newState == null) {
            throw new InternalException("newState may not be null");
        }

        this.oldStatesToNewStateMap.put(oldStates, newState);
        this.newStateToOldStatesMap.put(newState, oldStates);

        for (State oldState : oldStates) {
            SortedSet<State> newStates = this.stateMap.get(oldState);

            if (newStates == null) {
                newStates = new TreeSet<>();
                this.stateMap.put(oldState, newStates);
            }

            newStates.add(newState);
        }
    }

    Automaton getNewAutomaton() {

        return this.newAutomaton;
    }

    private SortedSet<State> getNewStates(
            State oldState) {

        if (oldState == null) {
            throw new InternalException("oldState may not be null");
        }

        if (!this.stateMap.containsKey(oldState)) {
            throw new InternalException("invalid oldState");
        }

        return this.stateMap.get(oldState);
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CSS Experiments With Form Field Animation</title>

    <link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />

  <link href="https://static.tutsplus.com/assets/favicon-3ef7b4f54ed4378b31ff3124d3c4bff8.png" rel="shortcut icon" type="image/png" />
  <link href="https://static.tutsplus.com/assets/apple-touch-icon-3ef7b4f54ed4378b31ff3124d3c4bff8.png" rel="apple-touch-icon" type="image/png" />

  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

      <input type="search" id="search" placeholder="Search..." />

      <input type="search" id="search" placeholder="Search..." />

      <input type="search" id="search" placeholder="Search..." />

      <input type="search" id="search" placeholder="Search..." />
    	<button class="icon"></button>


text:
package status

import (
	"context"
	"fmt"
	"sync"
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"

	"k8s.io/apimachinery/pkg/labels"

	"github.com/ghodss/yaml"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1beta1"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/utils/clock"

	"istio.io/pkg/log"
)

var scope = log.RegisterScope("status",
	"CRD distribution status debugging", 0)

type Progress struct {
	AckedInstances int
	TotalInstances int
}

func (p *Progress) PlusEquals(p2 Progress) {
	p.TotalInstances += p2.TotalInstances
	p.AckedInstances += p2.AckedInstances
}

type DistributionController struct {
	mu               sync.RWMutex
	CurrentState     map[Resource]map[string]Progress
	ObservationTime  map[string]time.Time
	UpdateInterval   time.Duration
	client           dynamic.Interface
	clock            clock.Clock
	knownResources   map[schema.GroupVersionResource]dynamic.NamespaceableResourceInterface
	currentlyWriting ResourceLock
	StaleInterval    time.Duration
	QPS              float32
	Burst            int
}

func (c *DistributionController) Start(restConfig *rest.Config, namespace string, stop <-chan struct{}) {
	scope.Info("Starting status leader controller")
	// default UpdateInterval
	if c.UpdateInterval == 0 {
		c.UpdateInterval = 200 * time.Millisecond
	}
	// default StaleInterval
	if c.StaleInterval == 0 {
		c.StaleInterval = time.Minute
	}
	if c.clock == nil {
		c.clock = clock.RealClock{}
	}
	c.CurrentState = make(map[Resource]map[string]Progress)
	c.ObservationTime = make(map[string]time.Time)
	c.knownResources = make(map[schema.GroupVersionResource]dynamic.NamespaceableResourceInterface)

	// client-go defaults to 5 QPS, with 10 Boost, which is insufficient for updating status on all the config
	// in the mesh.  These values can be configured using environment variables for tuning (see pilot/pkg/features)
	restConfig.QPS = c.QPS
	restConfig.Burst = c.Burst
	var err error
	if c.client, err = dynamic.NewForConfig(restConfig); err != nil {
		scope.Fatalf("Could not connect to kubernetes: %s", err)
	}
	// create watch
	i := informers.NewSharedInformerFactoryWithOptions(kubernetes.NewForConfigOrDie(restConfig), 1*time.Minute,
		informers.WithNamespace(namespace),
		informers.WithTweakListOptions(func(listOptions *metav1.ListOptions) {
			listOptions.LabelSelector = labels.Set(map[string]string{labelKey: "true"}).AsSelector().String()
		})).
		Core().V1().ConfigMaps()
	i.Informer().AddEventHandler(&DistroReportHandler{dc: c})
	// this will list all existing configmaps, as well as updates, right?
	ctx := NewIstioContext(stop)
	go i.Informer().Run(ctx.Done())

	//create Status Writer
	t := c.clock.Tick(c.UpdateInterval)
	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			case <-t:
				staleReporters := c.writeAllStatus(ctx)
				if len(staleReporters) > 0 {
					c.removeStaleReporters(staleReporters)
				}
			}
		}
	}()
}

func (c *DistributionController) handleReport(d DistributionReport) {
	defer c.mu.Unlock()
	c.mu.Lock()
	for resstr := range d.InProgressResources {
		res := *ResourceFromString(resstr)
		if _, ok := c.CurrentState[res]; !ok {
			c.CurrentState[res] = make(map[string]Progress)
		}
		c.CurrentState[res][d.Reporter] = Progress{d.InProgressResources[resstr], d.DataPlaneCount}
	}
	c.ObservationTime[d.Reporter] = c.clock.Now()
}

func (c *DistributionController) writeAllStatus(ctx context.Context) (staleReporters []string) {
	defer c.mu.RUnlock()
	c.mu.RLock()
	for config, fractions := range c.CurrentState {
		var distributionState Progress
		for reporter, w := range fractions {
			// check for stale data here
			if c.clock.Since(c.ObservationTime[reporter]) > c.StaleInterval {
				scope.Warnf("Status reporter %s has not been heard from since %v, deleting report.",
					reporter, c.ObservationTime[reporter])
				staleReporters = append(staleReporters, reporter)
			} else {
				distributionState.PlusEquals(w)
			}
		}
		if distributionState.TotalInstances > 0 { // this is necessary when all reports are stale.
			go c.writeStatus(ctx, config, distributionState)
		}
	}
	return
}

func (c *DistributionController) initK8sResource(gvr schema.GroupVersionResource) (result dynamic.NamespaceableResourceInterface) {
	if result, ok := c.knownResources[gvr]; ok {
		return result
	}
	result = c.client.Resource(gvr)
	c.knownResources[gvr] = result
	return
}

func (c *DistributionController) writeStatus(ctx context.Context, config Resource, distributionState Progress) {
	// Note: I'd like to use Pilot's ConfigStore here to avoid duplicate reads and writes, but
	// the update() function is not implemented, and the Get() function returns the resource
	// in a different format than is needed for k8s.updateStatus.
	c.currentlyWriting.Lock(config)
	defer c.currentlyWriting.Unlock(config)
	resourceInterface := c.initK8sResource(config.GroupVersionResource).
		Namespace(config.Namespace)
	// should this be moved to some sort of InformerCache for speed?
	current, err := resourceInterface.Get(ctx, config.Name, metav1.GetOptions{ResourceVersion: config.ResourceVersion})
	if err != nil {
		if errors.IsGone(err) || errors.IsNotFound(err) {
			// this resource has been deleted.  prune its state and move on.
			c.pruneOldVersion(config)
			return
		}
		scope.Errorf("Encountered unexpected error when retrieving status for %v: %s", config, err)
		return

	}
	if config.ResourceVersion != current.GetResourceVersion() {
		// this distribution report is for an old version of the object.  Prune and continue.
		c.pruneOldVersion(config)
		return
	}
	// check if status needs updating
	if needsReconcile, desiredStatus := ReconcileStatuses(current.Object, distributionState, c.clock); needsReconcile {
		// technically, we should be updating probe time even when reconciling isn't needed, but
		// I'm skipping that for efficiency.
		current.Object["status"] = desiredStatus
		_, err := resourceInterface.UpdateStatus(ctx, current, metav1.UpdateOptions{})
		if err != nil {
			scope.Errorf("Encountered unexpected error updating status for %v, will try again later: %s", config, err)
			return
		}
	}
}

func (c *DistributionController) pruneOldVersion(config Resource) {
	defer c.mu.Unlock()
	c.mu.Lock()
	delete(c.CurrentState, config)
}

func (c *DistributionController) removeStaleReporters(staleReporters []string) {
	defer c.mu.Unlock()
	c.mu.Lock()
	for key, fractions := range c.CurrentState {
		for _, staleReporter := range staleReporters {
			delete(fractions, staleReporter)
		}
		c.CurrentState[key] = fractions
	}
}

func GetTypedStatus(in interface{}) (out IstioStatus, err error) {
	var statusBytes []byte
	if statusBytes, err = yaml.Marshal(in); err == nil {
		err = yaml.Unmarshal(statusBytes, &out)
	}
	return
}

func boolToConditionStatus(b bool) v1beta1.ConditionStatus {
	if b {
		return metav1.ConditionTrue
	}
	return metav1.ConditionFalse
}

func ReconcileStatuses(current map[string]interface{}, desired Progress, clock clock.Clock) (bool, *IstioStatus) {
	needsReconcile := false
	currentStatus, err := GetTypedStatus(current["status"])
	desiredCondition := IstioCondition{
		Type:               Reconciled,
		Status:             boolToConditionStatus(desired.AckedInstances == desired.TotalInstances),
		LastProbeTime:      metav1.NewTime(clock.Now()),
		LastTransitionTime: metav1.NewTime(clock.Now()),
		Message:            fmt.Sprintf("%d/%d proxies up to date.", desired.AckedInstances, desired.TotalInstances),
	}
	if err != nil {
		// the status field is in an unexpected state.
		scope.Warn("Encountered unexpected status content.  Overwriting status.")
		scope.Debugf("Encountered unexpected status content.  Overwriting status: %v", current["status"])
		currentStatus = IstioStatus{
			Conditions: []IstioCondition{desiredCondition},
		}
		return true, &currentStatus
	}
	var currentCondition *IstioCondition
	conditionIndex := -1
	for i, c := range currentStatus.Conditions {
		if c.Type == Reconciled {
			currentCondition = &c
			conditionIndex = i
		}
	}
	if currentCondition == nil ||
		currentCondition.Message != desiredCondition.Message ||
		currentCondition.Status != desiredCondition.Status {
		needsReconcile = true
	}
	if conditionIndex > -1 {
		currentStatus.Conditions[conditionIndex] = desiredCondition
	} else {
		currentStatus.Conditions = append(currentStatus.Conditions, desiredCondition)
	}
	return needsReconcile, &currentStatus
}

type DistroReportHandler struct {
	dc *DistributionController
}

func (drh *DistroReportHandler) OnAdd(obj interface{}) {
	drh.HandleNew(obj)
}

func (drh *DistroReportHandler) OnUpdate(oldObj, newObj interface{}) {
	drh.HandleNew(newObj)
}

func (drh *DistroReportHandler) HandleNew(obj interface{}) {
	cm, ok := obj.(*v1.ConfigMap)
	if !ok {
		scope.Warnf("expected configmap, but received %v, discarding", obj)
		return
	}
	rptStr := cm.Data[dataField]
	scope.Debugf("using report: %s", rptStr)
	dr, err := ReportFromYaml([]byte(cm.Data[dataField]))
	if err != nil {
		scope.Warnf("received malformed distributionReport %s, discarding: %v", cm.Name, err)
		return
	}
	drh.dc.handleReport(dr)

}

func (drh *DistroReportHandler) OnDelete(obj interface{}) {
	// TODO: what do we do here?  will these ever be deleted?
}


text:
package dao

import (
	"context"
	"database/sql"
	"encoding/json"
	"time"

	"go-common/app/admin/main/workflow/model"

	"github.com/jinzhu/gorm"
	"github.com/pkg/errors"
)

// Chall will retrive challenge by cid
func (d *Dao) Chall(c context.Context, cid int64) (chall *model.Chall, err error) {
	chall = &model.Chall{}
	if db := d.ReadORM.Table("workflow_chall").Where("id=?", cid).First(chall); db.Error != nil {
		err = db.Error
		if db.RecordNotFound() {
			chall = nil
			err = nil
		} else {
			err = errors.Wrapf(err, "chall(%d)", cid)
		}
	}
	return
}

// Challs will select challenges by ids
func (d *Dao) Challs(c context.Context, cids []int64) (challs map[int64]*model.Chall, err error) {
	challs = make(map[int64]*model.Chall, len(cids))
	if len(cids) <= 0 {
		return
	}

	chlist := make([]*model.Chall, 0)
	err = d.ReadORM.Table("workflow_chall").Where("id IN (?)", cids).Find(&chlist).Error
	if err != nil {
		err = errors.WithStack(err)
		return
	}

	for _, c := range chlist {
		challs[c.Cid] = c
	}
	return
}

// StateChalls will select a set of groups by challenge ids and state
func (d *Dao) StateChalls(c context.Context, cids []int64, state int8) (challs map[int64]*model.Chall, err error) {
	challs = make(map[int64]*model.Chall, len(cids))
	challSlice := make([]*model.Chall, 0, len(cids))
	if len(cids) <= 0 {
		return
	}

	if err = d.ORM.Table("workflow_chall").Where("id IN (?)", cids).Find(&challSlice).Error; err != nil {
		err = errors.WithStack(err)
		return
	}

	for _, chall := range challSlice {
		chall.FromState()
		if chall.State != state {
			continue
		}
		challs[chall.Cid] = chall
	}

	return
}

// LastChallIDsByGids will select last chall ids by given gids
func (d *Dao) LastChallIDsByGids(c context.Context, gids []int64) (cids []int64, err error) {
	if len(gids) <= 0 {
		return
	}
	var rows *sql.Rows
	if rows, err = d.ReadORM.Table("workflow_chall").Select("max(id)").Where("gid IN (?)", gids).Group("gid").Rows(); err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var maxID int64
		if err = rows.Scan(&maxID); err != nil {
			return
		}
		cids = append(cids, maxID)
	}

	return
}

// TxUpChall will update state of a challenge
// Deprecated
func (d *Dao) TxUpChall(tx *gorm.DB, chall *model.Chall) (rows int64, err error) {
	// write old field
	chall.FromState()
	db := tx.Table("workflow_chall").Where("id=?", chall.Cid).
		Update("dispatch_state", chall.DispatchState)
	if db.Error != nil {
		err = errors.WithStack(db.Error)
		return
	}

	rows = db.RowsAffected
	return
}

// TxBatchUpChallByIDs will update state of challenges by cids
func (d *Dao) TxBatchUpChallByIDs(tx *gorm.DB, cids []int64, state int8) (err error) {
	challSlice := make([]*model.Chall, 0, len(cids))
	if len(cids) <= 0 {
		return
	}
	if err = tx.Table("workflow_chall").Where("id IN (?)", cids).Find(&challSlice).Error; err != nil {
		err = errors.WithStack(err)
		return
	}

	for _, chall := range challSlice {
		chall.SetState(uint32(state), uint8(0))
		if err = tx.Table("workflow_chall").Where("id=?", chall.Cid).
			Update("dispatch_state", chall.DispatchState).Error; err != nil {
			err = errors.WithStack(err)
			return
		}
	}

	return
}

// AttPathsByCids will select a set of attachments paths by challenge ids
func (d *Dao) AttPathsByCids(c context.Context, cids []int64) (paths map[int64][]string, err error) {
	var pathSlice []*struct {
		Cid  int64
		Path string
	}
	paths = make(map[int64][]string, len(cids))
	if len(cids) <= 0 {
		return
	}
	if err = d.ReadORM.Table("workflow_attachment").Where("cid IN (?)", cids).Select("cid,path").Find(&pathSlice).Error; err != nil {
		return
	}
	for _, cp := range pathSlice {
		if _, ok := paths[cp.Cid]; !ok {
			paths[cp.Cid] = make([]string, 0, 1)
		}
		paths[cp.Cid] = append(paths[cp.Cid], cp.Path)
	}
	return
}

// AttPathsByCid will select a set of attachments paths by challenge id
// Deprecated
func (d *Dao) AttPathsByCid(c context.Context, cid int64) (paths []string, err error) {
	paths = make([]string, 0)

	rows, err := d.ReadORM.Table("workflow_attachment").Select("cid,path").Where("cid=?", cid).Rows()
	if err != nil {
		err = errors.Wrapf(err, "cid(%d)", cid)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var cp struct {
			cid  int32
			path string
		}
		if err = rows.Scan(&cp.cid, &cp.path); err != nil {
			err = errors.WithStack(err)
			return
		}
		paths = append(paths, cp.path)
	}

	return
}

// UpChallBusState will update specified business_state by conditions
// Deprecated
func (d *Dao) UpChallBusState(c context.Context, cid int64, busState int8, assigneeAdminid int64) (err error) {
	var chall *model.Chall
	if chall, err = d.Chall(c, cid); err != nil {
		return
	}
	if chall == nil {
		err = errors.Wrapf(err, "can not find challenge cid(%d)", cid)
		return
	}
	// double write to new field
	chall.SetState(uint32(busState), uint8(1))

	if err = d.ORM.Table("workflow_chall").Where("id=?", cid).
		Update("dispatch_state", chall.DispatchState).
		Update("assignee_adminid", assigneeAdminid).
		Error; err != nil {
		err = errors.WithStack(err)
	}
	return
}

// BatchUpChallBusState will update specified business_state by conditions
func (d *Dao) BatchUpChallBusState(c context.Context, cids []int64, busState int8, assigneeAdminid int64) (err error) {
	var challs map[int64]*model.Chall

	challs, err = d.Challs(c, cids)
	if err != nil {
		return
	}
	for cid := range challs {
		challs[cid].SetState(uint32(busState), uint8(1))
		if err = d.ORM.Table("workflow_chall").Where("id=?", cid).
			Update("dispatch_state", challs[cid].DispatchState).
			Update("assignee_adminid", assigneeAdminid).Error; err != nil {
			err = errors.WithStack(err)
			return
		}
	}
	return
}

// TxChallsByBusStates select cids by business and oid
func (d *Dao) TxChallsByBusStates(tx *gorm.DB, business int8, oid int64, busStates []int8) (cids []int64, err error) {
	cids = make([]int64, 0)
	rows, err := tx.Table("workflow_chall").Where("business=? AND oid=? ",
		business, oid).Select("id,dispatch_state").Rows()
	if err != nil {
		err = errors.WithStack(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		c := &model.Chall{}
		if err = rows.Scan(&c.Cid, &c.DispatchState); err != nil {
			return
		}
		for _, busState := range busStates {
			c.FromState()
			if c.BusinessState == busState {
				cids = append(cids, int64(c.Cid))
			}
		}
	}
	return
}

// TxUpChallsBusStateByIDs will update specified business_state by conditions
func (d *Dao) TxUpChallsBusStateByIDs(tx *gorm.DB, cids []int64, busState int8, assigneeAdminid int64) (err error) {
	challSlice := make([]*model.Chall, 0)
	if err = tx.Table("workflow_chall").Where("id IN (?)", cids).
		Select("id,gid,mid,dispatch_state").Find(&challSlice).Error; err != nil {
		err = errors.WithStack(err)
		return
	}
	for _, chall := range challSlice {
		chall.SetState(uint32(busState), uint8(1))
		if err = tx.Table("workflow_chall").Where("id=?", chall.Cid).
			Update("dispatch_state", chall.DispatchState).Update("assignee_adminid", assigneeAdminid).Error; err != nil {
			err = errors.WithStack(err)
			return
		}
	}
	return
}

// TxUpChallExtraV2 will update Extra data by business oid
func (d *Dao) TxUpChallExtraV2(tx *gorm.DB, business int8, oid, adminid int64, extra map[string]interface{}) (rows int64, err error) {
	exData, err := json.Marshal(extra)
	if err != nil {
		err = errors.Wrapf(err, "business(%d) oid(%d), extra(%s)", business, oid, extra)
		return
	}
	if err = tx.Table("workflow_business").Where("business=? AND oid=?", business, oid).Update("extra", exData).Error; err != nil {
		err = errors.Wrapf(err, "business(%d), oid(%d), extra(%s)", business, oid, exData)
	}
	return
}

// UpExtraV3 will update Extra data by gids
func (d *Dao) UpExtraV3(gids []int64, adminid int64, extra string) error {
	return d.ORM.Table("workflow_business").Where("gid IN (?)", gids).Update("extra", extra).Error
}

// TxUpChallTag will update tid by cid
func (d *Dao) TxUpChallTag(tx *gorm.DB, cid int64, tid int64) (err error) {
	if err = tx.Table("workflow_chall").Where("id=?", cid).Update("tid", tid).Error; err != nil {
		err = errors.Wrapf(err, "cid(%d), tid(%d)", cid, tid)
	}
	return
}

// BatchUpChallByIDs update dispatch_state field of cids
func (d *Dao) BatchUpChallByIDs(cids []int64, dispatchState uint32, adminid int64) (err error) {
	if len(cids) <= 0 {
		return
	}
	if err = d.ORM.Table("workflow_chall").Where("id IN (?)", cids).
		Update("dispatch_state", dispatchState).Update("adminid", adminid).Error; err != nil {
		err = errors.WithStack(err)
	}
	return
}

// BatchResetAssigneeAdminID reset assignee_adminid by cids
func (d *Dao) BatchResetAssigneeAdminID(cids []int64) (err error) {
	if len(cids) <= 0 {
		return
	}
	if err = d.ORM.Table("workflow_chall").Where("id IN (?)", cids).
		Update("assignee_adminid", 0).Error; err != nil {
		err = errors.WithStack(err)
	}
	return
}

// TxUpChallAssignee update assignee_adminid and dispatch_time when admin start a mission
func (d *Dao) TxUpChallAssignee(tx *gorm.DB, cids []int64) error {
	return tx.Table("workflow_chall").Where("id IN (?)", cids).
		Update("dispatch_time", time.Now().Format("2006-01-02 15:04:05")).Error
}


text:
import random
import string
import collections

class stringsets(object):
    DEFAULT = string.ascii_letters+string.digits+string.punctuation
    HOMOGLYPH_SAFE = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    ONLY_LETTERS = string.ascii_letters
    LETTERS_AND_NUMBERS = string.ascii_letters+string.digits

def get_random_string(length,
                      stringset=stringsets.DEFAULT,
                      only_letters=False,
                      letters_and_numbers=False,
                      ignoreset=None
                      ):
    '''
    Uses random.SystemRandom to return a string with `length` characters chosen
    from `stringset`.
    >>> len(get_random_string(20) == 20

    Set only_letters=True and it will return only /[a-zA-Z]/

    Set letters_and_numbers=True and it will return /[a-zA-Z0-9]/

    Set ignoreset to some string or list/tuple of characters that should not be
    included in the return string

    Setting both will result in only letters.

    Characters from stringset may repeat (or else you could just use
    random.SystemRandom().sample())

    `length` must be non-zero positive, if not, will return None
    '''

    if length <= 0:
        return None

    # 'set' object does not support indexing
    if isinstance(stringset, set):
        stringset = ''.join(stringset)

    if only_letters:
        stringset = stringsets.ONLY_LETTERS
    elif letters_and_numbers:
        stringset = stringsets.LETTERS_AND_NUMBERS

    if ignoreset:
        stringset = ''.join((c for c in stringset if c not in ignoreset))

    rand = random.SystemRandom()
    char_list = [rand.choice(stringset) for foo in xrange(length)]
    return ''.join(char_list)


text:
var https = require("https");
var http = require("http");
var cheerio = require("cheerio");

module.exports.getClientIp = function (req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};

module.exports.getDataByHttps = function (url, callback) {
    https.get(url, function (res) {
        var data = "";
        res.on("data", function (chunk) {
            data += chunk;
        });
        res.on("end", function () {
            callback(data);
        });
        res.on("error", function () {
            callback(null);
        });
    });
};

module.exports.getDataByHttp = function (url, callback) {
    http.get(url, function (res) {
        var data = "";
        res.on("data", function (chunk) {
            data += chunk;
        });
        res.on("end", function () {
            callback(data);
        });
        res.on("error", function () {
            callback(null);
        });
    });
};


text:
package org.qi4j.api.object;

import org.qi4j.api.common.InvalidApplicationException;

/**
 * This exception is thrown if no visible Object of the requested type can be found.
 */
public class NoSuchObjectException
    extends InvalidApplicationException
{
    private static final long serialVersionUID = -1121690536365682511L;

    private final String objectType;
    private final String moduleName;

    public NoSuchObjectException( String type, String moduleName )
    {
        super( "Could not find any visible Object of type [" + type + "] in module [" +
               moduleName + "]." );
        this.objectType = type;
        this.moduleName = moduleName;
    }

    public String objectType()
    {
        return objectType;
    }

    public String moduleName()
    {
        return moduleName;
    }
}


text:
from __future__ import absolute_import

try:
    from django.conf.urls import url, include
except ImportError:
    # for Django version less than 1.4
    from django.conf.urls.defaults import url, include  # NOQA

from raven.contrib.django.resolver import RouteResolver

included_url_conf = (
    url(r'^foo/bar/(?P<param>[\w]+)', lambda x: ''),
), '', ''

example_url_conf = (
    url(r'^api/(?P<project_id>[\w_-]+)/store/$', lambda x: ''),
    url(r'^example/', include(included_url_conf)),
)

def test_no_match():
    resolver = RouteResolver()
    result = resolver.resolve('/foo/bar', example_url_conf)
    assert result == '/foo/bar'

def test_simple_match():
    resolver = RouteResolver()
    result = resolver.resolve('/report/', example_url_conf)
    assert result == '/report/'

def test_complex_match():
    resolver = RouteResolver()
    result = resolver.resolve('/api/1234/store/', example_url_conf)
    assert result == '/api/{project_id}/store/'

def test_included_match():
    resolver = RouteResolver()
    result = resolver.resolve('/example/foo/bar/baz', example_url_conf)
    assert result == '/example/foo/bar/{param}'


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.KeyVault.Models;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.KeyVault
{
    /// <summary>
    /// Removes a given certificate contact from Key Vault for certificate management
    /// </summary>
    [Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzurePrefix + "KeyVaultCertificateContact",SupportsShouldProcess = true, DefaultParameterSetName = ByNameParameterSet)]
    [OutputType(typeof(PSKeyVaultCertificateContact))]
    public class RemoveAzureKeyVaultCertificateContact : KeyVaultCmdletBase
    {
        #region Parameter Set Names

        private const string ByNameParameterSet = "ByName";
        private const string ByObjectParameterSet = "ByObject";
        private const string ByResourceIdParameterSet = "ByResourceId";

        #endregion

        /// <summary>
        /// VaultName
        /// </summary>
        [Parameter(Mandatory = true,
                   Position = 0,
                   ParameterSetName = ByNameParameterSet,
                   HelpMessage = "Vault name. Cmdlet constructs the FQDN of a vault based on the name and currently selected environment.")]
        [ValidateNotNullOrEmpty]
        public string VaultName { get; set; }

        /// <summary>
        /// Vault object
        /// </summary>
        [Parameter(Mandatory = true,
                   Position = 0,
                   ParameterSetName = ByObjectParameterSet,
                   ValueFromPipeline = true,
                   HelpMessage = "KeyVault object.")]
        [ValidateNotNullOrEmpty]
        public PSKeyVault InputObject { get; set; }

        /// <summary>
        /// Vault ResourceId
        /// </summary>
        [Parameter(Mandatory = true,
                   Position = 0,
                   ParameterSetName = ByResourceIdParameterSet,
                   ValueFromPipelineByPropertyName = true,
                   HelpMessage = "KeyVault Resource Id.")]
        [ValidateNotNullOrEmpty]
        public string ResourceId { get; set; }

        /// <summary>
        /// EmailAddress
        /// </summary>
        [Parameter(Mandatory = true,
                   Position = 1,
                   HelpMessage = "Specifies the email address of the contact.")]
        [ValidateNotNullOrEmpty]
        public string[] EmailAddress { get; set; }

        /// <summary>
        /// PassThru parameter
        /// </summary>
        [Parameter(Mandatory = false,
                   HelpMessage = "This cmdlet does not return an object by default. If this switch is specified, it returns the contact object.")]
        public SwitchParameter PassThru { get; set; }

        public override void ExecuteCmdlet()
        {
            if (InputObject != null)
            {
                VaultName = InputObject.VaultName;
            }
            else if (ResourceId != null)
            {
                var resourceIdentifier = new ResourceIdentifier(ResourceId);
                VaultName = resourceIdentifier.ResourceName;
            }

            if (ShouldProcess(VaultName, Properties.Resources.RemoveCertificateContact))
            {
                List<PSKeyVaultCertificateContact> existingContacts;

                try
                {
                    existingContacts = this.DataServiceClient.GetCertificateContacts(VaultName)?.ToList();
                }
                catch (KeyVaultErrorException exception)
                {
                    if (exception.Response.StatusCode != System.Net.HttpStatusCode.NotFound)
                    {
                        throw;
                    }

                    existingContacts = null;
                }

                foreach (var email in EmailAddress)
                {
                    existingContacts.RemoveAll(contact => string.Compare(contact.Email, email, StringComparison.OrdinalIgnoreCase) == 0);
                }

                if (existingContacts.Count == 0)
                {
                    existingContacts = null;
                }

                var resultantContacts = this.DataServiceClient.SetCertificateContacts(VaultName, existingContacts);

                if (PassThru.IsPresent)
                {
                    this.WriteObject(resultantContacts);
                }
            }
        }
    }
}


text: Create a speciality


text:
RAISERROR('Create table: [health-check].[statsDatabaseUsageHistory]', 10, 1) WITH NOWAIT
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[health-check].[statsDatabaseUsageHistory]') AND type in (N'U'))
DROP TABLE [health-check].[statsDatabaseUsageHistory]
GO
CREATE TABLE [health-check].[statsDatabaseUsageHistory]
(
	[id]						[int]	 IDENTITY (1, 1)	NOT NULL,
	[catalog_database_id]		[int]			NOT NULL,
	[instance_id]				[smallint]		NOT NULL,
	[data_size_mb]				[numeric](20,3)	NULL,
	[data_space_used_percent]	[numeric](6,2)	NULL,
	[log_size_mb]				[numeric](20,3)	NULL,
	[log_space_used_percent]	[numeric](6,2)	NULL,
	[volume_mount_point]		[nvarchar](512)	NULL,
	[event_date_utc]			[datetime]		NOT NULL,
	CONSTRAINT [PK_statsDatabaseUsageHistory] PRIMARY KEY  CLUSTERED
	(
		[id],
		[catalog_database_id]
	) ,
	CONSTRAINT [FK_statsDatabaseUsageHistory_catalogDatabaseNames] FOREIGN KEY
	(
		  [catalog_database_id]
		, [instance_id]
	)
	REFERENCES [dbo].[catalogDatabaseNames]
	(
		  [id]
		, [instance_id]
	)
)
GO

CREATE INDEX [IX_statsDatabaseUsageHistory_CatalogDatabaseID] ON [health-check].[statsDatabaseUsageHistory]( [catalog_database_id], [instance_id])
GO
CREATE INDEX [IX_statsDatabaseUsageHistory_InstanceID] ON [health-check].[statsDatabaseUsageHistory] ([instance_id])
GO


text:
from msrest.serialization import Model

class ResourceMetricName(Model):
    """Name of a metric for any resource .

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar value: metric name value.
    :vartype value: str
    :ivar localized_value: Localized metric name value.
    :vartype localized_value: str
    """

    _validation = {
        'value': {'readonly': True},
        'localized_value': {'readonly': True},
    }

    _attribute_map = {
        'value': {'key': 'value', 'type': 'str'},
        'localized_value': {'key': 'localizedValue', 'type': 'str'},
    }

    def __init__(self):
        self.value = None
        self.localized_value = None


text:
package resources;

/**
 * Write your tests for the Stock Resource here
 */
public class StockResourceTest {
    if(stockTicker==null || startDate == null || endDate == null)
    {
        //throw
    }
    if(stockTicker=="" || startDate == "" || endDate == "")
    {
        //throw
    }
    if(validateStock(stockTicker, startDate, endDate) == false)
     {
            //throw an exception
     }
    // TODO - write a test for each method in the CompanyResource class
    // Think about both positive and negative test cases:
    // What happens if no inputs are passed?
    // What happens if the input is null?

}


text:
package com.mikesamuel.cil.ast.mixins;

import com.mikesamuel.cil.ast.BaseNode;
import com.mikesamuel.cil.ast.NodeI;
import com.mikesamuel.cil.ast.NodeType;
import com.mikesamuel.cil.ast.NodeVariant;
import com.mikesamuel.cil.ast.meta.CallableInfo;
import com.mikesamuel.cil.ast.meta.MethodDescriptor;
import com.mikesamuel.cil.ast.meta.TypeSpecification;

/**
 * A reference to a specific method or constructor that can be resolved,
 * in context, to a particular method descriptor.
 */
public interface MethodDescriptorReference<
    B extends BaseNode,
    T extends Enum<T> & NodeType,
    V extends NodeVariant>
extends NodeI {

  /**
   * The method descriptor if known.  Usually set by the class member and
   * typing passes.
   */
  MethodDescriptor getMethodDescriptor();

  /**
   * @param newMethodDescriptor a well-formed method descriptor per
   *     JVM 4.3.3
   * @return this
   */
  MethodDescriptorReference setMethodDescriptor(
      MethodDescriptor newMethodDescriptor);

  /**
   * The name of the type that declares the referenced method.
   */
  TypeSpecification getMethodDeclaringType();

  /**
   * The name of the type that declares the referenced method.
   * @return this
   */
  MethodDescriptorReference setMethodDeclaringType(
      TypeSpecification newMethodDeclaringType);

  /**
   * Info for the referenced method.
   */
  CallableInfo getCallableInfo();

  /**
   * Sets info for the referenced method.
   * @return this
   */
  MethodDescriptorReference setCallableInfo(CallableInfo newCallableInfo);
}


text:
namespace DFSRecursiveOOPGraph
{
    using System;
    using System.Collections.Generic;

    public class RecursiveDfs
    {
        public static void Main()
        {
            var graph = new Graph(
                new[]
                    {
                        new[] { 3, 6 }, // successors of vertice 0
                        new[] { 2, 3, 4, 5, 6 }, // successors of vertice 1
                        new[] { 1, 4, 5 }, // successors of vertice 2
                        new[] { 0, 1, 5 }, // successors of vertice 3
                        new[] { 1, 2, 6 }, // successors of vertice 4
                        new[] { 1, 2, 3 }, // successors of vertice 5
                        new[] { 0, 1, 4 } // successors of vertice 6
                    });

            graph.DfsRecursive(0);
        }
    }

    public class Graph
    {
        private readonly HashSet<int> visited;
        private readonly int[][] childNodes;

        public Graph(int[][] nodes)
        {
            this.childNodes = nodes;
            this.visited = new HashSet<int>();
        }

        public void DfsRecursive(int node)
        {
            if (!this.visited.Contains(node))
            {
                this.visited.Add(node);
                Console.WriteLine(node);

                for (int i = 0; i < this.childNodes[node].Length; i++)
                {
                    this.DfsRecursive(this.childNodes[node][i]);
                }
            }
        }
    }
}