text:
namespace eja
{
	// Static
	//static const size_t s_timeout_ms[] = { 0, 100, 161, 261, 423, 685, 1109, 1794, 2903 };
	static const size_t s_timeout_ms[] = { 0, 100, 100, 200, 300, 500, 800, 1300, 2100, 3400 };
	static const size_t s_timeout_size = sizeof(s_timeout_ms) / sizeof(size_t);
	static const size_t s_timeout_max = s_timeout_ms[s_timeout_size - 1];

	// Interface
	void transfer_component::update(const u64 size)
	{
		component::update();

		// Status
		const auto owner = get_owner();

		if (is_running())
		{
			// Timeout
			const auto timeout = owner->get<timeout_component>();
			timeout->update();

			// Timer
			if (!has_progress())
			{
				const auto timer = owner->get<timer_component>();
				timer->restart();
			}

			const auto status = owner->get<status_component>();
			status->set_success();
		}

		// Size
		m_progress += size;
		m_size += size;

		m_retry = 0;
		m_wait = 0;

		// Done?
		const auto file = owner->get<file_component>();
		if (m_size >= file->get_size())
		{
			stop();

			set_done(true);
		}

		// Should never trigger for download
		assert(m_progress <= file->get_size());
		assert(m_size <= file->get_size());
	}

	void transfer_list_component::clear()
	{
		thread_safe_ex<component, std::deque<entity::ptr>>::clear();

		m_next = 0;
	}

	// Utility
	void transfer_component::start()
	{
		if (!is_running())
		{
			set_running(true);

			m_progress = 0;

			// Status
			const auto owner = get_owner();
			const auto status = owner->get<status_component>();
			status->set_pending();

			// Timeout
			const auto timeout = owner->get<timeout_component>();
			timeout->start();

			// Timer
			const auto timer = owner->get<timer_component>();
			timer->start();
		}
	}

	void transfer_component::stop()
	{
		if (is_running())
		{
			set_running(false);

			// Timer
			const auto owner = get_owner();
			const auto timer = owner->get<timer_component>();
			timer->stop();

			// Timeout
			const auto timeout = owner->get<timeout_component>();
			timeout->stop();

			// Transfer
			if (!is_done())
			{
				if (owner->has<transfer_map_component>())
				{
					const auto transfer_map = owner->get<transfer_map_component>();
					{
						thread_lock(transfer_map);
						transfer_map->clear();
					}
				}

				if (owner->has<transfer_list_component>())
				{
					const auto transfer_list = owner->get<transfer_list_component>();
					{
						thread_lock(transfer_list);
						transfer_list->clear();
					}
				}
			}

			//m_retry = 0;
			m_wait = 0;
		}
	}

	void transfer_component::pause()
	{
		if (!is_paused())
		{
			set_paused(true);

			if (is_running())
			{
				set_running(false);

				// Timer
				const auto owner = get_owner();
				const auto timer = owner->get<timer_component>();
				timer->stop();

				// Timeout
				const auto timeout = owner->get<timeout_component>();
				timeout->stop();

				//m_retry = 0;
				m_wait = 0;

				// Status
				const auto status = owner->get<status_component>();
				status->set_pending();
			}
		}
	}

	void transfer_component::reset()
	{
		m_retry = 0;

		set_cancelled(false);
		set_done(false);
		set_errored(false);
	}

	void transfer_component::resume()
	{
		if (is_paused())
			set_paused(false);
	}

	void transfer_component::cancel()
	{
		if (!is_done())
		{
			stop();

			m_retry = 0;

			set_cancelled(true);
			set_done(true);
			set_paused(false);
		}
	}

	void transfer_component::error()
	{
		if (!is_done())
		{
			stop();

			m_retry = 0;

			set_done(true);
			set_errored(true);
			set_paused(false);
		}
	}

	void transfer_component::finish()
	{
		if (!is_done())
		{
			stop();

			m_retry = 0;

			set_done(true);
			set_paused(false);
		}
	}

	// Has
	bool transfer_component::has_chunks() const
	{
		const auto owner = get_owner();
		if (owner->has<chunk_list_component>())
		{
			const auto chunk_list = owner->get<chunk_list_component>();
			if (!chunk_list->empty())
				return true;

			const auto chunk_set = owner->get<chunk_set_component>();
			if (!chunk_set->empty())
				return true;
		}

		return false;
	}

	// Is
	bool transfer_component::is_done() const
	{
		if (is_mode(bits::done))
			return true;

		const auto owner = get_owner();
		const auto file = owner->get<file_component>();
		assert(m_size <= file->get_size());

		return m_size == file->get_size();
	}

	bool transfer_component::is_download() const
	{
		const auto owner = get_owner();
		return owner->has<transfer_list_component>();
	}

	// Get
	size_t transfer_component::get_chunks() const
	{
		const auto owner = get_owner();
		if (owner->has<chunk_list_component>())
		{
			const auto chunk_list = owner->get<chunk_list_component>();
			const auto chunk_set = owner->get<chunk_set_component>();
			return chunk_list->size() + chunk_set->size();
		}

		return 0;
	}

	u64 transfer_component::get_remaining() const
	{
		const auto owner = get_owner();
		const auto file = owner->get<file_component>();
		assert(m_size <= file->get_size());

		return file->get_size() - m_size;
	}

	std::string transfer_component::get_time() const
	{
		size_t ms = 0;

		if (is_running())
		{
			const auto owner = get_owner();
			const auto timer = owner->get<timer_component>();

			if (has_progress())
			{
				const auto ratio = static_cast<double>(timer->get_milliseconds()) / static_cast<double>(m_progress);
				const auto file = owner->get<file_component>();
				assert(m_progress <= file->get_size());

				ms = static_cast<size_t>(ratio * (file->get_size() - m_size));
			}
			else
			{
				ms = timer->get_milliseconds();
			}
		}
		else if (is_done())
		{
			const auto owner = get_owner();
			const auto timer = owner->get<timer_component>();
			ms = timer->get_milliseconds();
		}

		if (ms)
		{
			const auto seconds = (ms / 1000) % 60;
			const auto minutes = (ms / (1000 * 60)) % 60;
			const auto hours = (ms / (1000 * 60 * 60)) % 24;

			return boost::str(boost::format("%02d:%02d:%02d") % hours % minutes % (seconds + 1));
		}

		return "00:00:00";
	}

	size_t transfer_component::get_speed() const
	{
		const auto owner = get_owner();
		const auto timer = owner->get<timer_component>();
		const auto seconds = timer->get_seconds();

		return seconds ? static_cast<size_t>(m_progress / seconds) : static_cast<size_t>(m_progress);
	}

	double transfer_component::get_ratio() const
	{
		const auto owner = get_owner();
		const auto file = owner->get<file_component>();
		//assert(m_size <= file->get_size());

		if (file->has_size() && (m_size < file->get_size()))
			return static_cast<double>(m_size) / static_cast<double>(file->get_size());

		return 1.0;
	}

	size_t transfer_component::get_wait() const
	{
		return (m_wait < s_timeout_size) ? s_timeout_ms[m_wait] : s_timeout_max;
	}

	entity::ptr transfer_list_component::get_entity()
	{
		if (!empty())
		{
			m_next = clamp(static_cast<size_t>(0), m_next, size() - 1);
			const auto entity = at(m_next++);
			return entity;
		}

		return nullptr;
	}
}


text:
namespace ui {
namespace ime {

namespace {

// VerticalCandidateLabel is used for rendering candidate text in
// the vertical candidate window.
class VerticalCandidateLabel : public views::Label {
 public:
  VerticalCandidateLabel() {}

 private:
  ~VerticalCandidateLabel() override {}

  // views::Label:
  // Returns the preferred size, but guarantees that the width has at
  // least kMinCandidateLabelWidth pixels.
  gfx::Size GetPreferredSize() const override {
    gfx::Size size = Label::GetPreferredSize();
    size.SetToMax(gfx::Size(kMinCandidateLabelWidth, 0));
    size.SetToMin(gfx::Size(kMaxCandidateLabelWidth, size.height()));
    return size;
  }

  const char* GetClassName() const override { return "VerticalCandidateLabel"; }

  DISALLOW_COPY_AND_ASSIGN(VerticalCandidateLabel);
};

// Creates the shortcut label, and returns it (never returns NULL).
// The label text is not set in this function.
views::Label* CreateShortcutLabel(
    ui::CandidateWindow::Orientation orientation,
    const ui::NativeTheme& theme) {
  // Create the shortcut label. The label will be owned by
  // |wrapped_shortcut_label|, hence it's deleted when
  // |wrapped_shortcut_label| is deleted.
  views::Label* shortcut_label = new views::Label;

  if (orientation == ui::CandidateWindow::VERTICAL) {
    shortcut_label->SetFontList(
        shortcut_label->font_list().Derive(kFontSizeDelta, gfx::Font::BOLD));
  } else {
    shortcut_label->SetFontList(
        shortcut_label->font_list().DeriveWithSizeDelta(kFontSizeDelta));
  }
  // TODO(satorux): Maybe we need to use language specific fonts for
  // candidate_label, like Chinese font for Chinese input method?
  shortcut_label->SetEnabledColor(theme.GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor));
  shortcut_label->SetDisabledColor(theme.GetSystemColor(
      ui::NativeTheme::kColorId_LabelDisabledColor));

  // Setup paddings.
  const gfx::Insets kVerticalShortcutLabelInsets(1, 6, 1, 6);
  const gfx::Insets kHorizontalShortcutLabelInsets(1, 3, 1, 0);
  const gfx::Insets insets =
      (orientation == ui::CandidateWindow::VERTICAL ?
       kVerticalShortcutLabelInsets :
       kHorizontalShortcutLabelInsets);
  shortcut_label->SetBorder(views::Border::CreateEmptyBorder(
      insets.top(), insets.left(), insets.bottom(), insets.right()));

  // Add decoration based on the orientation.
  if (orientation == ui::CandidateWindow::VERTICAL) {
    // Set the background color.
    SkColor blackish = color_utils::AlphaBlend(
        SK_ColorBLACK,
        theme.GetSystemColor(ui::NativeTheme::kColorId_WindowBackground),
        0x40);
    SkColor transparent_blakish = color_utils::AlphaBlend(
        SK_ColorTRANSPARENT, blackish, 0xE0);
    shortcut_label->set_background(
        views::Background::CreateSolidBackground(transparent_blakish));
  }
  shortcut_label->SetElideBehavior(gfx::NO_ELIDE);

  return shortcut_label;
}

// Creates the candidate label, and returns it (never returns NULL).
// The label text is not set in this function.
views::Label* CreateCandidateLabel(
    ui::CandidateWindow::Orientation orientation) {
  views::Label* candidate_label = NULL;

  // Create the candidate label. The label will be added to |this| as a
  // child view, hence it's deleted when |this| is deleted.
  if (orientation == ui::CandidateWindow::VERTICAL) {
    candidate_label = new VerticalCandidateLabel;
  } else {
    candidate_label = new views::Label;
  }

  // Change the font size.
  candidate_label->SetFontList(
      candidate_label->font_list().DeriveWithSizeDelta(kFontSizeDelta));
  candidate_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  candidate_label->SetElideBehavior(gfx::NO_ELIDE);

  return candidate_label;
}

// Creates the annotation label, and return it (never returns NULL).
// The label text is not set in this function.
views::Label* CreateAnnotationLabel(
    ui::CandidateWindow::Orientation orientation,
    const ui::NativeTheme& theme) {
  // Create the annotation label.
  views::Label* annotation_label = new views::Label;

  // Change the font size and color.
  annotation_label->SetFontList(
      annotation_label->font_list().DeriveWithSizeDelta(kFontSizeDelta));
  annotation_label->SetEnabledColor(theme.GetSystemColor(
      ui::NativeTheme::kColorId_LabelDisabledColor));
  annotation_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  annotation_label->SetElideBehavior(gfx::NO_ELIDE);

  return annotation_label;
}

}  // namespace

CandidateView::CandidateView(
    views::ButtonListener* listener,
    ui::CandidateWindow::Orientation orientation)
    : views::CustomButton(listener),
      orientation_(orientation),
      shortcut_label_(NULL),
      candidate_label_(NULL),
      annotation_label_(NULL),
      infolist_icon_(NULL),
      shortcut_width_(0),
      candidate_width_(0),
      highlighted_(false) {
  SetBorder(views::Border::CreateEmptyBorder(1, 1, 1, 1));

  const ui::NativeTheme& theme = *GetNativeTheme();
  shortcut_label_ = CreateShortcutLabel(orientation, theme);
  candidate_label_ = CreateCandidateLabel(orientation);
  annotation_label_ = CreateAnnotationLabel(orientation, theme);

  AddChildView(shortcut_label_);
  AddChildView(candidate_label_);
  AddChildView(annotation_label_);

  if (orientation == ui::CandidateWindow::VERTICAL) {
    infolist_icon_ = new views::View;
    infolist_icon_->set_background(
        views::Background::CreateSolidBackground(theme.GetSystemColor(
            ui::NativeTheme::kColorId_FocusedBorderColor)));
    AddChildView(infolist_icon_);
  }
}

void CandidateView::GetPreferredWidths(int* shortcut_width,
                                       int* candidate_width) {
  *shortcut_width = shortcut_label_->GetPreferredSize().width();
  *candidate_width = candidate_label_->GetPreferredSize().width();
}

void CandidateView::SetWidths(int shortcut_width, int candidate_width) {
  shortcut_width_ = shortcut_width;
  shortcut_label_->SetVisible(shortcut_width_ != 0);
  candidate_width_ = candidate_width;
}

void CandidateView::SetEntry(const ui::CandidateWindow::Entry& entry) {
  base::string16 label = entry.label;
  if (!label.empty() && orientation_ != ui::CandidateWindow::VERTICAL)
    label += base::ASCIIToUTF16(".");
  shortcut_label_->SetText(label);
  candidate_label_->SetText(entry.value);
  annotation_label_->SetText(entry.annotation);
}

void CandidateView::SetInfolistIcon(bool enable) {
  if (infolist_icon_)
    infolist_icon_->SetVisible(enable);
  SchedulePaint();
}

void CandidateView::SetHighlighted(bool highlighted) {
  if (highlighted_ == highlighted)
    return;

  highlighted_ = highlighted;
  if (highlighted) {
    ui::NativeTheme* theme = GetNativeTheme();
    set_background(
        views::Background::CreateSolidBackground(theme->GetSystemColor(
            ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused)));
    SetBorder(views::Border::CreateSolidBorder(
        1,
        theme->GetSystemColor(ui::NativeTheme::kColorId_FocusedBorderColor)));

    // Cancel currently focused one.
    for (int i = 0; i < parent()->child_count(); ++i) {
      CandidateView* view =
          static_cast<CandidateView*>((parent()->child_at(i)));
      if (view != this)
        view->SetHighlighted(false);
    }
  } else {
    set_background(NULL);
    SetBorder(views::Border::CreateEmptyBorder(1, 1, 1, 1));
  }
  SchedulePaint();
}

void CandidateView::StateChanged() {
  shortcut_label_->SetEnabled(state() != STATE_DISABLED);
  if (state() == STATE_PRESSED)
    SetHighlighted(true);
}

const char* CandidateView::GetClassName() const {
  return "CandidateView";
}

bool CandidateView::OnMouseDragged(const ui::MouseEvent& event) {
  if (!HitTestPoint(event.location())) {
    // Moves the drag target to the sibling view.
    gfx::Point location_in_widget(event.location());
    ConvertPointToWidget(this, &location_in_widget);
    for (int i = 0; i < parent()->child_count(); ++i) {
      CandidateView* sibling =
          static_cast<CandidateView*>(parent()->child_at(i));
      if (sibling == this)
        continue;
      gfx::Point location_in_sibling(location_in_widget);
      ConvertPointFromWidget(sibling, &location_in_sibling);
      if (sibling->HitTestPoint(location_in_sibling)) {
        GetWidget()->GetRootView()->SetMouseHandler(sibling);
        sibling->SetHighlighted(true);
        return sibling->OnMouseDragged(ui::MouseEvent(event, this, sibling));
      }
    }

    return false;
  }

  return views::CustomButton::OnMouseDragged(event);
}

void CandidateView::Layout() {
  const int padding_width =
      orientation_ == ui::CandidateWindow::VERTICAL ? 4 : 6;
  int x = 0;
  shortcut_label_->SetBounds(x, 0, shortcut_width_, height());
  if (shortcut_width_ > 0)
    x += shortcut_width_ + padding_width;
  candidate_label_->SetBounds(x, 0, candidate_width_, height());
  x += candidate_width_ + padding_width;

  int right = bounds().right();
  if (infolist_icon_ && infolist_icon_->visible()) {
    infolist_icon_->SetBounds(
        right - kInfolistIndicatorIconWidth - kInfolistIndicatorIconPadding,
        kInfolistIndicatorIconPadding,
        kInfolistIndicatorIconWidth,
        height() - kInfolistIndicatorIconPadding * 2);
    right -= kInfolistIndicatorIconWidth + kInfolistIndicatorIconPadding * 2;
  }
  annotation_label_->SetBounds(x, 0, right - x, height());
}

gfx::Size CandidateView::GetPreferredSize() const {
  const int padding_width =
      orientation_ == ui::CandidateWindow::VERTICAL ? 4 : 6;
  gfx::Size size;
  if (shortcut_label_->visible()) {
    size = shortcut_label_->GetPreferredSize();
    size.SetToMax(gfx::Size(shortcut_width_, 0));
    size.Enlarge(padding_width, 0);
  }
  gfx::Size candidate_size = candidate_label_->GetPreferredSize();
  candidate_size.SetToMax(gfx::Size(candidate_width_, 0));
  size.Enlarge(candidate_size.width() + padding_width, 0);
  size.SetToMax(candidate_size);
  if (annotation_label_->visible()) {
    gfx::Size annotation_size = annotation_label_->GetPreferredSize();
    size.Enlarge(annotation_size.width() + padding_width, 0);
    size.SetToMax(annotation_size);
  }

  // Reserves the margin for infolist_icon even if it's not visible.
  size.Enlarge(
      kInfolistIndicatorIconWidth + kInfolistIndicatorIconPadding * 2, 0);
  return size;
}

}  // namespace ime
}  // namespace ui

redpajama_set_name: RedPajamaGithub


text:
package org.trustedanalytics.sparktk.frame.internal.ops.groupby.aggregators

import org.trustedanalytics.sparktk.frame.DataTypes.DataType

/**
 *  Trait for group-by aggregators
 *
 *  This trait defines methods needed to implement aggregators, e.g. counts and sums.
 *
 *  This implementation uses Spark's aggregateByKey(). aggregateByKey() aggregates the values of each key using
 *  an initial "zero value", an operation which merges an input value V into an aggregate value U,
 *  and an operation for merging two U's.
 *
 *  @see org.apache.spark.rdd.PairRDDFunctions#aggregateByKey
 */
trait GroupByAggregator extends Serializable {

  /**
   * The type that represents aggregate results. For example, Double for mean, and Long for distinct count values.
   */
  type AggregateType

  /**
   * A type that represents the value to be aggregated. For example, 'ones' for counts, or column values for sums
   */
  type ValueType

  /**
   * The 'empty' or 'zero' or initial value for the aggregator
   */
  def zero: AggregateType

  /**
   * Map function that transforms column values in each row into the input expected by the aggregator
   *
   * For example, for counts, the map function would output 'one' for each map value.
   *
   * @param columnValue Column value
   * @param columnDataType Column data type
   * @return Input value for aggregator
   */
  def mapFunction(columnValue: Any, columnDataType: DataType): ValueType

  /**
   * Adds the output of the map function to the aggregate value
   *
   * This function increments the aggregated value within a single Spark partition.
   *
   * @param aggregateValue Current aggregate value
   * @param mapValue Input value
   * @return Updated aggregate value
   */
  def add(aggregateValue: AggregateType, mapValue: ValueType): AggregateType

  /**
   * Combines two aggregate values
   *
   * This function combines aggregate values across Spark partitions.
   * For example, adding two counts
   *
   * @param aggregateValue1 First aggregate value
   * @param aggregateValue2 Second aggregate value
   * @return Combined aggregate value
   */
  def merge(aggregateValue1: AggregateType, aggregateValue2: AggregateType): AggregateType

  /**
   * Returns the results of the aggregator
   *
   * For some aggregators, this involves casting the result to a Scala Any type.
   * Other aggregators output an intermediate value, so this method computes the
   * final result. For example, the arithmetic mean is represented as a count and sum,
   * so this method computes the mean by dividing the count by the sum.
   *
   * @param result Results of aggregator (might be an intermediate value)
   * @return Final result
   */
  def getResult(result: AggregateType): Any = result

}


text:
HC=ghc
DIST=dist
CDEV=cabal-dev
STYLE=stylish-haskell

.PHONY: clean test hlint

default: build

init:
	cabal update
	$(CDEV) install --only-dependencies

clean:
	rm -rf $(DIST)
	rm -rf ./cabal-dev/lib/snaplet-oauth*
	rm -rf ./cabal-dev/packages/snaplet-oauth*
	rm -f ./cabal-dev/packages-7.4.1.conf/snaplet-oauth-*

hlint:
	hlint src/ tests/ --report=$(DIST)/hlint.html
	find src tests example -name '*.hs' | xargs $(STYLE) -i

conf:
	$(CDEV) configure --enable-tests

build: conf
	$(CDEV) build

rebuild: clean build

install: build
	$(CDEV) install --enable-tests

reinstall: clean install

test: build
	$(CDEV) test

demo:
	cd example && make clean p

doc:
	$(CDEV) haddock

dist: clean build
	$(CDEV) sdist

### build before push in case compilation error

push: clean build
	git push --all

fun:
	cloc src
	cloc tests

local:
	rm -rf ./cabal-dev/lib/hoauth2*
	rm -rf ./cabal-dev/packages/hoauth2*
	rm -f ./cabal-dev/packages-7.4.1.conf/hoauth2-*
	$(CDEV) add-source ../hoauth2
	$(CDEV) install

##
## cd example/ && runghc -package-conf=../cabal-dev/packages-7.4.1.conf/ snap.hs -b 127.0.0.1 -p 9988


text:
***WARNING: This version is invalid. Please install a different version.***

#### Scripts
##### New: ExtractEmailTransformer
- ExtractEmailTransformer (Available from Cortex XSOAR 6.1.0).


text:
package io.ripc.protocol.tcp;

import org.reactivestreams.Publisher;

/**
 * An abstraction for a TCP connection.
 *
 * @param <R> The type of objects read from this connection.
 * @param <W> The type of objects written to this connection.
 */
public interface TcpConnection<R, W> extends Publisher<R> {

    /**
     * Writes the passed stream of {@code data} and returns the result as a {@link Publisher}. All items emitted by
     * this stream are flushed on completion of the stream.
     *
     * @param data Data stream to write.
     *
     * @return Result of write.
     */
    Publisher<Void> write(Publisher<? extends W> data);

}


text:
/*
 *  THIS FILE IS AUTOGENERATED. DO NOT MODIFY IT; ALL CHANGES WILL BE LOST IN
 *  VAIN.
 *
 *  @generated
 */
#include "mcrouter/lib/carbon/example/gen/HelloGoodbyeMessages.h"

#include "mcrouter/lib/carbon/example/gen/gen-cpp2/HelloGoodbye_types.h"

namespace hellogoodbye {
namespace thrift {

void HelloRequest::deserialize(carbon::CarbonProtocolReader& reader) {
  reader.readStructBegin();
  while (true) {
    const auto pr = reader.readFieldHeader();
    const auto fieldType = pr.first;
    const auto fieldId = pr.second;

    if (fieldType == carbon::FieldType::Stop) {
      break;
    }

    switch (fieldId) {
      case 1: {
        reader.readField(key_ref(), fieldType);
        break;
      }
      case 2: {
        reader.readField(shardId_ref(), fieldType);
        break;
      }
      case 3: {
        reader.readField(deadlineMs_ref(), fieldType);
        break;
      }
      case 4: {
        reader.readField(message_ref(), fieldType);
        break;
      }
      case 5: {
        reader.readField(priority_ref(), fieldType);
        break;
      }
      case 6: {
        reader.readField(beforeLatencyUs_ref(), fieldType);
        break;
      }
      case 7: {
        reader.readField(afterLatencyUs_ref(), fieldType);
        break;
      }
      case 8: {
        reader.readField(clientVersion_ref(), fieldType);
        break;
      }
      default: {
        reader.skip(fieldType);
        break;
      }
    }
  }
  reader.readStructEnd();
}

void HelloReply::deserialize(carbon::CarbonProtocolReader& reader) {
  reader.readStructBegin();
  while (true) {
    const auto pr = reader.readFieldHeader();
    const auto fieldType = pr.first;
    const auto fieldId = pr.second;

    if (fieldType == carbon::FieldType::Stop) {
      break;
    }

    switch (fieldId) {
      case 1: {
        reader.readField(result_ref(), fieldType);
        break;
      }
      case 2: {
        reader.readField(message_ref(), fieldType);
        break;
      }
      default: {
        reader.skip(fieldType);
        break;
      }
    }
  }
  reader.readStructEnd();
}

void GoodbyeRequest::deserialize(carbon::CarbonProtocolReader& reader) {
  reader.readStructBegin();
  while (true) {
    const auto pr = reader.readFieldHeader();
    const auto fieldType = pr.first;
    const auto fieldId = pr.second;

    if (fieldType == carbon::FieldType::Stop) {
      break;
    }

    switch (fieldId) {
      case 1: {
        reader.readField(key_ref(), fieldType);
        break;
      }
      case 2: {
        reader.readField(shardId_ref(), fieldType);
        break;
      }
      default: {
        reader.skip(fieldType);
        break;
      }
    }
  }
  reader.readStructEnd();
}

void GoodbyeReply::deserialize(carbon::CarbonProtocolReader& reader) {
  reader.readStructBegin();
  while (true) {
    const auto pr = reader.readFieldHeader();
    const auto fieldType = pr.first;
    const auto fieldId = pr.second;

    if (fieldType == carbon::FieldType::Stop) {
      break;
    }

    switch (fieldId) {
      case 1: {
        reader.readField(result_ref(), fieldType);
        break;
      }
      case 2: {
        reader.readField(message_ref(), fieldType);
        break;
      }
      default: {
        reader.skip(fieldType);
        break;
      }
    }
  }
  reader.readStructEnd();
}
} // namespace thrift
} // namespace hellogoodbye


text:
using System;
using System.Text.RegularExpressions;
using OpenTK;

namespace SimpleScene
{
	// only used to register with the asset manager
	public class SSSkeletalAnimationMD5 : SSSkeletalAnimation
	{
		public SSSkeletalAnimationMD5 (int frameRate,
									   SSSkeletalJoint[] jointInfo,
									   SSSkeletalJointLocation[][] frames,
									   SSAABB[] bounds)
			: base(frameRate, jointInfo, frames, bounds)
		{ }
	}

	public class SSMD5AnimParser : SSMD5Parser
	{
		public static SSSkeletalAnimationMD5 ReadAnimation(SSAssetManager.Context ctx, string filename)
		{
			var parser = new SSMD5AnimParser(ctx, filename);
			var anim = parser.readAnimation ();
			anim.name = filename;
			return anim;
		}

		private enum LocationFlags : byte {
			Tx = 1, Ty = 2, Tz = 4,
			Qx = 8, Qy = 16, Qz = 32
		}

		private SSMD5AnimParser (SSAssetManager.Context ctx, string filename)
			: base(ctx, filename)
		{
		}

		private SSSkeletalAnimationMD5 readAnimation()
		{
			Match[] matches;

			// header
			seekEntry ("MD5Version", "10");
			seekEntry ("commandline", SSMD5Parser._quotedStrRegex);

			matches = seekEntry ("numFrames", SSMD5Parser._uintRegex);
			var numFrames = Convert.ToInt32 (matches [1].Value);

			matches = seekEntry ("numJoints", SSMD5Parser._uintRegex);
			var numJoints = Convert.ToInt32 (matches [1].Value);

			matches = seekEntry ("frameRate", SSMD5Parser._uintRegex);
			var frameRate = Convert.ToInt32 (matches [1].Value);

			matches = seekEntry ("numAnimatedComponents", SSMD5Parser._uintRegex);
			int numAnimatedComponents = Convert.ToInt32 (matches [1].Value);
			var floatComponents = new float[numAnimatedComponents];

			// hierarchy
			seekEntry ("hierarchy", "{");
			var hierarchy = new SSSkeletalJoint[numJoints];
			var flags = new byte[numJoints];
			for (int j = 0; j < numJoints; ++j) {
				hierarchy [j] = readHierarchyEntry (out flags [j]);
			}
			seekEntry ("}");

			// bounds
			seekEntry ("bounds", "{");
			var bounds = new SSAABB[numFrames];
			for (int f = 0; f < numFrames; ++f) {
				bounds [f] = readBounds ();
			}
			seekEntry ("}");

			// base frame
			seekEntry ("baseframe", "{");
			for (int j = 0; j < numJoints; ++j) {
				hierarchy[j].bindPoseLocation = readBaseFrame ();
			}
			seekEntry ("}");

			// frames
			var frames = new SSSkeletalJointLocation[numFrames][];
			for (int f = 0; f < numFrames; ++f) {
				matches = seekEntry ("frame", SSMD5Parser._uintRegex, "{");
				int frameIdx = Convert.ToInt32 (matches [1].Value);
				frames [frameIdx] = readFrameJoints (flags, hierarchy, floatComponents);
				seekEntry ("}");
			}
			return new SSSkeletalAnimationMD5 (frameRate, hierarchy, frames, bounds);
		}

		private SSSkeletalJoint readHierarchyEntry(out byte flags)
		{
			Match[] matches = seekEntry(
				SSMD5Parser._quotedStrRegex, // name
				SSMD5Parser._intRegex, // parent index
				SSMD5Parser._uintRegex, // flags
				SSMD5Parser._uintRegex // start index (currently not used)
			);
			SSSkeletalJoint ret = new SSSkeletalJoint();
			ret.name = matches[0].Value;
			ret.parentIndex = Convert.ToInt32(matches[1].Value);
			flags = Convert.ToByte(matches[2].Value);
			//m_startIndex = Convert.ToInt32(matches[3].Value);
			return ret;
		}

		private SSAABB readBounds()
		{
			Match[] matches = seekEntry (
				SSMD5Parser._parOpen,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
				SSMD5Parser._parClose,
				SSMD5Parser._parOpen,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
				SSMD5Parser._parClose
			);
			SSAABB ret;
			ret.Min.X = (float)Convert.ToDouble (matches [1].Value);
			ret.Min.Y = (float)Convert.ToDouble (matches [2].Value);
			ret.Min.Z = (float)Convert.ToDouble (matches [3].Value);
			ret.Max.X = (float)Convert.ToDouble (matches [6].Value);
			ret.Max.Y = (float)Convert.ToDouble (matches [7].Value);
			ret.Max.Z = (float)Convert.ToDouble (matches [8].Value);
			return ret;
		}

		private SSSkeletalJointLocation readBaseFrame()
		{
			Match[] matches = seekEntry (
				SSMD5Parser._parOpen,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
				SSMD5Parser._parClose,
				SSMD5Parser._parOpen,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
					SSMD5Parser._floatRegex,
					SSMD5Parser._parClose
			);
			SSSkeletalJointLocation loc;
			loc.position.X = (float)Convert.ToDouble (matches [1].Value);
			loc.position.Y = (float)Convert.ToDouble (matches [2].Value);
			loc.position.Z = (float)Convert.ToDouble (matches [3].Value);
			loc.orientation = new Quaternion ();
			loc.orientation.X = (float)Convert.ToDouble (matches [6].Value);
			loc.orientation.Y = (float)Convert.ToDouble (matches [7].Value);
			loc.orientation.Z = (float)Convert.ToDouble (matches [8].Value);
			loc.computeQuatW ();
			return loc;
		}

		private SSSkeletalJointLocation[] readFrameJoints(byte[] jointFlags,
														  SSSkeletalJoint[] jointInfos,
														  float[] floatComponents)
		{
			seekFloats (floatComponents);
			var thisFrameLocations = new SSSkeletalJointLocation[jointInfos.Length];
			int compIdx = 0;
			for (int j = 0; j < jointInfos.Length; ++j) {
				byte flags = jointFlags[j];
				SSSkeletalJoint jointInfo = jointInfos [j];
				SSSkeletalJointLocation loc = jointInfo.bindPoseLocation;
				if ((flags & (byte)LocationFlags.Tx) != 0) {
					loc.position.X = floatComponents [compIdx++];
				}
				if ((flags & (byte)LocationFlags.Ty) != 0) {
					loc.position.Y = floatComponents [compIdx++];
				}
				if ((flags & (byte)LocationFlags.Tz) != 0) {
					loc.position.Z = floatComponents [compIdx++];
				}
				if ((flags & (byte)LocationFlags.Qx) != 0) {
					loc.orientation.X = floatComponents [compIdx++];
				}
				if ((flags & (byte)LocationFlags.Qy) != 0) {
					loc.orientation.Y = floatComponents [compIdx++];
				}
				if ((flags & (byte)LocationFlags.Qz) != 0) {
					loc.orientation.Z = floatComponents [compIdx++];
				}
				loc.computeQuatW ();

				#if false
				if (jointInfo.ParentIndex >= 0) { // has a parent
					SSSkeletalJointLocation parentLoc = thisFrameLocations [jointInfo.ParentIndex];
					loc.Position = parentLoc.Position
						+ Vector3.Transform (loc.Position, parentLoc.Orientation);
					loc.Orientation = Quaternion.Multiply (parentLoc.Orientation,
						loc.Orientation);
					loc.Orientation.Normalize ();
				}
				#endif
				thisFrameLocations[j] = loc;
			}
			return thisFrameLocations;
		}
	}
}


text:
package com.al.json2model.model;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.al.json2model.general.ClassFile;
import com.al.json2model.general.DataType;
import com.al.json2model.model.properties.Language;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;

/**
 * Model class for Visual Basic. This class will be in charge to model the data and
 * produce a file.java class.
 *
 * @author alfredo
 *
 */
public class ModelVBA extends ModelAbstract {

	/**
	 * Default constructor.
	 *
	 * @param name
	 *            Name of the class to be created.
	 * @param json
	 *            JSON file to use as a blueprint.
	 * @param language
	 *            The language used for the class to be created.
	 * @param destFolder
	 *            Destination folder where to put the file(s).
	 * @see ModelAbstract
	 */
	public ModelVBA(String name, String json, Language language, String destFolder) {
		super(name, json, language, destFolder);
	}

	@Override
	protected DataType getPrimitiveDataType(Map.Entry<String, JsonElement> entry) {

		JsonPrimitive primivitive = entry.getValue().getAsJsonPrimitive();

		if (primivitive.isBoolean()) {
			return new DataType(entry.getKey(), "Boolean", false);
		} else if (primivitive.isNumber()) {

			if (isDouble(primivitive.getAsString())) {
				return new DataType(entry.getKey(), "Double", false);
			} else {
				return new DataType(entry.getKey(), "Long", false);
			}

		} else if (primivitive.isString()) {
			return new DataType(entry.getKey(), "String", false);
		} else {
			return new DataType(entry.getKey(), "Object", false);
		}
	}

	@Override
	protected DataType getArrayDataType(Map.Entry<String, JsonElement> entry) {

		String type = "Collection";

		return new DataType(entry.getKey(), type, false);
	}

	@Override
	protected void prepareFiles() {

		final String fileExtension = ".cls";

		// Java has only one class file to be created.
		ClassFile file = new ClassFile(modelName, fileExtension, destFolder, getBody());
		files.add(file);

	}

	@Override
	protected String getBody() {

		// Prepare the body.
		String properties = getBodyProperties();
		String constructor = getBodyConstructor();
		String getterAndSetters = getBodyGettersAndSetters();

		StringBuilder sb = new StringBuilder();

		sb.append("Option Explicit");
		sb.append(language.NEW_LINE);
		sb.append(language.NEW_LINE);
		sb.append(String.format(language.CLASS_DECLARATION_START, modelName));
		sb.append(properties);
		sb.append(constructor);
		sb.append(getLoadMethod());
		sb.append(getterAndSetters);
		sb.append(language.CLASS_DECLARATION_END);

		return sb.toString();
	}

	@Override
	protected String getBodyProperties() {

		StringBuilder sb = new StringBuilder();

		for (String propertyKey : properties.keySet()) {

			DataType t = properties.get(propertyKey);
			String type = t.isObject() ? StringUtils.capitalize(t.getName()) : t.getType();
			sb.append(String.format(language.PROPERTY_DECLARATION, t.getName(), type));
		}

		sb.append(language.NEW_LINE);

		return sb.toString();
	}

	@Override
	protected String getBodyConstructor() {
		return "";
	}

	@Override
	protected String getBodyGettersAndSetters() {
		return "";
	}

	@Override
	protected String getLoadMethod() {

		if (!topObject) {
			return "";
		}

		StringBuilder sb = new StringBuilder();

		sb.append(language.METHOD_LOAD_START);
		sb.append(language.METHOD_LOAD_BODY);
		sb.append(language.METHOD_LOAD_END);

		return sb.toString();

	}
}


text:
package grpc

import (
	"strings"
	"sync"

	"google.golang.org/grpc/balancer"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/internal/channelz"
	"google.golang.org/grpc/internal/grpcsync"
	"google.golang.org/grpc/internal/pretty"
	"google.golang.org/grpc/resolver"
	"google.golang.org/grpc/serviceconfig"
)

// ccResolverWrapper is a wrapper on top of cc for resolvers.
// It implements resolver.ClientConn interface.
type ccResolverWrapper struct {
	cc         *ClientConn
	resolverMu sync.Mutex
	resolver   resolver.Resolver
	done       *grpcsync.Event
	curState   resolver.State

	incomingMu sync.Mutex // Synchronizes all the incoming calls.
}

// newCCResolverWrapper uses the resolver.Builder to build a Resolver and
// returns a ccResolverWrapper object which wraps the newly built resolver.
func newCCResolverWrapper(cc *ClientConn, rb resolver.Builder) (*ccResolverWrapper, error) {
	ccr := &ccResolverWrapper{
		cc:   cc,
		done: grpcsync.NewEvent(),
	}

	var credsClone credentials.TransportCredentials
	if creds := cc.dopts.copts.TransportCredentials; creds != nil {
		credsClone = creds.Clone()
	}
	rbo := resolver.BuildOptions{
		DisableServiceConfig: cc.dopts.disableServiceConfig,
		DialCreds:            credsClone,
		CredsBundle:          cc.dopts.copts.CredsBundle,
		Dialer:               cc.dopts.copts.Dialer,
	}

	var err error
	// We need to hold the lock here while we assign to the ccr.resolver field
	// to guard against a data race caused by the following code path,
	// rb.Build-->ccr.ReportError-->ccr.poll-->ccr.resolveNow, would end up
	// accessing ccr.resolver which is being assigned here.
	ccr.resolverMu.Lock()
	defer ccr.resolverMu.Unlock()
	ccr.resolver, err = rb.Build(cc.parsedTarget, ccr, rbo)
	if err != nil {
		return nil, err
	}
	return ccr, nil
}

func (ccr *ccResolverWrapper) resolveNow(o resolver.ResolveNowOptions) {
	ccr.resolverMu.Lock()
	if !ccr.done.HasFired() {
		ccr.resolver.ResolveNow(o)
	}
	ccr.resolverMu.Unlock()
}

func (ccr *ccResolverWrapper) close() {
	ccr.resolverMu.Lock()
	ccr.resolver.Close()
	ccr.done.Fire()
	ccr.resolverMu.Unlock()
}

func (ccr *ccResolverWrapper) UpdateState(s resolver.State) error {
	ccr.incomingMu.Lock()
	defer ccr.incomingMu.Unlock()
	if ccr.done.HasFired() {
		return nil
	}
	ccr.addChannelzTraceEvent(s)
	ccr.curState = s
	if err := ccr.cc.updateResolverState(ccr.curState, nil); err == balancer.ErrBadResolverState {
		return balancer.ErrBadResolverState
	}
	return nil
}

func (ccr *ccResolverWrapper) ReportError(err error) {
	ccr.incomingMu.Lock()
	defer ccr.incomingMu.Unlock()
	if ccr.done.HasFired() {
		return
	}
	channelz.Warningf(logger, ccr.cc.channelzID, "ccResolverWrapper: reporting error to cc: %v", err)
	ccr.cc.updateResolverState(resolver.State{}, err)
}

// NewAddress is called by the resolver implementation to send addresses to gRPC.
func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) {
	ccr.incomingMu.Lock()
	defer ccr.incomingMu.Unlock()
	if ccr.done.HasFired() {
		return
	}
	ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig})
	ccr.curState.Addresses = addrs
	ccr.cc.updateResolverState(ccr.curState, nil)
}

// NewServiceConfig is called by the resolver implementation to send service
// configs to gRPC.
func (ccr *ccResolverWrapper) NewServiceConfig(sc string) {
	ccr.incomingMu.Lock()
	defer ccr.incomingMu.Unlock()
	if ccr.done.HasFired() {
		return
	}
	channelz.Infof(logger, ccr.cc.channelzID, "ccResolverWrapper: got new service config: %s", sc)
	if ccr.cc.dopts.disableServiceConfig {
		channelz.Info(logger, ccr.cc.channelzID, "Service config lookups disabled; ignoring config")
		return
	}
	scpr := parseServiceConfig(sc)
	if scpr.Err != nil {
		channelz.Warningf(logger, ccr.cc.channelzID, "ccResolverWrapper: error parsing service config: %v", scpr.Err)
		return
	}
	ccr.addChannelzTraceEvent(resolver.State{Addresses: ccr.curState.Addresses, ServiceConfig: scpr})
	ccr.curState.ServiceConfig = scpr
	ccr.cc.updateResolverState(ccr.curState, nil)
}

func (ccr *ccResolverWrapper) ParseServiceConfig(scJSON string) *serviceconfig.ParseResult {
	return parseServiceConfig(scJSON)
}

func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) {
	var updates []string
	var oldSC, newSC *ServiceConfig
	var oldOK, newOK bool
	if ccr.curState.ServiceConfig != nil {
		oldSC, oldOK = ccr.curState.ServiceConfig.Config.(*ServiceConfig)
	}
	if s.ServiceConfig != nil {
		newSC, newOK = s.ServiceConfig.Config.(*ServiceConfig)
	}
	if oldOK != newOK || (oldOK && newOK && oldSC.rawJSONString != newSC.rawJSONString) {
		updates = append(updates, "service config updated")
	}
	if len(ccr.curState.Addresses) > 0 && len(s.Addresses) == 0 {
		updates = append(updates, "resolver returned an empty address list")
	} else if len(ccr.curState.Addresses) == 0 && len(s.Addresses) > 0 {
		updates = append(updates, "resolver returned new addresses")
	}
	channelz.Infof(logger, ccr.cc.channelzID, "Resolver state updated: %s (%v)", pretty.ToJSON(s), strings.Join(updates, "; "))
}


text:
package com.alibaba.rocketmq.client.producer.selector;

import com.alibaba.rocketmq.client.log.ClientLogger;
import com.alibaba.rocketmq.common.message.MessageQueue;
import com.alibaba.rocketmq.remoting.common.RemotingUtil;
import org.slf4j.Logger;

import java.util.List;
import java.util.Random;

public class Util {

    private static final Logger LOGGER = ClientLogger.getLog();

    private static final String DOCKER_DC_INDEX_ENV_KEY = "ROCKETMQ_DC_INDEX";

    private static final String DOCKER_DC_INDEX_KEY = "DCIndex";

    private static final Random random = new Random(System.currentTimeMillis());

    public static String LOCAL_DATA_CENTER_ID = RemotingUtil.getLocalAddress(false).split("\\.")[1];

    static {
        String dcIndex = System.getenv(DOCKER_DC_INDEX_ENV_KEY);
        if (null == dcIndex) {
            dcIndex = System.getProperty(DOCKER_DC_INDEX_KEY);
        }

        if (null != dcIndex && dcIndex.trim().length() > 0) {
            LOCAL_DATA_CENTER_ID = dcIndex;
        }

        // 10.12 now also in region of US-East
        if ("12".equals(LOCAL_DATA_CENTER_ID)) {
            LOCAL_DATA_CENTER_ID = "1";
        }

        LOGGER.info("DCIndex: {}", LOCAL_DATA_CENTER_ID);
    }

    /**
     * Randomly choose an element from the given list.
     * @param list List of elements, not empty.
     * @return randomly chosen element in the list.
     */
    public static<T> T random(List<T> list) {
        return list.get(random.nextInt(Integer.MAX_VALUE) % list.size());
    }

    public static int getRegionIndex(MessageQueue messageQueue) {
        String brokerName = messageQueue.getBrokerName();
        String[] segments = brokerName.split("_");
        if (segments.length < 3) {
            return -1;
        }

        try {
            return Integer.parseInt(segments[1]);
        } catch (Exception e) {
            return -1;
        }
    }
}


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.modeshape.jcr;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import java.util.UUID;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;

import org.junit.Test;
import org.modeshape.common.FixFor;
import org.modeshape.common.util.FileUtil;

public class FederationConfigurationTest extends SingleUseAbstractTest {

    @FixFor( "MODE-1772" )
    @Test
    public void shouldStartRepositoryWithFileSystemConnectorAccessingAncestorOfCacheStoreDirectory() throws Exception {
        // Clean up and create some initial files ...
        FileUtil.delete("target/federation_persistent_repository");

        startRepositoryWithConfiguration(resource("config/repo-config-filesystem-federation-with-persistence.json"));
        Session session = session();
        Node federation = session.getNode("/federation");

        // Get the children under federation ...
        NodeIterator iter = federation.getNodes();
        while (iter.hasNext()) {
            Node child = iter.nextNode();
            assertThat(child, is(notNullValue()));
        }

        // Add a node directly under 'federation' (which is a federated node)...
        for (int i = 0; i != 3; ++i) {
            Node newNode = federation.addNode("Node");
            assertThat(newNode, is(notNullValue()));
            session.save();
        }

        // Add a node directly under 'generated-sources' (which is a federated node)...
        Node sources = federation.getNode("generated-sources");
        for (int i = 0; i != 3; ++i) {
            Node newNode = sources.addNode("GeneratedFolder_" + UUID.randomUUID().toString(), "nt:folder");
            assertThat(newNode, is(notNullValue()));
            session.save();
        }

        // Add a node directly under 'generated-sources/annotations' (which is a federated node)...
        Node annotations = federation.getNode("generated-sources/annotations");
        for (int i = 0; i != 3; ++i) {
            Node newNode = annotations.addNode("GeneratedFolder_" + UUID.randomUUID().toString(), "nt:folder");
            assertThat(newNode, is(notNullValue()));
            session.save();
        }
    }

    @Test
    public void shouldIgnorePreconfiguredProjectionIfProjectedPathPointsTowardsInternalNode() throws Exception {
        startRepositoryWithConfiguration(resource("config/repo-config-filesystem-federation-invalid-alias.json"));
        //check that there only the internal node + 1 child and that the projection has not been created
        Session session = session();
        Node federation = session.getNode("/federation");
        assertEquals(1, federation.getNodes().getSize());
        assertNotNull(session.getNode("/federation/fs"));
    }

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


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe CuratorActivityLog do

  # TODO.  Sorry, there's just way too much to do here to bother right now.  It was completely wrong, before.

  # TODO - make sure all of these methods are actually USED.  I'm not so sure.

  it 'should know the #taxon_concept_name for a data object'
  it 'should know the #taxon_concept_name for a comment'
  it 'should know the #taxon_concept_name for user submitted text'
  it 'should know the #taxon_concept_name for a synonym'
  it 'should raise an exception for #taxon_concept_name for other types of objects'

  it 'should find images from a taxon concept'
  it 'should find dohes from a TC'
  it 'should find cdohes from a TC'
  it 'should find taxon_concept_names from a TC'
  it 'should find synonyms from a TC'

  it 'should know the id for a data object'
  it 'should know the id for a comment'
  it 'should know the id for user submitted text'
  it 'should know the id for a synonym'
  it 'should raise an exception for #taxon_concept_name for other types of objects'

  it 'should return the label of a data type for #data_object_type'

  it 'should use the label from the first toc_item fir #toc_label'

  it 'should find the comment object'

  it 'should grab a #comment_parent'

  it 'should find the #synonym'

  it 'should find the #users_data_object'

  it 'should find the #udo_parent_text'

  it 'should find the #udo_taxon_concept'

end


text:
package org.zstack.test.network.flat;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.host.HostInventory;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.network.service.flat.FlatDhcpBackend.ApplyDhcpCmd;
import org.zstack.network.service.flat.FlatDhcpBackend.DhcpInfo;
import org.zstack.network.service.flat.FlatNetworkServiceSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig;
import org.zstack.storage.primary.local.LocalStorageSimulatorConfig.Capacity;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.data.SizeUnit;

/**
 * 1. delete a flat network
 * <p>
 * confirm the namespace is deleted
 */
public class TestFlatNetwork4 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    LocalStorageSimulatorConfig config;
    FlatNetworkServiceSimulatorConfig fconfig;
    long totalSize = SizeUnit.GIGABYTE.toByte(100);

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/flatnetwork/TestFlatNetwork4.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("localStorageSimulator.xml");
        deployer.addSpringConfig("localStorage.xml");
        deployer.addSpringConfig("flatNetworkServiceSimulator.xml");
        deployer.addSpringConfig("flatNetworkProvider.xml");
        deployer.load();

        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        config = loader.getComponent(LocalStorageSimulatorConfig.class);
        fconfig = loader.getComponent(FlatNetworkServiceSimulatorConfig.class);

        Capacity c = new Capacity();
        c.total = totalSize;
        c.avail = totalSize;

        config.capacityMap.put("host1", c);
        config.capacityMap.put("host2", c);

        deployer.build();
        api = deployer.getApi();
        session = api.loginAsAdmin();
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        api.setTimeout(100000);
        HostInventory host = deployer.hosts.get("host1");
        fconfig.applyDhcpCmdList.clear();
        api.reconnectHost(host.getUuid());

        VmInstanceInventory vm1 = deployer.vms.get("TestVm1");
        VmNicInventory nic1 = vm1.getVmNics().get(0);

        VmInstanceInventory vm2 = deployer.vms.get("TestVm2");
        VmNicInventory nic2 = vm2.getVmNics().get(0);

        Assert.assertEquals(2, fconfig.applyDhcpCmdList.size());

        ApplyDhcpCmd cmd = fconfig.applyDhcpCmdList.stream().filter(c -> c.l3NetworkUuid.equals(nic1.getL3NetworkUuid())).findAny().get();
        Assert.assertNotNull(cmd);
        Assert.assertEquals(1, cmd.dhcp.size());
        DhcpInfo dhcp = cmd.dhcp.get(0);
        Assert.assertNotNull(dhcp);
        Assert.assertEquals(nic1.getIp(), dhcp.ip);

        cmd = fconfig.applyDhcpCmdList.stream().filter(c -> c.l3NetworkUuid.equals(nic2.getL3NetworkUuid())).findAny().get();
        Assert.assertNotNull(cmd);
        Assert.assertEquals(1, cmd.dhcp.size());
        dhcp = cmd.dhcp.get(0);
        Assert.assertNotNull(dhcp);
        Assert.assertEquals(nic2.getIp(), dhcp.ip);
    }
}


text:
  static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
  static const int ddLogLevel = LOG_LEVEL_INFO;
#endif

@implementation RootViewController

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (iPhoneXMPPAppDelegate *)appDelegate
{
	return (iPhoneXMPPAppDelegate *)[[UIApplication sharedApplication] delegate];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark View lifecycle
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];

	UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 400, 44)];
	titleLabel.backgroundColor = [UIColor clearColor];
	titleLabel.textColor = [UIColor darkTextColor];
	titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
	titleLabel.numberOfLines = 1;
	titleLabel.adjustsFontSizeToFitWidth = YES;
	titleLabel.textAlignment = NSTextAlignmentCenter;

	if ([[self appDelegate] connect])
	{
		titleLabel.text = [[[[self appDelegate] xmppStream] myJID] bare];
	} else
	{
		titleLabel.text = @"No JID";
	}

	[titleLabel sizeToFit];

	self.navigationItem.titleView = titleLabel;
}

- (void)viewWillDisappear:(BOOL)animated
{
	[[self appDelegate] disconnect];
	[[[self appDelegate] xmppvCardTempModule] removeDelegate:self];

	[super viewWillDisappear:animated];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSFetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSFetchedResultsController *)fetchedResultsController
{
	if (fetchedResultsController == nil)
	{
		NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];

		NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
		                                          inManagedObjectContext:moc];

		NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
		NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];

		NSArray *sortDescriptors = @[sd1, sd2];

		NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
		[fetchRequest setEntity:entity];
		[fetchRequest setSortDescriptors:sortDescriptors];
		[fetchRequest setFetchBatchSize:10];

		fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
		                                                               managedObjectContext:moc
		                                                                 sectionNameKeyPath:@"sectionNum"
		                                                                          cacheName:nil];
		[fetchedResultsController setDelegate:self];

		NSError *error = nil;
		if (![fetchedResultsController performFetch:&error])
		{
			DDLogError(@"Error performing fetch: %@", error);
		}

	}

	return fetchedResultsController;
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
	[[self tableView] reloadData];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableViewCell helpers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)configurePhotoForCell:(UITableViewCell *)cell user:(XMPPUserCoreDataStorageObject *)user
{
	// Our xmppRosterStorage will cache photos as they arrive from the xmppvCardAvatarModule.
	// We only need to ask the avatar module for a photo, if the roster doesn't have it.

	if (user.photo != nil)
	{
		cell.imageView.image = user.photo;
	}
	else
	{
		NSData *photoData = [[[self appDelegate] xmppvCardAvatarModule] photoDataForJID:user.jid];

		if (photoData != nil)
			cell.imageView.image = [UIImage imageWithData:photoData];
		else
			cell.imageView.image = [UIImage imageNamed:@"defaultPerson"];
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableView
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [[[self fetchedResultsController] sections] count];
}

- (NSString *)tableView:(UITableView *)sender titleForHeaderInSection:(NSInteger)sectionIndex
{
	NSArray *sections = [[self fetchedResultsController] sections];

	if (sectionIndex < [sections count])
	{
		id <NSFetchedResultsSectionInfo> sectionInfo = sections[sectionIndex];

		int section = [sectionInfo.name intValue];
		switch (section)
		{
			case 0  : return @"Available";
			case 1  : return @"Away";
			default : return @"Offline";
		}
	}

	return @"";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
	NSArray *sections = [[self fetchedResultsController] sections];

	if (sectionIndex < [sections count])
	{
		id <NSFetchedResultsSectionInfo> sectionInfo = sections[sectionIndex];
		return sectionInfo.numberOfObjects;
	}

	return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
		                               reuseIdentifier:CellIdentifier];
	}

	XMPPUserCoreDataStorageObject *user = [[self fetchedResultsController] objectAtIndexPath:indexPath];

	cell.textLabel.text = user.displayName;
	[self configurePhotoForCell:cell user:user];

	return cell;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (IBAction)settings:(id)sender
{
	[self.navigationController presentViewController:[[self appDelegate] settingsViewController] animated:YES completion:NULL];
}

@end


text:
package com.intellij.util.xml.impl;

import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.SmartList;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomNameStrategy;
import com.intellij.util.xml.JavaMethod;
import com.intellij.util.xml.XmlName;
import com.intellij.util.xml.reflect.DomFixedChildDescription;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class FixedChildDescriptionImpl extends DomChildDescriptionImpl implements DomFixedChildDescription {
  private final Collection<JavaMethod>[] myGetterMethods;
  private final int myCount;

  public FixedChildDescriptionImpl(final XmlName tagName, final Type type, final int count, final Collection<JavaMethod>[] getterMethods) {
    super(tagName, type);
    assert getterMethods.length == count || getterMethods == ArrayUtilRt.EMPTY_COLLECTION_ARRAY;
    myCount = count;
    myGetterMethods = getterMethods;
  }

  @Override
  public JavaMethod getGetterMethod(int index) {
    if (myGetterMethods.length == 0) return null;

    final Collection<JavaMethod> methods = myGetterMethods[index];
    return methods == null || methods.isEmpty() ? null : methods.iterator().next();
  }

  @Override
  @Nullable
  public <T extends Annotation> T getAnnotation(int index, Class<? extends T> annotationClass) {
    final JavaMethod method = getGetterMethod(index);
    if (method != null) {
      final T annotation = method.getAnnotation(annotationClass);
      if (annotation != null) return annotation;
    }

    final Type elemType = getType();
    if (elemType instanceof AnnotatedElement) {
      T annotation = ((AnnotatedElement)elemType).getAnnotation(annotationClass);
      if (annotation != null) return annotation;
    }

    return super.getAnnotation(annotationClass);
  }

  @Override
  public int getCount() {
    return myCount;
  }

  @Override
  @NotNull
  public List<? extends DomElement> getValues(@NotNull final DomElement element) {
    final List<DomElement> result = new SmartList<>();
    final DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(element);
    if (handler != null) {
      for (int i = 0; i < myCount; i++) {
        result.add(handler.getFixedChild(Pair.create(this, i)).getProxy());
      }
    }
    else {
      for (Collection<JavaMethod> methods : myGetterMethods) {
        if (methods != null && !methods.isEmpty()) {
          result.add((DomElement)methods.iterator().next().invoke(element, ArrayUtilRt.EMPTY_OBJECT_ARRAY));
        }
      }
    }
    return result;
  }

  @Override
  @NotNull
  @NlsSafe
  public String getCommonPresentableName(@NotNull DomNameStrategy strategy) {
    return StringUtil.capitalizeWords(strategy.splitIntoWords(getXmlElementName()), true);
  }

  @Override
  @Nullable
  public final <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    return getAnnotation(0, annotationClass);
  }

  public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;

    final FixedChildDescriptionImpl that = (FixedChildDescriptionImpl)o;

    if (myCount != that.myCount) return false;
    if (!Arrays.equals(myGetterMethods, that.myGetterMethods)) return false;

    return true;
  }

  public String toString() {
    return getXmlElementName() + " " + getGetterMethod(0) + " " + getType();
  }

  public int hashCode() {
    int result = super.hashCode();
    result = 29 * result + myCount;
    return result;
  }
}


text:
  Noailles est
      une ville située dans le département de l'Oise en Picardie. On dénombrait 2 674 habitants en 2008.

À Noailles, la valeur moyenne à l'achat d'un appartement se situe à 1 979 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 146 € du m². À la location la valorisation moyenne se situe à 14,51 € du m² par mois.

La ville propose de multiples  équipements, elle propose entre autres un terrain de tennis, un centre d'équitation et deux terrains de sport.

Le parc d'habitations, à Noailles, était réparti en 2011 en 345 appartements et 907 maisons soit
 un marché relativement équilibré.

À Noailles le salaire moyen mensuel par personne se situe à environ 1 994 €  net. Ceci est inférieur à la moyenne nationale.

À coté de Noailles sont positionnées géographiquement les communes de
Mouchy-le-Châtel à 3 km, 71 habitants,
Hodenc-l'Évêque située à 3 km, 228 habitants,
Heilles située à 4 km, 587 habitants,
Ponchon localisée à 2 km, 1 087 habitants,
Le Fayel à 2 km, 227 habitants,
Villers-Saint-Sépulcre à 4 km, 865 habitants,
 entre autres. De plus, Noailles est située à seulement quatorze km de Beauvais.

La localité est équipée en ce qui concerne des études de un collège.
Pour ceux d'entre nous ayant moins de 6 ans, la localité est pourvue de une école primaire.
Noailles dispose des installations éducatives permettant une vie locale facilitée.
Si vous avez un projet de faire une acquisition à Noailles, il est intéressant d' évaluer la notoriété des écoles de la communes


text:
package com.amazonaws.services.lambda.invoke;

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

import org.apache.commons.logging.LogFactory;

import com.amazonaws.services.lambda.model.InvocationType;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.LogType;

/**
 * An annotation that marks methods of an interface that are meant to be proxied to remote code
 * running on AWS Lambda. Methods may accept zero or one arguments, and may return zero or one
 * values. Inputs and outputs will be converted to/from JSON using the Jackson {@code ObjectMapper}.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LambdaFunction {

    /**
     * The name of the Lambda function to invoke for this annotated method. If not explicitly set,
     * the name of the interface method is used.
     *

     *
     * public interface LambdaFunctions {
     *
     * @LambdaFunction(functionName="ActualFunctionName") void notTheRealFunctionName(); }
     * @see InvokeRequest#setFunctionName(String)
     */
    String functionName() default "";

    /**
     * The type of invocation to use. If unspecified, defaults to {@code RequestResponse}. If a
     * {@code logType} of anything other than {@code None} is specified, the invocation type may
     * only be set to {@code RequestResponse}.
     *

     *
     * public interface LambdaFunctions {
     *
     * @LambdaFunction(functionName="DoIt") void doIt();
     * @LambdaFunction(functionName="DoIt", invocationType=InvocationType.Event) void
     *                                      doItAsynchronously();
     * @LambdaFunction(functionName="DoIt", invocationType=InvocationType.DryRun) void dryRunIt(); }
     *
     * @see InvokeRequest#setInvocationType(InvocationType)
     */
    InvocationType invocationType() default InvocationType.RequestResponse;

    /**
     * The type of log to request from the service. If unspecified, no logs will be requested. If
     * specified, the invocation type may only be set to {@code RequestResponse}.
     *

     * When specified, the log information returned by the Lambda function will be emitted to the
     * JCL log for the interface class at the {@code INFO} level.
     *
     * @see InvokeRequest#setLogType(LogType)
     * @see LogFactory#getLog(Class)
     */
    LogType logType() default LogType.None;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="course.examples.helloandroidwithmenu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".HelloAndroidWithMenuActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
classdef NatParamExtractor < FeatureExtractor
    %NATPARAMEXTRACTOR Extract natural parameters.
    %   - Extract log precision for Gaussian instead of just precisions.

    properties
    end

    methods
        % dist is a Distribution
        function F = extractFeatures(this, dist)
            % dist can be a DistArray
            dt = dist.getDistType();
            if strcmp(dt, 'DistNormal') && unique([dist.d])==1
                M = [dist.mean];
                V = [dist.variance];
                nat1 = M./V;
                logPre = -log(V);
                F = [nat1; logPre];
            elseif isa(dist, 'DistArray') && strcmp(dt, 'DistBeta')
                inDa = dist.distArray;
                a = [inDa.alpha]-1;
                b = [inDa.beta]-1;
                F = [a; b];
            elseif isa(dist, 'DistBeta')
                a = [dist.alpha]-1;
                b = [dist.beta]-1;
                F = [a; b];
            else
                error('Unknown supported distribution type %s: ', class(dist(1)));
            end

        end

        % Short summary of this FeatureMap. Useful if in the form
        % mapName(param1, param2).
        function s = shortSummary(this)
            s = sprintf('%s', mfilename);
        end
    end

end


text:
namespace AtleX.CommandLineArguments.Parsers.TypeParsers
{
  /// <summary>
  /// Represents a <see cref="TypeParser{T}"/> for <see cref="short"/>
  /// </summary>
  internal sealed class ShortTypeParser
  : TypeParser<short>
  {
    /// <inheritdoc />
    public override bool TryParse(string value, out short parseResult)
    {
      bool result;

      if (!string.IsNullOrEmpty(value))
      {
        result = short.TryParse(value, out parseResult);
      }
      else
      {
        parseResult = default;
        result = false;
      }

      return result;
    }
  }
}


text:
"""Control Keyboard

This program uses :py:mod:`PyAutoGUI` to manipulate keyboard input.

"""

import pyautogui, time

def commentAfterDelay() -> None:
    """Comment after delay

    Automatically types then comments out a line in IDLE after waiting two seconds.

    Returns:
        None. Executes keyboard commands.

    """
    pyautogui.click(100, 100)  # focus IDLE file editor
    pyautogui.typewrite('In IDLE, Alt-3 comments out a line.')
    time.sleep(2)
    pyautogui.hotkey('alt', '3')

def main():
    # Sending a String from the Keyboard
    pyautogui.click(100, 100)  # put file editor in focus
    pyautogui.typewrite('Hello world!')
    pyautogui.typewrite('!dlrow olleH', 0.25)

    # Key Names
    pyautogui.typewrite(['enter', 'a', 'b', 'left', 'left', 'X', 'Y'])

    # Press and Release Keyboard Keys
    pyautogui.press('end')
    pyautogui.press('enter')
    pyautogui.keyDown('shift')
    pyautogui.press('4')
    pyautogui.keyUp('shift')

    # Hotkey Combinations
    pyautogui.keyDown('ctrl')
    pyautogui.keyDown('c')
    pyautogui.keyUp('c')
    pyautogui.keyUp('ctrl')

    pyautogui.hotkey('ctrl', 'c')

    commentAfterDelay()

if __name__ == '__main__':
    main()


text:
package net.safedata.spring.training.complete.project;

import net.safedata.spring.training.complete.project.dto.ProductDTO;
import net.safedata.spring.training.complete.project.repository.ProductRepository;
import net.safedata.spring.training.complete.project.service.ProductService;
import net.safedata.spring.training.jpa.model.Product;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;

@ExtendWith(SpringExtension.class)
class ProductServiceTest {

    @Mock
    private ProductRepository productRepository; // the collaborator (productRepository) is mocked

    @Spy
    @SuppressWarnings("unused")
    private ExecutorService executorService;

    // the tested service; also called 'system under test' // SUT
    @InjectMocks
    private ProductService productService;

    @Test
    @DisplayName("Given there are available products, when retrieving the products then products are retrieved correctly")
    void givenThereAreAvailableProducts_whenRetrievingProducts_thenProductsAreRetrievedCorrectly() {
        // arrange, including mocking behavior setup    --> given
        final List<Product> products = Arrays.asList(
                new Product("Samsung S8"),
                new Product("Google Pixel")
        );
        when(productRepository.findAll()).thenReturn(products); // simple mocking example

        // act --> calling the tested service method    --> when
        final List<ProductDTO> resulted = productService.getAll();

        // assert --> verifying the response of the tested method is correct (by the requirements)  --> then
        assertNotNull(resulted);
        assertThat(resulted.size(), is(products.size()));
        assertThat(resulted.iterator().hasNext(), is(true));
    }

    @Test
    @DisplayName("Given there are no available products, when retrieving the products then no products are retrieved")
    void givenThereAreNoAvailableProducts_whenRetrievingProducts_thenNoProductsAreReturned() {
        when(productRepository.findAll()).thenReturn(new ArrayList<>());

        final List<ProductDTO> resulted = productService.getAll();

        assertNotNull(resulted);
        assertThat(resulted.iterator().hasNext(), is(false));
    }

    @Test
    @DisplayName("Given there are available products, when retrieving a product by ID then the product is retrieved")
    void givenThereAreAvailableProducts_whenRetrievingAProductById_thenTheProductIsCorrectlyRetrieved() {
        final int productId = 20;

        final Product product = mock(Product.class);
        final String mockedName = "mocked name";
        when(product.getName()).thenReturn(mockedName);
        when(product.getId()).thenReturn(productId);

        when(productRepository.findById(productId)).thenReturn(Optional.of(product));

        final ProductDTO resulted = productService.get(productId);

        assertNotNull(resulted);
        assertThat(resulted.getProductName(), is(mockedName));
        assertThat(resulted.getId(), not(0));
        assertThat(resulted.getId(), is(productId));
    }

    @Test
    @DisplayName("Given there are no available products, when retrieving a product by ID then an IAE is thrown")
    void givenThereAreNoAvailableProducts_whenRetrievingAProductById_thenAnIllegalArgumentExceptionIsThrown() {
        assertThrows(IllegalArgumentException.class, () -> productService.get(13));
    }

    @Test
    @DisplayName("Given a product is saved, when saving the product then save is called one time and the response is not " +
            "null or empty")
    void givenAProductIsSaved_whenSavingTheProduct_thenSaveIsCalledOneTimesAndTheResponseShouldNotBeEmptyOrNull () {
        final ProductDTO product = mock(ProductDTO.class);

        final String response = productService.save(product);

        // it verifies that the .save method (from the productRepository collaborator) was called exactly 1 times
        verify(productRepository, times(1)).save(any(Product.class));

        assertNotNull(response);
        assertThat("The displayed error message", response.length(), not(0));
    }
}


text:
describe MiqServer do
  before do
    MiqRegion.seed
    @server = EvmSpecHelper.local_miq_server(:zone => Zone.seed)
  end

  let!(:database) do
    FactoryBot.create(:miq_region, :region => ApplicationRecord.my_region_number)
    db = MiqDatabase.seed
    db.update_repo_name = "repo-1 repo-2"
    db
  end

  let(:reg_system)  { LinuxAdmin::RegistrationSystem }
  let(:yum)         { LinuxAdmin::Yum }

  context "Queue multiple servers" do
    before do
      FactoryBot.create(:miq_server, :zone => @server.zone)
    end

    it ".queue_update_registration_status" do
      described_class.queue_update_registration_status(described_class.all.collect(&:id))

      expect(MiqQueue.where(:method_name => "update_registration_status").count).to eq(2)
    end

    it ".queue_check_updates" do
      described_class.queue_check_updates(described_class.all)

      expect(MiqQueue.where(:method_name => "check_updates").count).to eq(2)
    end

    it ".queue_apply_updates" do
      described_class.queue_apply_updates(described_class.all)

      expect(MiqQueue.where(:method_name => "apply_updates").count).to eq(2)
    end
  end

  context "Queue a single server" do
    it "#queue_update_registration_status" do
      @server.queue_update_registration_status

      expect(MiqQueue.where(:method_name => "update_registration_status").count).to eq(1)
    end

    it "#queue_check_updates" do
      @server.queue_check_updates

      expect(MiqQueue.where(:method_name => "check_updates").count).to eq(1)
    end

    it "#queue_apply_updates" do
      @server.queue_apply_updates

      expect(MiqQueue.where(:method_name => "apply_updates").count).to eq(1)
    end
  end

  it "#update_registration_status" do
    expect(@server).to receive(:attempt_registration).once
    expect(@server).to receive(:check_updates).once

    @server.update_registration_status
  end

  context "#attempt_registration" do
    it "does not continue if registration fails" do
      expect(@server).to receive(:register).and_return(false)
      expect(@server).not_to receive(:attach_products)

      @server.attempt_registration
    end

    it "should not try to enable the repo if already enabled" do
      expect(@server).to receive(:register).and_return(true)
      expect(@server).to receive(:attach_products)
      expect(@server).to receive(:repos_enabled?).and_return(true)
      expect(@server).not_to receive(:enable_repos)

      @server.attempt_registration
    end

    it "should enable the repo if not enabled" do
      expect(@server).to receive(:register).and_return(true)
      expect(@server).to receive(:attach_products)
      expect(reg_system).to receive(:enabled_repos).and_return([], [], database.update_repo_name.split)
      expect(@server).to receive(:enable_repos).twice

      @server.attempt_registration
    end

    it "should raise a notification if registration fails" do
      NotificationType.seed
      result = AwesomeSpawn::CommandResult.new("stuff", "things", "more things", 1)
      err = LinuxAdmin::SubscriptionManagerError.new("things", result)
      expect(@server).to receive(:register).and_raise(err)
      expect { @server.attempt_registration }.to raise_error(LinuxAdmin::SubscriptionManagerError)

      note = Notification.find_by(:notification_type_id => NotificationType.find_by(:name => "server_registration_error").id)
      expect(note.options.keys).to include(:server_name)
    end
  end

  context "#register" do
    let(:default_params) { {:server_url => "subscription.rhn.redhat.com"} }
    it "already registered" do
      allow(reg_system).to receive(:registered?).and_return(true)

      @server.register

      expect(@server.reload).to be_rh_registered
      expect(@server.upgrade_message).to eq("registration successful")
    end

    it "unregistered should use subscription-manager" do
      allow(reg_system).to receive(:registered?).once.and_return(false, true)
      expect(LinuxAdmin::SubscriptionManager).to receive(:register).once.with(default_params).and_return(true)
      expect(reg_system).to receive(:registration_type).once

      @server.register

      expect(@server.reload).to be_rh_registered
      expect(@server.upgrade_message).to eq("registration successful")
    end

    it "unregistered should use satellite6" do
      expected_params = {:server_url => "https://my-sat6-server.mydomain", :environment => "Library"}

      database.update_attribute(:registration_type, "rhn_satellite6")
      database.update_attribute(:registration_server, expected_params[:server_url])

      allow(reg_system).to receive(:registered?).once.and_return(false, true)
      expect(LinuxAdmin::SubscriptionManager).to receive(:register).once.with(expected_params).and_return(true)
      expect(reg_system).to receive(:registration_type).once

      @server.register

      expect(@server.reload).to be_rh_registered
      expect(@server.upgrade_message).to eq("registration successful")
    end
  end

  context "#attach_products" do
    it "attaches products for SubscriptionManager" do
      expect(reg_system).to receive(:subscribe)

      @server.attach_products
      expect(@server.upgrade_message).to eq("attaching products")
    end
  end

  context "#configure_yum_proxy" do
    it "with no proxy server" do
      expect(IniFile).not_to receive(:load)

      @server.configure_yum_proxy
    end

    it "with proxy server but no credentials" do
      database.update_attributes(:registration_http_proxy_server => "http://my_proxy:port")

      Tempfile.open do |tempfile|
        stub_inifile = IniFile.new(:filename => tempfile.path)
        expect(IniFile).to receive(:load).and_return(stub_inifile)

        @server.configure_yum_proxy

        expect(File.read(tempfile)).to eq("[main]\nproxy = http://my_proxy:port\n\n")
      end
    end

    it "with proxy server and credentials" do
      database.update_authentication(:registration_http_proxy => {:userid => "user", :password => "pass"})
      database.update_attributes(:registration_http_proxy_server => "http://my_proxy:port")

      Tempfile.open do |tempfile|
        stub_inifile = IniFile.new(:filename => tempfile.path)
        expect(IniFile).to receive(:load).and_return(stub_inifile)

        @server.configure_yum_proxy

        expect(File.read(tempfile)).to eq("[main]\nproxy = http://my_proxy:port\nproxy_username = user\nproxy_password = pass\n\n")
      end
    end
  end

  context "#repo_enabled?" do
    it "true" do
      expect(reg_system).to receive(:enabled_repos).and_return(["abc", database.update_repo_names].flatten)

      expect(@server.repos_enabled?).to be_truthy
      expect(@server.upgrade_message).to eq("registered")
    end

    it "false" do
      expect(reg_system).to receive(:enabled_repos).and_return(["abc", "def"])

      expect(@server.repos_enabled?).to be_falsey
    end
  end

  describe "#enable_repos" do
    it "enables all repos in the list" do
      expect(reg_system).to receive(:enable_repo).twice

      @server.enable_repos
      expect(@server.upgrade_message).to eq("enabling repo-2")
    end

    it "raises a notification for repos which fail to enable" do
      NotificationType.seed
      result = AwesomeSpawn::CommandResult.new("stuff", "things", "more things", 1)
      err = LinuxAdmin::SubscriptionManagerError.new("things", result)

      expect(reg_system).to receive(:enable_repo).with("repo-1", anything).and_raise(err)
      expect(reg_system).to receive(:enable_repo).with("repo-2", anything)

      @server.enable_repos
      note = Notification.find_by(:notification_type_id => NotificationType.find_by(:name => "enable_update_repo_failed").id)
      expect(note.options).to eq(:repo_name => "repo-1")
    end
  end

  it "#check_updates" do
    expect(yum).to receive(:updates_available?).twice.and_return(true)
    expect(yum).to receive(:version_available).with("cfme-appliance").once.and_return("cfme-appliance" => "3.1")
    allow(MiqDatabase).to receive_messages(:postgres_package_name => "postgresql-server")

    @server.check_updates

    expect(database.reload.cfme_version_available).to eq("3.1")
  end

  context "#apply_updates" do
    before do
      allow(MiqDatabase).to receive_messages(:postgres_package_name => "postgresql-server")
    end

    it "will apply cfme updates only with local database" do
      expect(yum).to receive(:updates_available?).twice.and_return(true)
      expect(yum).to receive(:version_available).once.and_return({})
      expect(Dir).to receive(:glob).and_return(["/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release", "/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-beta"])
      expect(LinuxAdmin::Rpm).to receive(:import_key).with("/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release").and_return(true)
      expect(LinuxAdmin::Rpm).to receive(:import_key).with("/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-beta").and_return(true)
      expect(EvmDatabase).to receive(:local?).and_return(true)

      @server.apply_updates
      expect(File.read(described_class::UPDATE_FILE)).to eq("cfme-appliance")
      FileUtils.rm_f(described_class::UPDATE_FILE)
    end

    it "will apply all updates with remote database" do
      expect(yum).to receive(:updates_available?).twice.and_return(true)
      expect(yum).to receive(:version_available).once.and_return({})
      expect(Dir).to receive(:glob).and_return(["/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release"])
      expect(LinuxAdmin::Rpm).to receive(:import_key).with("/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release").and_return(true)
      expect(EvmDatabase).to receive(:local?).and_return(false)

      @server.apply_updates
      expect(File.read(described_class::UPDATE_FILE)).to eq("")
      FileUtils.rm_f(described_class::UPDATE_FILE)
    end

    it "does not have updates to apply" do
      expect(yum).to receive(:updates_available?).twice.and_return(false)
      expect(yum).to receive(:version_available).once.and_return({})
      allow(MiqDatabase).to receive_messages(:postgres_package_name => "postgresql-server")

      @server.apply_updates
      expect(File.exist?(described_class::UPDATE_FILE)).to be false
    end
  end

  context "#cfme_available_update" do
    before do
      @server.update_attribute(:version, "1.2.3.4")
      MiqServer.my_server_clear_cache
    end

    it "with nil version available" do
      database.update_attribute(:cfme_version_available, nil)

      expect(@server.cfme_available_update).to be_nil
    end

    it "with short version available" do
      database.update_attribute(:cfme_version_available, "1.2.3")

      expect(@server.cfme_available_update).to be_nil
    end

    it "with equal versions" do
      database.update_attribute(:cfme_version_available, "1.2.3.4")

      expect(@server.cfme_available_update).to be_nil
    end

    it "with newer build available" do
      database.update_attribute(:cfme_version_available, "1.2.3.5")

      expect(@server.cfme_available_update).to eq("build")
    end

    it "with newer major available" do
      database.update_attribute(:cfme_version_available, "2.0.0.0")

      expect(@server.cfme_available_update).to eq("major")
    end
  end

  context "private" do
    it "#assemble_registration_options" do
      database.update_authentication(:registration => {:userid => "registration_user", :password => "registration_password"})
      database.update_authentication(:registration_http_proxy => {:userid => "proxy_user", :password => "proxy_password"})
      database.update_attributes(
        :registration_organization      => "my_org",
        :registration_http_proxy_server => "my_proxy:port",
        :registration_server            => "subscription.example.com",
      )

      options = @server.send(:assemble_registration_options)

      expect(options).to eq(
        :username       => "registration_user",
        :password       => "registration_password",
        :proxy_address  => "my_proxy:port",
        :proxy_password => "proxy_password",
        :proxy_username => "proxy_user",
        :org            => "my_org",
        :server_url     => "subscription.example.com",
      )
    end
  end
end


text:
@implementation UIView (Masonry)

@end


text:
https://github.com/stanleyxu2005/dashing

The file only contains the major change history. For full change history, please check the commit log.

## 0.4.9
* Improvement (#67): Support readonly form control.

## 0.4.8
* Improvement (#65): Add a notification dialog service.
* Bugfix (#66): Be node v6 friendly.

## 0.4.7
* Improvement (#63): Hide placeholder text when search box is focused.
* Improvement (#64): When file picker has a selection, click on the input box should show the file browse dialog again.

## 0.4.6
* Feature (#62): Create a confirmation dialog service.
* Improvement (#60): Hide table header when no records in table (not in search mode).
* Improvement (#61): Sort data point values in chart's tooltip by name.

## 0.4.5
* Bugfix (#57): Date picker was not rendered correctly for Firefox.
* Bugfix (#55): Date time picker control was not aligned on small screen.
* Bugfix (#59): Library breaks with angular 1.4.9.
* Updated example build script (angular 1.4.9 has conflict with attribute required="true").

## 0.4.4
* Improvment (#54): Tooltip of table caption will be right to the caption.

## 0.4.3
* Improvment (#54): Allow table caption to have tooltip and sub-caption.

## 0.4.2
* Improvment (#44): Allow to override line and bar chart's margin.
* Bugfix (#1): When window is resized, the bar chart should recalculate all bar positions.

## 0.4.1
* Feature (#51): Exposed charts apis to directive. Chart will be repainted, if option is changed.
* Improvement (#52): Optional to hide "0" on y-axis for line and bar charts.

## 0.4.0
* Improvement (#49): Auto select the current date for date picker.
* Improvement (#50): Allow to customize empty sortable table.

## 0.3.9
* Improvement (#2): Click sort arrow will show animation.
* Improvement: Able to align a numberic column to left by setting `.textLeft()`.
* Improvement: Tooltip y-position will be 10px below chart top border.
* Bugfix: Bar chart will have an integral bar width and updated the demo page.

## 0.3.8
* Improvement (#47): Use a more elegant/active color theme for bar chart.
* Bugfix (#46): Sortable table wont render records correctly if sort key's value equals 0.
* Bugfix (#45): Chart's right margin was too large (when only one y-axis is used).
* Bugfix (#42): Added a helper method to update `<sortable-table>` records and changed the pagination control.
* Bugfix (#41): `<sortable-table>` flicker, if default sort direction is descending.

## 0.3.7
* Feature (#22): Polished datetime picker.
* Improvement (#38): Add onclick event to remark icon of `<metrics>`.
* Improvement: Provide a bugfix style for stripe cell in `<sortable-table>`.

## 0.3.6
* Improvement (#26): Support file upload control as `<form-control>`.
* Improvement: `<form-control>` The ng-model of datetime picker is now an array with date string and time string.

## 0.3.5
* Improvement (#37): Pluralize `<metrics>` unit.
* Bugfix (#36): Remark icon might disappear.

## 0.3.4
* Improvement (#35): Open link in new page for property `<button>`.
* Bugfix (#10): Property `<indicator shape="stripe">` wont show in MSIE and Firefox.

## 0.3.3
* Improvement (#34): Allow `<metrics>` to show warning or information remark icon.

## 0.3.1
* Improvement (#33): Property `<bytes>` is deprecated. Use `<number>` instead, which provides precision, unit and human-readable.

## 0.3.0
* Improvement (#31): Allow Number1 and Number2 as showing 1 or 2 digits after period in property table.

## 0.2.9
* Breaking changes (#27): `<form-control>` numeric types are all called "integer". Specify the `min` to `0`, `1` or undefined for different validators.
* Improvement (#27): `<form-control>` supports "multi-checks" and "check".
* Improvement (#29): `<property renderer="Link">` supports "target=_blank".
* Bugfix (#25): ui-select required style sheets were missing.
* Bugfix (#30): `$sortableTableBuilder` should warn developer to specify a sort key, if multipe keys are defined for a column.

## 0.2.8 (0.2.7 was published to npm corrupted)

## 0.2.7
* Improvement: Added two chinese fonts "Hiragino Sans GB" and "Microsoft YaHei" in style sheets.
* Improvement (#20): Fixed several look and feel glitches when charts are grouped together.
* Bugfix (#21): `<form-control>`'s label should not right aligned when page is very narrow.
* Bugfix: Always show axis line and ticks at the bottom of `<line-chart>`.

## 0.2.6
* Feature (#19): `<form-control>` support radio group.
* Feature (#18): `<line-chart>` allows to have a secondary y-axis.

## 0.2.5
* Feature (#13): Support to render 2-value data as a `<ring-chart>`.
* Improvement: Specify tooltip position for `<remark>`.
* Feature: Added `<form-control>` to build a consistent input form. Supports text/dropdown/numeric inputs with validation.

## 0.2.4
* Improvement (#12): Prior to 0.2.2, found a solution to hide tooltip when chart's selection is empty.

## 0.2.3 (Hotfix to 0.2.2)
* Bugfix : gulp would strip too many blank spaces in 0.2.2.
* Improvement: Exposed method `toHumanReadableDuration` to util module.

## 0.2.2
* Improvement: If visibleDataPointsNum is specified, the chart will be initialized the empty point positions with placeholders. This change fixes animation flicker while adding data points.
* Feature (#6): Allows to group `<line-chart>` components. (Dashing-deps 0.0.7 is required)
* Improvement (#11): PropertyTableBuilder is able to change layout direction for a multiple renderers cell.

## 0.2.0
* Feature (#8): Polished data points of a `<line-chart>` by having a semi-transparent border.
* Feature (#4, #5): `<bar-chart>` has more layouts (including rotated chart, bar with negative color).

## 0.1.9
* Improvement: Thousand separator support for chart labels and tooltips.
* Improvement: npm will include release files and github will be responsible for source code only.

## 0.1.8
* Feature: Add timeline support for `<line-chart>`. Previously x-axis can only have string labels.

## 0.1.7
* Improvement: If no initial data is provided, the chart is still able to be created. With a "No Graph Data Available" animation.
* Bugfix: The default sort ordering of `<sortable-table>` was wrong.

## 0.1.6
* Feature: Auto format y-axis. By default it will be formatted in a human readable notation.
* Feature: `<line-chart>` will have minor split lines.

## 0.1.4
* Feature: Provided builder to build and update `<property-table>` and `<sortable-table>`.
* Improvement: `<bar-chart>` will calculate bar width regarding specified data values.
* Improvement: Moved the custom Echarts build to dashing-deps project.

*The older versions are not documented well. We start the change log from here.*