text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.clients.commerce.customer;

import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 * Use the Customer Segments resource to manage the segments that enable a client to manage groups of customers and target discounts for these segments. After a customer segment is defined, you can associate any number of customer accounts with it.
 *
 */
public class CustomerSegmentClient {

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection> mozuClient=GetSegmentsClient();
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegmentCollection customerSegmentCollection = client.Result();
	 *

	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegmentCollection>
	 * @see com.mozu.api.contracts.customer.CustomerSegmentCollection
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection> getSegmentsClient() throws Exception
	{
		return getSegmentsClient( null,  null,  null,  null,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection> mozuClient=GetSegmentsClient( startIndex,  pageSize,  sortBy,  filter,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegmentCollection customerSegmentCollection = client.Result();
	 *

	 * @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
	 * @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.
	 * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegmentCollection>
	 * @see com.mozu.api.contracts.customer.CustomerSegmentCollection
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection> getSegmentsClient(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.getSegmentsUrl(filter, pageSize, responseFields, sortBy, startIndex);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.customer.CustomerSegmentCollection.class;
		MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerSegmentCollection>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=GetSegmentClient( id);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> getSegmentClient(Integer id) throws Exception
	{
		return getSegmentClient( id,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=GetSegmentClient( id,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> getSegmentClient(Integer id, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.getSegmentUrl(id, responseFields);
		String verb = "GET";
		Class<?> clz = com.mozu.api.contracts.customer.CustomerSegment.class;
		MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerSegment>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=AddSegmentClient( segment);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param segment The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> addSegmentClient(com.mozu.api.contracts.customer.CustomerSegment segment) throws Exception
	{
		return addSegmentClient( segment,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=AddSegmentClient( segment,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param segment The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> addSegmentClient(com.mozu.api.contracts.customer.CustomerSegment segment, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.addSegmentUrl(responseFields);
		String verb = "POST";
		Class<?> clz = com.mozu.api.contracts.customer.CustomerSegment.class;
		MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerSegment>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(segment);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=AddSegmentAccountsClient( accountIds,  id);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @param accountIds List of customer account IDs to add to the customer segment specified in the request.
	 * @return Mozu.Api.MozuClient
	 * @see int
	 */
	public static MozuClient addSegmentAccountsClient(List<Integer> accountIds, Integer id) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.addSegmentAccountsUrl(id);
		String verb = "POST";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(accountIds);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=UpdateSegmentClient( segment,  id);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @param segment The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> updateSegmentClient(com.mozu.api.contracts.customer.CustomerSegment segment, Integer id) throws Exception
	{
		return updateSegmentClient( segment,  id,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient=UpdateSegmentClient( segment,  id,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * CustomerSegment customerSegment = client.Result();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @param segment The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerSegment>
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 * @see com.mozu.api.contracts.customer.CustomerSegment
	 */
	public static MozuClient<com.mozu.api.contracts.customer.CustomerSegment> updateSegmentClient(com.mozu.api.contracts.customer.CustomerSegment segment, Integer id, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.updateSegmentUrl(id, responseFields);
		String verb = "PUT";
		Class<?> clz = com.mozu.api.contracts.customer.CustomerSegment.class;
		MozuClient<com.mozu.api.contracts.customer.CustomerSegment> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerSegment>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		mozuClient.setBody(segment);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=DeleteSegmentClient( id);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param id Unique identifier of the customer segment to retrieve.
	 * @return Mozu.Api.MozuClient
	 */
	public static MozuClient deleteSegmentClient(Integer id) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.deleteSegmentUrl(id);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient mozuClient=RemoveSegmentAccountClient( id,  accountId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 *

	 * @param accountId Unique identifier of the customer account.
	 * @param id Unique identifier of the customer segment to retrieve.
	 * @return Mozu.Api.MozuClient
	 */
	public static MozuClient removeSegmentAccountClient(Integer id, Integer accountId) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.customer.CustomerSegmentUrl.removeSegmentAccountUrl(accountId, id);
		String verb = "DELETE";
				MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

}


text:
using content::OpenURLParams;
using content::WebContents;

namespace {

// Delay, in ms, during dragging before we bring a window to front.
const int kBringToFrontDelay = 750;

// Used to determine how far a tab must obscure another tab in order to swap
// their indexes.
const int kHorizontalMoveThreshold = 16;  // pixels

// How far a drag must pull a tab out of the tabstrip in order to detach it.
const int kVerticalDetachMagnetism = 15;  // pixels

// Returns the bounds that will be used for insertion index calculation.
// |bounds| is the actual tab bounds, but subtracting the overlapping areas from
// both sides makes the calculations much simpler.
gfx::Rect GetEffectiveBounds(const gfx::Rect& bounds) {
  gfx::Rect effective_bounds(bounds);
  effective_bounds.set_width(effective_bounds.width() - 2 * 16);
  effective_bounds.set_x(effective_bounds.x() + 16);
  return effective_bounds;
}

}  // namespace

DraggedTabControllerGtk::DraggedTabControllerGtk(
    TabStripGtk* source_tabstrip,
    TabGtk* source_tab,
    const std::vector<TabGtk*>& tabs)
    : source_tabstrip_(source_tabstrip),
      attached_tabstrip_(source_tabstrip),
      in_destructor_(false),
      last_move_screen_x_(0),
      initial_move_(true) {
  DCHECK(!tabs.empty());
  DCHECK(std::find(tabs.begin(), tabs.end(), source_tab) != tabs.end());

  std::vector<DraggedTabData> drag_data;
  for (size_t i = 0; i < tabs.size(); i++)
    drag_data.push_back(InitDraggedTabData(tabs[i]));

  int source_tab_index =
      std::find(tabs.begin(), tabs.end(), source_tab) - tabs.begin();
  drag_data_.reset(new DragData(drag_data, source_tab_index));
}

DraggedTabControllerGtk::~DraggedTabControllerGtk() {
  in_destructor_ = true;
  // Need to delete the dragged tab here manually _before_ we reset the dragged
  // contents to NULL, otherwise if the view is animating to its destination
  // bounds, it won't be able to clean up properly since its cleanup routine
  // uses GetIndexForDraggedContents, which will be invalid.
  CleanUpDraggedTabs();
  dragged_view_.reset();
  drag_data_.reset();
}

void DraggedTabControllerGtk::CaptureDragInfo(const gfx::Point& mouse_offset) {
  start_screen_point_ = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
  mouse_offset_ = mouse_offset;
}

void DraggedTabControllerGtk::Drag() {
  if (!drag_data_->GetSourceTabData()->tab_ ||
      !drag_data_->GetSourceTabContents() ||
      !drag_data_->GetSourceWebContents()) {
    return;
  }

  bring_to_front_timer_.Stop();

  EnsureDraggedView();

  // Before we get to dragging anywhere, ensure that we consider ourselves
  // attached to the source tabstrip.
  if (drag_data_->GetSourceTabData()->tab_->IsVisible()) {
    Attach(source_tabstrip_, gfx::Point());
  }

  if (!drag_data_->GetSourceTabData()->tab_->IsVisible()) {
    // TODO(jhawkins): Save focus.
    ContinueDragging();
  }
}

bool DraggedTabControllerGtk::EndDrag(bool canceled) {
  return EndDragImpl(canceled ? CANCELED : NORMAL);
}

TabGtk* DraggedTabControllerGtk::GetDraggedTabForContents(
    WebContents* contents) {
  if (attached_tabstrip_ == source_tabstrip_) {
    for (size_t i = 0; i < drag_data_->size(); i++) {
      if (contents == drag_data_->get(i)->contents_->web_contents())
        return drag_data_->get(i)->tab_;
    }
  }
  return NULL;
}

bool DraggedTabControllerGtk::IsDraggingTab(const TabGtk* tab) {
  for (size_t i = 0; i < drag_data_->size(); i++) {
    if (tab == drag_data_->get(i)->tab_)
      return true;
  }
  return false;
}

bool DraggedTabControllerGtk::IsDraggingTabContents(
    const TabContents* tab_contents) {
  for (size_t i = 0; i < drag_data_->size(); i++) {
    if (tab_contents == drag_data_->get(i)->contents_)
      return true;
  }
  return false;
}

bool DraggedTabControllerGtk::IsTabDetached(const TabGtk* tab) {
  return IsDraggingTab(tab) && attached_tabstrip_ == NULL;
}

DraggedTabData DraggedTabControllerGtk::InitDraggedTabData(TabGtk* tab) {
  int source_model_index = source_tabstrip_->GetIndexOfTab(tab);
  TabContents* contents =
      source_tabstrip_->model()->GetTabContentsAt(source_model_index);
  bool pinned = source_tabstrip_->IsTabPinned(tab);
  bool mini = source_tabstrip_->model()->IsMiniTab(source_model_index);
  // We need to be the delegate so we receive messages about stuff,
  // otherwise our dragged_contents() may be replaced and subsequently
  // collected/destroyed while the drag is in process, leading to
  // nasty crashes.
  content::WebContentsDelegate* original_delegate =
      contents->web_contents()->GetDelegate();
  contents->web_contents()->SetDelegate(this);

  DraggedTabData dragged_tab_data(tab, contents, original_delegate,
                                  source_model_index, pinned, mini);
  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
      content::Source<WebContents>(contents->web_contents()));
  return dragged_tab_data;
}

////////////////////////////////////////////////////////////////////////////////
// DraggedTabControllerGtk, content::WebContentsDelegate implementation:

WebContents* DraggedTabControllerGtk::OpenURLFromTab(
    WebContents* source,
    const OpenURLParams& params) {
  if (drag_data_->GetSourceTabData()->original_delegate_) {
    OpenURLParams forward_params = params;
    if (params.disposition == CURRENT_TAB)
      forward_params.disposition = NEW_WINDOW;

    return drag_data_->GetSourceTabData()->original_delegate_->
        OpenURLFromTab(source, forward_params);
  }
  return NULL;
}

void DraggedTabControllerGtk::NavigationStateChanged(const WebContents* source,
                                                     unsigned changed_flags) {
  if (dragged_view_.get())
    dragged_view_->Update();
}

void DraggedTabControllerGtk::AddNewContents(WebContents* source,
                                             WebContents* new_contents,
                                             WindowOpenDisposition disposition,
                                             const gfx::Rect& initial_pos,
                                             bool user_gesture,
                                             bool* was_blocked) {
  DCHECK(disposition != CURRENT_TAB);

  // Theoretically could be called while dragging if the page tries to
  // spawn a window. Route this message back to the browser in most cases.
  if (drag_data_->GetSourceTabData()->original_delegate_) {
    drag_data_->GetSourceTabData()->original_delegate_->AddNewContents(
        source, new_contents, disposition, initial_pos, user_gesture,
        was_blocked);
  }
}

void DraggedTabControllerGtk::LoadingStateChanged(WebContents* source) {
  // TODO(jhawkins): It would be nice to respond to this message by changing the
  // screen shot in the dragged tab.
  if (dragged_view_.get())
    dragged_view_->Update();
}

content::JavaScriptDialogCreator*
DraggedTabControllerGtk::GetJavaScriptDialogCreator() {
  return GetJavaScriptDialogCreatorInstance();
}

////////////////////////////////////////////////////////////////////////////////
// DraggedTabControllerGtk, content::NotificationObserver implementation:

void DraggedTabControllerGtk::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type);
  WebContents* destroyed_web_contents =
      content::Source<WebContents>(source).ptr();
  for (size_t i = 0; i < drag_data_->size(); ++i) {
    if (drag_data_->get(i)->contents_->web_contents() ==
        destroyed_web_contents) {
      // One of the tabs we're dragging has been destroyed. Cancel the drag.
      if (destroyed_web_contents->GetDelegate() == this)
        destroyed_web_contents->SetDelegate(NULL);
      drag_data_->get(i)->contents_ = NULL;
      drag_data_->get(i)->original_delegate_ = NULL;
      EndDragImpl(TAB_DESTROYED);
      return;
    }
  }
  // If we get here it means we got notification for a tab we don't know about.
  NOTREACHED();
}

gfx::Point DraggedTabControllerGtk::GetWindowCreatePoint() const {
  gfx::Point creation_point =
      gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
  gfx::Point distance_from_origin =
      dragged_view_->GetDistanceFromTabStripOriginToMousePointer();
  // TODO(dpapad): offset also because of tabstrip origin being different than
  // window origin.
  creation_point.Offset(-distance_from_origin.x(), -distance_from_origin.y());
  return creation_point;
}

void DraggedTabControllerGtk::ContinueDragging() {
  // TODO(jhawkins): We don't handle the situation where the last tab is dragged
  // out of a window, so we'll just go with the way Windows handles dragging for
  // now.
  gfx::Point screen_point =
      gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();

  // Determine whether or not we have dragged over a compatible TabStrip in
  // another browser window. If we have, we should attach to it and start
  // dragging within it.
  TabStripGtk* target_tabstrip = GetTabStripForPoint(screen_point);
  if (target_tabstrip != attached_tabstrip_) {
    // Make sure we're fully detached from whatever TabStrip we're attached to
    // (if any).
    if (attached_tabstrip_)
      Detach();

    if (target_tabstrip)
      Attach(target_tabstrip, screen_point);
  }

  if (!target_tabstrip) {
    bring_to_front_timer_.Start(FROM_HERE,
        base::TimeDelta::FromMilliseconds(kBringToFrontDelay), this,
        &DraggedTabControllerGtk::BringWindowUnderMouseToFront);
  }

  if (attached_tabstrip_)
    MoveAttached(screen_point);
  else
    MoveDetached(screen_point);
}

void DraggedTabControllerGtk::RestoreSelection(TabStripModel* model) {
  for (size_t i = 0; i < drag_data_->size(); ++i) {
    TabContents* contents = drag_data_->get(i)->contents_;
    // If a tab is destroyed while dragging contents might be null. See
    // http://crbug.com/115409.
    if (contents != NULL) {
      int index = model->GetIndexOfTabContents(contents);
      CHECK(index != TabStripModel::kNoTab);
      model->AddTabAtToSelection(index);
    }
  }
}

void DraggedTabControllerGtk::MoveAttached(const gfx::Point& screen_point) {
  DCHECK(attached_tabstrip_);

  gfx::Point dragged_view_point = GetDraggedViewPoint(screen_point);
  TabStripModel* attached_model = attached_tabstrip_->model();

  std::vector<TabGtk*> tabs(drag_data_->GetDraggedTabs());

  // Determine the horizontal move threshold. This is dependent on the width
  // of tabs. The smaller the tabs compared to the standard size, the smaller
  // the threshold.
  double unselected, selected;
  attached_tabstrip_->GetCurrentTabWidths(&unselected, &selected);
  double ratio = unselected / TabGtk::GetStandardSize().width();
  int threshold = static_cast<int>(ratio * kHorizontalMoveThreshold);

  // Update the model, moving the TabContents from one index to another.
  // Do this only if we have moved a minimum distance since the last reorder (to
  // prevent jitter) or if this is the first move and the tabs are not
  // consecutive.
  if (abs(screen_point.x() - last_move_screen_x_) > threshold ||
      (initial_move_ && !AreTabsConsecutive())) {
    if (initial_move_ && !AreTabsConsecutive()) {
      // Making dragged tabs adjacent, this is done only once, if necessary.
      attached_tabstrip_->model()->MoveSelectedTabsTo(
          drag_data_->GetSourceTabData()->source_model_index_ -
              drag_data_->source_tab_index());
    }
    gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point);
    int to_index = GetInsertionIndexForDraggedBounds(
        GetEffectiveBounds(bounds));
    to_index = NormalizeIndexToAttachedTabStrip(to_index);
    last_move_screen_x_ = screen_point.x();
    attached_model->MoveSelectedTabsTo(to_index);
  }

  dragged_view_->MoveAttachedTo(dragged_view_point);
  initial_move_ = false;
}

void DraggedTabControllerGtk::MoveDetached(const gfx::Point& screen_point) {
  DCHECK(!attached_tabstrip_);
  // Just moving the dragged view. There are no changes to the model if we're
  // detached.
  dragged_view_->MoveDetachedTo(screen_point);
}

TabStripGtk* DraggedTabControllerGtk::GetTabStripForPoint(
    const gfx::Point& screen_point) {
  GtkWidget* dragged_window = dragged_view_->widget();
  dock_windows_.insert(dragged_window);
  gfx::NativeWindow local_window =
      DockInfo::GetLocalProcessWindowAtPoint(
          chrome::HOST_DESKTOP_TYPE_NATIVE, screen_point, dock_windows_);
  dock_windows_.erase(dragged_window);
  if (!local_window)
    return NULL;

  BrowserWindowGtk* browser =
      BrowserWindowGtk::GetBrowserWindowForNativeWindow(local_window);
  if (!browser)
    return NULL;

  TabStripGtk* other_tabstrip = browser->tabstrip();
  if (!other_tabstrip->IsCompatibleWith(source_tabstrip_))
    return NULL;

  return GetTabStripIfItContains(other_tabstrip, screen_point);
}

TabStripGtk* DraggedTabControllerGtk::GetTabStripIfItContains(
    TabStripGtk* tabstrip, const gfx::Point& screen_point) const {
  // Make sure the specified screen point is actually within the bounds of the
  // specified tabstrip...
  gfx::Rect tabstrip_bounds =
      ui::GetWidgetScreenBounds(tabstrip->tabstrip_.get());
  if (screen_point.x() < tabstrip_bounds.right() &&
      screen_point.x() >= tabstrip_bounds.x()) {
    // TODO(beng): make this be relative to the start position of the mouse for
    // the source TabStrip.
    int upper_threshold = tabstrip_bounds.bottom() + kVerticalDetachMagnetism;
    int lower_threshold = tabstrip_bounds.y() - kVerticalDetachMagnetism;
    if (screen_point.y() >= lower_threshold &&
        screen_point.y() <= upper_threshold) {
      return tabstrip;
    }
  }

  return NULL;
}

void DraggedTabControllerGtk::Attach(TabStripGtk* attached_tabstrip,
                                     const gfx::Point& screen_point) {
  attached_tabstrip_ = attached_tabstrip;
  attached_tabstrip_->GenerateIdealBounds();

  std::vector<TabGtk*> attached_dragged_tabs =
      GetTabsMatchingDraggedContents(attached_tabstrip_);

  // Update the tab first, so we can ask it for its bounds and determine
  // where to insert the hidden tab.

  // If this is the first time Attach is called for this drag, we're attaching
  // to the source tabstrip, and we should assume the tab count already
  // includes this tab since we haven't been detached yet. If we don't do this,
  // the dragged representation will be a different size to others in the
  // tabstrip.
  int tab_count = attached_tabstrip_->GetTabCount();
  int mini_tab_count = attached_tabstrip_->GetMiniTabCount();
  if (attached_dragged_tabs.size() == 0) {
    tab_count += drag_data_->size();
    mini_tab_count += drag_data_->mini_tab_count();
  }

  double unselected_width = 0, selected_width = 0;
  attached_tabstrip_->GetDesiredTabWidths(tab_count, mini_tab_count,
                                          &unselected_width, &selected_width);

  GtkWidget* parent_window = gtk_widget_get_parent(
      gtk_widget_get_parent(attached_tabstrip_->tabstrip_.get()));
  gfx::Rect window_bounds = ui::GetWidgetScreenBounds(parent_window);
  dragged_view_->Attach(static_cast<int>(floor(selected_width + 0.5)),
                        TabGtk::GetMiniWidth(), window_bounds.width());

  if (attached_dragged_tabs.size() == 0) {
    // There is no tab in |attached_tabstrip| that corresponds to the dragged
    // TabContents. We must now create one.

    // Remove ourselves as the delegate now that the dragged TabContents
    // is being inserted back into a Browser.
    for (size_t i = 0; i < drag_data_->size(); ++i) {
      drag_data_->get(i)->contents_->web_contents()->SetDelegate(NULL);
      drag_data_->get(i)->original_delegate_ = NULL;
    }

    // Return the TabContents to normalcy.
    drag_data_->GetSourceWebContents()->SetCapturingContents(false);

    // We need to ask the tabstrip we're attached to ensure that the ideal
    // bounds for all its tabs are correctly generated, because the calculation
    // in GetInsertionIndexForDraggedBounds needs them to be to figure out the
    // appropriate insertion index.
    attached_tabstrip_->GenerateIdealBounds();

    // Inserting counts as a move. We don't want the tabs to jitter when the
    // user moves the tab immediately after attaching it.
    last_move_screen_x_ = screen_point.x();

    // Figure out where to insert the tab based on the bounds of the dragged
    // representation and the ideal bounds of the other tabs already in the
    // strip. ("ideal bounds" are stable even if the tabs' actual bounds are
    // changing due to animation).
    gfx::Rect bounds =
        GetDraggedViewTabStripBounds(GetDraggedViewPoint(screen_point));
    int index = GetInsertionIndexForDraggedBounds(GetEffectiveBounds(bounds));
    for (size_t i = 0; i < drag_data_->size(); ++i) {
      attached_tabstrip_->model()->InsertTabContentsAt(
          index + i, drag_data_->get(i)->contents_,
          drag_data_->GetAddTypesForDraggedTabAt(i));
    }
    RestoreSelection(attached_tabstrip_->model());
    attached_dragged_tabs = GetTabsMatchingDraggedContents(attached_tabstrip_);
  }
  // We should now have a tab.
  DCHECK(attached_dragged_tabs.size() == drag_data_->size());
  SetDraggedTabsVisible(false, false);
  // TODO(jhawkins): Move the corresponding window to the front.
}

void DraggedTabControllerGtk::Detach() {
  // Update the Model.
  TabStripModel* attached_model = attached_tabstrip_->model();
  for (size_t i = 0; i < drag_data_->size(); ++i) {
    int index =
        attached_model->GetIndexOfTabContents(drag_data_->get(i)->contents_);
    if (index >= 0 && index < attached_model->count()) {
      // Sometimes, DetachTabContentsAt has consequences that result in
      // attached_tabstrip_ being set to NULL, so we need to save it first.
      attached_model->DetachTabContentsAt(index);
    }
  }

  // If we've removed the last tab from the tabstrip, hide the frame now.
  if (attached_model->empty())
    HideWindow();

  // Update the dragged tab. This NULL check is necessary apparently in some
  // conditions during automation where the view_ is destroyed inside a
  // function call preceding this point but after it is created.
  if (dragged_view_.get()) {
    dragged_view_->Detach();
  }

  // Detaching resets the delegate, but we still want to be the delegate.
  for (size_t i = 0; i < drag_data_->size(); ++i)
    drag_data_->get(i)->contents_->web_contents()->SetDelegate(this);

  attached_tabstrip_ = NULL;
}

gfx::Point DraggedTabControllerGtk::ConvertScreenPointToTabStripPoint(
    TabStripGtk* tabstrip, const gfx::Point& screen_point) {
  return screen_point - ui::GetWidgetScreenOffset(tabstrip->tabstrip_.get());
}

gfx::Rect DraggedTabControllerGtk::GetDraggedViewTabStripBounds(
    const gfx::Point& screen_point) {
  gfx::Point client_point =
      ConvertScreenPointToTabStripPoint(attached_tabstrip_, screen_point);
  gfx::Size tab_size = dragged_view_->attached_tab_size();
  return gfx::Rect(client_point.x(), client_point.y(),
                   dragged_view_->GetTotalWidthInTabStrip(), tab_size.height());
}

int DraggedTabControllerGtk::GetInsertionIndexForDraggedBounds(
    const gfx::Rect& dragged_bounds) {
  int dragged_bounds_start = gtk_util::MirroredLeftPointForRect(
      attached_tabstrip_->widget(),
      dragged_bounds);
  int dragged_bounds_end = gtk_util::MirroredRightPointForRect(
      attached_tabstrip_->widget(),
      dragged_bounds);
  int right_tab_x = 0;
  int index = -1;

  for (int i = 0; i < attached_tabstrip_->GetTabCount(); i++) {
    // Divides each tab into two halves to see if the dragged tab has crossed
    // the halfway boundary necessary to move past the next tab.
    gfx::Rect ideal_bounds = attached_tabstrip_->GetIdealBounds(i);
    gfx::Rect left_half, right_half;
    ideal_bounds.SplitVertically(&left_half, &right_half);
    right_tab_x = right_half.x();

    if (dragged_bounds_start >= right_half.x() &&
        dragged_bounds_start < right_half.right()) {
      index = i + 1;
      break;
    } else if (dragged_bounds_start >= left_half.x() &&
               dragged_bounds_start < left_half.right()) {
      index = i;
      break;
    }
  }

  if (index == -1) {
    if (dragged_bounds_end > right_tab_x)
      index = attached_tabstrip_->GetTabCount();
    else
      index = 0;
  }

  TabGtk* tab = GetTabMatchingDraggedContents(
      attached_tabstrip_, drag_data_->GetSourceTabContents());
  if (tab == NULL) {
    // If dragged tabs are not attached yet, we don't need to constrain the
    // index.
    return index;
  }

  int max_index =
      attached_tabstrip_-> GetTabCount() - static_cast<int>(drag_data_->size());
  return std::max(0, std::min(max_index, index));
}

gfx::Point DraggedTabControllerGtk::GetDraggedViewPoint(
    const gfx::Point& screen_point) {
  int x = screen_point.x() -
      dragged_view_->GetWidthInTabStripUpToMousePointer();
  int y = screen_point.y() - mouse_offset_.y();

  // If we're not attached, we just use x and y from above.
  if (attached_tabstrip_) {
    gfx::Rect tabstrip_bounds =
        ui::GetWidgetScreenBounds(attached_tabstrip_->tabstrip_.get());
    // Snap the dragged tab to the tabstrip if we are attached, detaching
    // only when the mouse position (screen_point) exceeds the screen bounds
    // of the tabstrip.
    if (x < tabstrip_bounds.x() && screen_point.x() >= tabstrip_bounds.x())
      x = tabstrip_bounds.x();

    gfx::Size tab_size = dragged_view_->attached_tab_size();
    int vertical_drag_magnetism = tab_size.height() * 2;
    int vertical_detach_point = tabstrip_bounds.y() - vertical_drag_magnetism;
    if (y < tabstrip_bounds.y() && screen_point.y() >= vertical_detach_point)
      y = tabstrip_bounds.y();

    // Make sure the tab can't be dragged off the right side of the tabstrip
    // unless the mouse pointer passes outside the bounds of the strip by
    // clamping the position of the dragged window to the tabstrip width less
    // the width of one tab until the mouse pointer (screen_point) exceeds the
    // screen bounds of the tabstrip.
    int max_x =
        tabstrip_bounds.right() - dragged_view_->GetTotalWidthInTabStrip();
    int max_y = tabstrip_bounds.bottom() - tab_size.height();
    if (x > max_x && screen_point.x() <= tabstrip_bounds.right())
      x = max_x;
    if (y > max_y && screen_point.y() <=
        (tabstrip_bounds.bottom() + vertical_drag_magnetism)) {
      y = max_y;
    }
  }
  return gfx::Point(x, y);
}

int DraggedTabControllerGtk::NormalizeIndexToAttachedTabStrip(int index) const {
  if (index >= attached_tabstrip_->model_->count())
    return attached_tabstrip_->model_->count() - 1;
  if (index == TabStripModel::kNoTab)
    return 0;
  return index;
}

TabGtk* DraggedTabControllerGtk::GetTabMatchingDraggedContents(
    TabStripGtk* tabstrip, TabContents* tab_contents) {
  int index = tabstrip->model()->GetIndexOfTabContents(tab_contents);
  return index == TabStripModel::kNoTab ? NULL : tabstrip->GetTabAt(index);
}

std::vector<TabGtk*> DraggedTabControllerGtk::GetTabsMatchingDraggedContents(
    TabStripGtk* tabstrip) {
  std::vector<TabGtk*> dragged_tabs;
  for (size_t i = 0; i < drag_data_->size(); ++i) {
    if (!drag_data_->get(i)->contents_)
      continue;
    TabGtk* tab = GetTabMatchingDraggedContents(tabstrip,
                                                drag_data_->get(i)->contents_);
    if (tab)
      dragged_tabs.push_back(tab);
  }
  return dragged_tabs;
}

void DraggedTabControllerGtk::SetDraggedTabsVisible(bool visible,
                                                    bool repaint) {
  std::vector<TabGtk*> dragged_tabs(GetTabsMatchingDraggedContents(
      attached_tabstrip_));
  for (size_t i = 0; i < dragged_tabs.size(); ++i) {
    dragged_tabs[i]->SetVisible(visible);
    dragged_tabs[i]->set_dragging(!visible);
    if (repaint)
      dragged_tabs[i]->SchedulePaint();
  }
}

bool DraggedTabControllerGtk::EndDragImpl(EndDragType type) {
  bring_to_front_timer_.Stop();

  // WARNING: this may be invoked multiple times. In particular, if deletion
  // occurs after a delay (as it does when the tab is released in the original
  // tab strip) and the navigation controller/tab contents is deleted before
  // the animation finishes, this is invoked twice. The second time through
  // type == TAB_DESTROYED.

  bool destroy_now = true;
  if (type != TAB_DESTROYED) {
    // If we never received a drag-motion event, the drag will never have
    // started in the sense that |dragged_view_| will be NULL. We don't need to
    // revert or complete the drag in that case.
    if (dragged_view_.get()) {
      if (type == CANCELED) {
        RevertDrag();
      } else {
        destroy_now = CompleteDrag();
      }
    }
  } else if (drag_data_->size() > 0) {
    RevertDrag();
  }

  ResetDelegates();

  // If we're not destroyed now, we'll be destroyed asynchronously later.
  if (destroy_now)
    source_tabstrip_->DestroyDragController();

  return destroy_now;
}

void DraggedTabControllerGtk::RevertDrag() {
  // We save this here because code below will modify |attached_tabstrip_|.
  bool restore_window = attached_tabstrip_ != source_tabstrip_;
  if (attached_tabstrip_) {
    if (attached_tabstrip_ != source_tabstrip_) {
      // The tabs were inserted into another tabstrip. We need to put them back
      // into the original one.
      for (size_t i = 0; i < drag_data_->size(); ++i) {
        if (!drag_data_->get(i)->contents_)
          continue;
        int index = attached_tabstrip_->model()->GetIndexOfTabContents(
            drag_data_->get(i)->contents_);
        attached_tabstrip_->model()->DetachTabContentsAt(index);
      }
      // TODO(beng): (Cleanup) seems like we should use Attach() for this
      //             somehow.
      attached_tabstrip_ = source_tabstrip_;
      for (size_t i = 0; i < drag_data_->size(); ++i) {
        if (!drag_data_->get(i)->contents_)
          continue;
        attached_tabstrip_->model()->InsertTabContentsAt(
            drag_data_->get(i)->source_model_index_,
            drag_data_->get(i)->contents_,
            drag_data_->GetAddTypesForDraggedTabAt(i));
      }
    } else {
      // The tabs were moved within the tabstrip where the drag was initiated.
      // Move them back to their starting locations.
      for (size_t i = 0; i < drag_data_->size(); ++i) {
        if (!drag_data_->get(i)->contents_)
          continue;
        int index = attached_tabstrip_->model()->GetIndexOfTabContents(
            drag_data_->get(i)->contents_);
        source_tabstrip_->model()->MoveTabContentsAt(
            index, drag_data_->get(i)->source_model_index_, true);
      }
    }
  } else {
    // TODO(beng): (Cleanup) seems like we should use Attach() for this
    //             somehow.
    attached_tabstrip_ = source_tabstrip_;
    // The tab was detached from the tabstrip where the drag began, and has not
    // been attached to any other tabstrip. We need to put it back into the
    // source tabstrip.
    for (size_t i = 0; i < drag_data_->size(); ++i) {
      if (!drag_data_->get(i)->contents_)
        continue;
      source_tabstrip_->model()->InsertTabContentsAt(
          drag_data_->get(i)->source_model_index_,
          drag_data_->get(i)->contents_,
          drag_data_->GetAddTypesForDraggedTabAt(i));
    }
  }
  RestoreSelection(source_tabstrip_->model());

  // If we're not attached to any tab strip, or attached to some other tab
  // strip, we need to restore the bounds of the original tab strip's frame, in
  // case it has been hidden.
  if (restore_window)
    ShowWindow();

  SetDraggedTabsVisible(true, false);
}

bool DraggedTabControllerGtk::CompleteDrag() {
  bool destroy_immediately = true;
  if (attached_tabstrip_) {
    // We don't need to do anything other than make the tabs visible again,
    // since the dragged view is going away.
    dragged_view_->AnimateToBounds(GetAnimateBounds(),
        base::Bind(&DraggedTabControllerGtk::OnAnimateToBoundsComplete,
                   base::Unretained(this)));
    destroy_immediately = false;
  } else {
    // Compel the model to construct a new window for the detached
    // WebContentses.
    BrowserWindowGtk* window = source_tabstrip_->window();
    gfx::Rect window_bounds = window->GetRestoredBounds();
    window_bounds.set_origin(GetWindowCreatePoint());

    std::vector<TabStripModelDelegate::NewStripContents> contentses;
    for (size_t i = 0; i < drag_data_->size(); ++i) {
      TabStripModelDelegate::NewStripContents item;
      item.web_contents = drag_data_->get(i)->contents_->web_contents();
      item.add_types = drag_data_->GetAddTypesForDraggedTabAt(i);
      contentses.push_back(item);
    };

    Browser* new_browser =
        source_tabstrip_->model()->delegate()->CreateNewStripWithContents(
            contentses, window_bounds, dock_info_, window->IsMaximized());
    RestoreSelection(new_browser->tab_strip_model());
    new_browser->window()->Show();
    CleanUpHiddenFrame();
  }

  return destroy_immediately;
}

void DraggedTabControllerGtk::ResetDelegates() {
  for (size_t i = 0; i < drag_data_->size(); ++i) {
    if (drag_data_->get(i)->contents_ &&
        drag_data_->get(i)->contents_->web_contents()->GetDelegate() == this) {
      drag_data_->get(i)->ResetDelegate();
    }
  }
}

void DraggedTabControllerGtk::EnsureDraggedView() {
  if (!dragged_view_.get()) {
    gfx::Rect rect;
    drag_data_->GetSourceWebContents()->GetContainerBounds(&rect);
    dragged_view_.reset(new DraggedViewGtk(drag_data_.get(), mouse_offset_,
                                           rect.size()));
  }
}

gfx::Rect DraggedTabControllerGtk::GetAnimateBounds() {
  // A hidden widget moved with gtk_fixed_move in a GtkFixed container doesn't
  // update its allocation until after the widget is shown, so we have to use
  // the tab bounds we keep track of.
  //
  // We use the requested bounds instead of the allocation because the
  // allocation is relative to the first windowed widget ancestor of the tab.
  // Because of this, we can't use the tabs allocation to get the screen bounds.
  std::vector<TabGtk*> tabs = GetTabsMatchingDraggedContents(
      attached_tabstrip_);
  TabGtk* tab = !base::i18n::IsRTL() ? tabs.front() : tabs.back();
  gfx::Rect bounds = tab->GetRequisition();
  GtkWidget* widget = tab->widget();
  GtkWidget* parent = gtk_widget_get_parent(widget);
  bounds.Offset(ui::GetWidgetScreenOffset(parent));

  return gfx::Rect(bounds.x(), bounds.y(),
                   dragged_view_->GetTotalWidthInTabStrip(), bounds.height());
}

void DraggedTabControllerGtk::HideWindow() {
  GtkWidget* tabstrip = source_tabstrip_->widget();
  GtkWindow* window = platform_util::GetTopLevel(tabstrip);
  gtk_widget_hide(GTK_WIDGET(window));
}

void DraggedTabControllerGtk::ShowWindow() {
  GtkWidget* tabstrip = source_tabstrip_->widget();
  GtkWindow* window = platform_util::GetTopLevel(tabstrip);
  gtk_window_present(window);
}

void DraggedTabControllerGtk::CleanUpHiddenFrame() {
  // If the model we started dragging from is now empty, we must ask the
  // delegate to close the frame.
  if (source_tabstrip_->model()->empty())
    source_tabstrip_->model()->delegate()->CloseFrameAfterDragSession();
}

void DraggedTabControllerGtk::CleanUpDraggedTabs() {
  // If we were attached to the source tabstrip, dragged tabs will be in use. If
  // we were detached or attached to another tabstrip, we can safely remove
  // them and delete them now.
  if (attached_tabstrip_ != source_tabstrip_) {
    for (size_t i = 0; i < drag_data_->size(); ++i) {
      if (drag_data_->get(i)->contents_) {
        registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
            content::Source<WebContents>(
                drag_data_->get(i)->contents_->web_contents()));
      }
      source_tabstrip_->DestroyDraggedTab(drag_data_->get(i)->tab_);
      drag_data_->get(i)->tab_ = NULL;
    }
  }
}

void DraggedTabControllerGtk::OnAnimateToBoundsComplete() {
  // Sometimes, for some reason, in automation we can be called back on a
  // detach even though we aren't attached to a tabstrip. Guard against that.
  if (attached_tabstrip_)
    SetDraggedTabsVisible(true, true);

  CleanUpHiddenFrame();

  if (!in_destructor_)
    source_tabstrip_->DestroyDragController();
}

void DraggedTabControllerGtk::BringWindowUnderMouseToFront() {
  // If we're going to dock to another window, bring it to the front.
  gfx::NativeWindow window = dock_info_.window();
  if (!window) {
    gfx::NativeView dragged_tab = dragged_view_->widget();
    dock_windows_.insert(dragged_tab);
    window = DockInfo::GetLocalProcessWindowAtPoint(
        chrome::HOST_DESKTOP_TYPE_NATIVE,
        gfx::Screen::GetNativeScreen()->GetCursorScreenPoint(),
        dock_windows_);
    dock_windows_.erase(dragged_tab);
  }

  if (window)
    gtk_window_present(GTK_WINDOW(window));
}

bool DraggedTabControllerGtk::AreTabsConsecutive() {
  for (size_t i = 1; i < drag_data_->size(); ++i) {
    if (drag_data_->get(i - 1)->source_model_index_ + 1 !=
        drag_data_->get(i)->source_model_index_) {
      return false;
    }
  }
  return true;
}

redpajama_set_name: RedPajamaGithub


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ServiceBehaviorContext.cs" company="Quartz Software SRL">
//   Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
//   The default implementation of a service behavior context.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Services.Behavior
{
    using System.Diagnostics.Contracts;

    using Kephas.Application;

    /// <summary>
    /// The default implementation of a service behavior context.
    /// </summary>
    /// <typeparam name="TServiceContract">Type of the service contract.</typeparam>
    public class ServiceBehaviorContext<TServiceContract> : ContextBase, IServiceBehaviorContext<TServiceContract>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceBehaviorContext{TServiceContract}" />
        /// class.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="appContext">Context for the application.</param>
        public ServiceBehaviorContext(TServiceContract service, IAppContext appContext = null)
        {
            Contract.Requires(service != null);

            this.Service = service;
            this.AppContext = appContext;
        }

        /// <summary>
        /// Gets the application context.
        /// </summary>
        /// <value>
        /// The application context.
        /// </value>
        public IAppContext AppContext { get; }

        /// <summary>
        /// Gets the service.
        /// </summary>
        /// <value>
        /// The service.
        /// </value>
        public TServiceContract Service { get; }
    }
}


text:
<?php

namespace System\Web;

final class HttpResponse {

    private $headers;
    private $cookies;
    private $redirect;
    private $output;
    private $statusCode;
    private $contentType;
    private $encoding;
    private static $statusCodes = array(
        //Informational 1xx
        100 => '100 Continue',
        101 => '101 Switching Protocols',
        //Successful 2xx
        200 => '200 OK',
        201 => '201 Created',
        202 => '202 Accepted',
        203 => '203 Non-Authoritative Information',
        204 => '204 No Content',
        205 => '205 Reset Content',
        206 => '206 Partial Content',
        //Redirection 3xx
        300 => '300 Multiple Choices',
        301 => '301 Moved Permanently',
        302 => '302 Found',
        303 => '303 See Other',
        304 => '304 Not Modified',
        305 => '305 Use Proxy',
        306 => '306 (Unused)',
        307 => '307 Temporary Redirect',
        //Client Error 4xx
        400 => '400 Bad Request',
        401 => '401 Unauthorized',
        402 => '402 Payment Required',
        403 => '403 Forbidden',
        404 => '404 Not Found',
        405 => '405 Method Not Allowed',
        406 => '406 Not Acceptable',
        407 => '407 Proxy Authentication Required',
        408 => '408 Request Timeout',
        409 => '409 Conflict',
        410 => '410 Gone',
        411 => '411 Length Required',
        412 => '412 Precondition Failed',
        413 => '413 Request Entity Too Large',
        414 => '414 Request-URI Too Long',
        415 => '415 Unsupported Media Type',
        416 => '416 Requested Range Not Satisfiable',
        417 => '417 Expectation Failed',
        422 => '422 Unprocessable Entity',
        423 => '423 Locked',
        //Server Error 5xx
        500 => '500 Internal Server Error',
        501 => '501 Not Implemented',
        502 => '502 Bad Gateway',
        503 => '503 Service Unavailable',
        504 => '504 Gateway Timeout',
        505 => '505 HTTP Version Not Supported'
    );

    /**
     * Initializes a new instance of the HttpResponse class.
     *
     */
    public function __construct(){
        $this->cookies = new HttpCookieCollection(array());
        $this->headers = new \System\Collections\Dictionary();
        $this->setContentType('text/html');
        $this->setContentEncoding('UTF-8');
        $this->setStatusCode(200);
    }

    /**
     * Sets the HTTP content type of the output.
     *
     * @param   string $contentType
     * @return  System.Web.HttpResponse
     */
    public function setContentType($contentType){
        $this->contentType = $contentType;
        $this->addHeader('Content-type', $this->contentType.';'.$this->encoding, true);
        return $this;
    }

    /**
     * Gets the HTTP content type of the output.
     *
     * @return  string
     */
    public function getContentType(){
        return $this->contentType;
    }

    /**
     * Sets the HTTP character set of the output.
     *
     * @param   string $encoding
     * @return  System.Web.HttpResponse
     */
    public function setContentEncoding($encoding){
        $this->encoding = $encoding;
        $this->addHeader('Content-type', $this->contentType.';charset='.$this->encoding, true);
        return $this;
    }

    /**
     * Gets the HTTP character set of the output.
     *
     * @return  string
     */
    public function getContentEncoding(){
        return $this->encoding;
    }

    /**
     * Sets the content length of the output.
     *
     * @param   int $length
     * @return  System.Web.HttpResponse
     */
    public function setContentLength($length){
        $this->addHeader('Content-length', $length, true);
        return $this;
    }

    /**
     * Gets the content length of the output.
     *
     * @return  int
     */
    public function getContentLength(){
        return (int)$this->headers->get('Content-length');
    }

    /**
     * Sets the HTTP status code of the output.
     *
     * @param   int $code
     * @return  System.Web.HttpResponse
     */
    public function setStatusCode($code){
        if (isset(self::$statusCodes[$code])){
            $this->statusCode = (int)$code;
            $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
            header($protocol.' '.self::$statusCodes[$code]);
        }
        return $this;
    }

    /**
     * Gets the HTTP status code of the output.
     *
     * @return  int
     */
    public function getStatusCode(){
        return $this->statusCode;
    }

    /**
     * Gets the HTTP header collection.
     *
     * @return  System.Collections.Dictionary
     */
    public function getHeaders(){
        return $this->headers;
    }

    /**
     * Gets a cookie from the cookie collection. Creates a new cookie if the cookie does not exist.
     * Gets the cookie collection if no name is specified.
     *
     * @param   string $name
     * @return  mixed
     */
    public function getCookies($name = null){
        if($name){
            return $this->cookies->get($name);
        }
        return $this->cookies;
    }

    /**
     * Gets the HTTP response output.
     *
     * @return  string
     */
    public function getOutput(){
        return $this->output;
    }

    /**
     * Adds a HTTP header to the header collection. Overrides an existing header
     * if $override is set to true.
     *
     * @param   string $header
     * @param   string $value
     * @param   bool $override = true
     * @return  System.Web.HttpResponse
     */
    public function addHeader($header, $value, $override = true){
        if($override){
            $this->headers->set($header, $value);
        }else{
            if(!$this->headers->hasKey($header)){
                $this->headers->add($header, $value);
            }
        }
        return $this;
    }

    /**
     * Writes a string to the response output.
     *
     * @param   string $output
     * @return  System.Web.HttpResponse
     */
    public function write($output){
        $this->output .= $output;
        return $this;
    }

    /**
     * Writes the string contents of the specified file to the response output.
     *
     * @param   string $file
     * @return  System.Web.HttpResponse
     */
    public function writeFile($file){
        if(is_file($file)){
            $this->output .= file_get_contents($file);
        }else{
            throw new \RuntimeException(sprintf("File '%s' not found.", $file));
        }
        return $this;
    }

    /**
     * Clears the response output.
     *
     * @return  @this
     */
    public function clear(){
        $this->output = '';
        return $this;
    }

    /**
     * Redirects a client to a new URL. Immediately does a redirect if $immediateRedirect is set to true.
     * Setting $immediateRedirect to false will result in the script continuing execution until
     * the application cycle is complete and the response objects flush() method has been called.
     *
     * @param   string $location
     * @param   bool $immediateRedirect
     * @return  void
     */
    public function redirect($location, $immediateRedirect = true){
        if(is_string($location)){
            if($immediateRedirect){
                header('Location: ' . $location);
                exit;
            }
            $this->redirect = $location;
        }
    }

    /**
     * Sends all output and headers to the client then terminates execution.
     *
     * @return  void
     */
    public function endFlush(){
        $this->flush();
        exit;
    }

    /**
     * Sends all output and headers to the client.
     *
     * @return  void
     */
    public function flush(){
        if (!headers_sent()){
            foreach($this->headers as $header=>$value){
                header($header.':'.$value, true);
            }
            foreach($this->cookies as $cookie){
                setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpires(), $cookie->getPath(), $cookie->getDomain(), $cookie->getIsSecure(), $cookie->getIsHttpOnly());
            }
            if($this->redirect){
                header('Location: ' . $this->redirect);
                exit;
            }
        }
        echo $this->output;
        $this->output = '';
    }
}


text:
package org.apache.hadoop.hbase.hbql.client;

import org.apache.hadoop.conf.Configuration;

public interface HConnectionPool {

    String getName();

    Configuration getConfiguration();

    HConnection takeConnection() throws HBqlException;
}


text:
using System.Collections.Generic;
using Opserver.Data.PagerDuty;

namespace Opserver.Views.PagerDuty
{
    public class PagerDutyIncidentModel
    {
        public Incident Incident { get; set; }
        public List<LogEntry> Logs { get; set; }
    }
}


text:
namespace MosesTraining
{
namespace Syntax
{
namespace PostprocessEgretForests
{

int PostprocessEgretForests::Main(int argc, char *argv[])
{
  try {
    // Process command-line options.
    Options options;
    ProcessOptions(argc, argv, options);

    // Open input files.
    boost::scoped_ptr<SplitPointFileParser> splitPointParser;
    std::ifstream splitPointFileStream;
    if (!options.splitPointsFile.empty()) {
      OpenInputFileOrDie(options.splitPointsFile, splitPointFileStream);
      splitPointParser.reset(new SplitPointFileParser(splitPointFileStream));
    }

    ProcessForest(std::cin, std::cout, splitPointParser.get(), options);
  } catch (const MosesTraining::Syntax::Exception &e) {
    Error(e.msg());
  }
  return 0;
}

void PostprocessEgretForests::ProcessForest(
  std::istream &in, std::ostream &out, SplitPointFileParser *splitPointParser,
  const Options &options)
{
  std::size_t sentNum = 0;
  ForestWriter writer(options, out);
  ForestParser end;
  for (ForestParser p(in); p != end; ++p) {
    ++sentNum;
    if (splitPointParser) {
      if (*splitPointParser == SplitPointFileParser()) {
        throw Exception("prematurely reached end of split point file");
      }
      if (!p->forest.vertices.empty()) {
        try {
          MarkSplitPoints((*splitPointParser)->splitPoints, p->forest);
          MarkSplitPoints((*splitPointParser)->splitPoints, p->sentence);
        } catch (const Exception &e) {
          std::ostringstream msg;
          msg << "failed to mark split point for sentence " << sentNum << ": "
              << e.msg();
          throw Exception(msg.str());
        }
      }
      ++(*splitPointParser);
    }
    writer.Write(p->sentence, p->forest, p->sentNum);
  }
}

void PostprocessEgretForests::ProcessOptions(int argc, char *argv[],
    Options &options) const
{
  namespace po = boost::program_options;
  namespace cls = boost::program_options::command_line_style;

  // Construct the 'top' of the usage message: the bit that comes before the
  // options list.
  std::ostringstream usageTop;
  usageTop << "Usage: " << name()
           << " [OPTION]...\n\n"
           << "TODO\n\n"
           << "Options";

  // Construct the 'bottom' of the usage message.
  std::ostringstream usageBottom;
  usageBottom << "TODO";

  // Declare the command line options that are visible to the user.
  po::options_description visible(usageTop.str());
  visible.add_options()
  ("Escape",
   "escape Moses special characters")
  ("MarkSplitPoints",
   po::value(&options.splitPointsFile),
   "read split points from named file and mark (using @) in output")
  ;

  // Declare the command line options that are hidden from the user
  // (these are used as positional options).
  po::options_description hidden("Hidden options");
  hidden.add_options()
  // None
  ;

  // Compose the full set of command-line options.
  po::options_description cmdLineOptions;
  cmdLineOptions.add(visible).add(hidden);

  // Register the positional options.
  po::positional_options_description p;
  // Currently none

  // Process the command-line.
  po::variables_map vm;
  try {
    po::store(po::command_line_parser(argc, argv).style(MosesOptionStyle()).
              options(cmdLineOptions).positional(p).run(), vm);
    po::notify(vm);
  } catch (const std::exception &e) {
    std::ostringstream msg;
    msg << e.what() << "\n\n" << visible << usageBottom.str();
    Error(msg.str());
  }

  if (vm.count("help")) {
    std::cout << visible << usageBottom.str() << std::endl;
    std::exit(0);
  }

  // Process Boolean options.
  if (vm.count("Escape")) {
    options.escape = true;
  }
}

}  // namespace PostprocessEgretForests
}  // namespace Syntax
}  // namespace MosesTraining


text:
package preprocessing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SecondString {

	private static Map<String,List<Integer>> matches;
	private static BufferedWriter numericOutputWriter;
	private static BufferedWriter stringOutputWriter;
	private static BufferedWriter matchWriter;
	private static Lexicon lexicon;
	private static String swFile;
	private static WordProcessor wordProcessor;

	private final static String regexExp = "\\t+";

	public static void main(String[] args){
		String inputFile = args[0];
		matches = new HashMap<String,List<Integer>>();
		String numericOutputFile = args[1];
		String matchFile = args[2];
		String paramsFile = args[3];
		swFile = args[4];
		String lexiconOutFile = args[5];
		String recordOutFile = args[6];

		lexicon = new Lexicon(new File(paramsFile));
		wordProcessor = new WordProcessor(new File(swFile));

		try {
			numericOutputWriter = new BufferedWriter(new FileWriter(new File(
					numericOutputFile)));
			matchWriter = new BufferedWriter(
					new FileWriter(new File(matchFile)));
			stringOutputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(recordOutFile)));

			BufferedReader inputReader = new BufferedReader(new FileReader(
					new File(inputFile)));
			String currLine = "";
			int recordId = 1;
			while (currLine != null) {
				currLine = inputReader.readLine();
				if(currLine == null)
					break;
				String[] parts = currLine.split(regexExp);
				String clusterId = parts[1].toLowerCase().trim();
				String concatedImportentparts ="";
				if(parts.length <= 3){//source, cluster id, and item
					concatedImportentparts = parts[2];
				}
				else{
					StringBuilder sb = new StringBuilder();
					for (int i=2 ; i < parts.length ; i++) {
						sb.append(parts[i]).append(" ");
					}
					concatedImportentparts = sb.toString();
				}
				String cleanString = getCleanString(concatedImportentparts.trim());
				StringBuilder numericStringBuilder = new StringBuilder();
				for(int i=2 ; i < parts.length ; i++){
					numericStringBuilder.append(getNGramIdString(recordId, parts[i],i-1)).append(" ");
				}
				String numericString = numericStringBuilder.toString().trim();
				numericOutputWriter.write(numericString.trim());
				numericOutputWriter.newLine();
				stringOutputWriter.write(cleanString.trim());
				stringOutputWriter.newLine();

				List<Integer> cluster = null;
				if(matches.containsKey(clusterId)){
					cluster = matches.get(clusterId);
				}
				else{
					cluster = new ArrayList<Integer>();
				}
				cluster.add(recordId);
				matches.put(clusterId, cluster);
				recordId++;
			}
			 //write the matches
	        int numOfpairs = 0;
	        for (List<Integer> cluster : matches.values()) {
	        	StringBuilder sb = new StringBuilder();
	        	Collections.sort(cluster);
				if(cluster.size() < 2) continue;
				numOfpairs += cluster.size()*(cluster.size()-1)*0.5;
				for (Integer integer : cluster) {
					sb.append(integer).append(" ");
				}
				matchWriter.write(sb.toString());
				matchWriter.newLine();
			}
	        numericOutputWriter.close();
	        stringOutputWriter.close();
	        matchWriter.close();
	        lexicon.exportToPropFile(lexiconOutFile);
	        System.out.println("total number of pairs in match file: " + numOfpairs);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static String getCleanString(String value){
		List<String> swFreeTerms = wordProcessor.removeStopwordsAndSpecialChars(value);
		return WordProcessor.concatListMembers(swFreeTerms);
	}

	private static String getNGramIdString(int recordId, String value, int propertyId){
		List<Integer> NGramsIds = new ArrayList<Integer>();
		String[] values = value.split("\\s+");
		for(int i=0; i < values.length ;i++){
			List<String> valueNgrams = getNGrams(values[i]);
			NGramsIds.addAll(getNGramIds(valueNgrams,recordId,propertyId)); //generic id
		}
		return WordProcessor.concatListMembers(NGramsIds);
	}

	private static List<String> getNGrams(String value){
		return wordProcessor.processValue(value);
	}
	private static List<Integer> getNGramIds(List<String> nGrams, int recordId, int attributeId){
		List<Integer> retVal = new ArrayList<Integer>(nGrams.size());
		for (String nGram : nGrams) {
			retVal.add(lexicon.addWord(attributeId, recordId, nGram));
		}
		return retVal;
	}
}


text:
export default GeoTIFFSource;
export type SourceInfo = {
    /**
     * URL for the source GeoTIFF.
     */
    url: string;
    /**
     * List of any overview URLs.
     */
    overviews?: string[];
    /**
     * The minimum source data value.  Rendered values are scaled from 0 to 1 based on
     * the configured min and max.
     */
    min?: number;
    /**
     * The maximum source data value.  Rendered values are scaled from 0 to 1 based on
     * the configured min and max.
     */
    max?: number;
    /**
     * Values to discard. When provided, an additional band (alpha) will be added
     * to the data.
     */
    nodata?: number;
    /**
     * Band numbers to be read from (where the first band is `1`). If not provided, all bands will
     * be read. For example, if a GeoTIFF has blue (1), green (2), red (3), and near-infrared (4) bands, and you only need the
     * near-infrared band, configure `bands: [4]`.
     */
    bands?: number[];
};
export type GeoKeys = {
    /**
     * Model type.
     */
    GTModelTypeGeoKey: number;
    /**
     * Raster type.
     */
    GTRasterTypeGeoKey: number;
    /**
     * Angular units.
     */
    GeogAngularUnitsGeoKey: number;
    /**
     * Inverse flattening.
     */
    GeogInvFlatteningGeoKey: number;
    /**
     * Semi-major axis.
     */
    GeogSemiMajorAxisGeoKey: number;
    /**
     * Geographic coordinate system code.
     */
    GeographicTypeGeoKey: number;
    /**
     * Projected linear unit code.
     */
    ProjLinearUnitsGeoKey: number;
    /**
     * Projected coordinate system code.
     */
    ProjectedCSTypeGeoKey: number;
};
export type GeoTIFFImage = {
    /**
     * The file directory.
     */
    fileDirectory: any;
    /**
     * The parsed geo-keys.
     */
    geoKeys: GeoKeys;
    /**
     * Uses little endian byte order.
     */
    littleEndian: boolean;
    /**
     * The tile cache.
     */
    tiles: any;
    /**
     * The image is tiled.
     */
    isTiled: boolean;
    /**
     * Get the image bounding box.
     */
    getBoundingBox: () => number[];
    /**
     * Get the image origin.
     */
    getOrigin: () => number[];
    /**
     * Get the image resolution.
     */
    getResolution: (arg0: GeoTIFFImage) => number[];
};
export type Options = {
    /**
     * List of information about GeoTIFF sources.
     * Multiple sources can be combined when their resolution sets are equal after applying a scale.
     * The list of sources defines a mapping between input bands as they are read from each GeoTIFF and
     * the output bands that are provided by data tiles. To control which bands to read from each GeoTIFF,
     * use the {@link import("./GeoTIFF.js").SourceInfo bands} property. If, for example, you specify two
     * sources, one with 3 bands and {@link import("./GeoTIFF.js").SourceInfo nodata} configured, and
     * another with 1 band, the resulting data tiles will have 5 bands: 3 from the first source, 1 alpha
     * band from the first source, and 1 band from the second source.
     */
    sources: SourceInfo[];
    /**
     * By default, bands from the sources are read as-is. When
     * reading GeoTIFFs with the purpose of displaying them as RGB images, setting this to `true` will
     * convert other color spaces (YCbCr, CMYK) to RGB.
     */
    convertToRGB?: boolean;
    /**
     * Whether the layer is opaque.
     */
    opaque?: boolean;
    /**
     * Duration of the opacity transition for rendering.
     * To disable the opacity transition, pass `transition: 0`.
     */
    transition?: number;
};
/**
 * @typedef {Object} Options
 * @property {Array<SourceInfo>} sources List of information about GeoTIFF sources.
 * Multiple sources can be combined when their resolution sets are equal after applying a scale.
 * The list of sources defines a mapping between input bands as they are read from each GeoTIFF and
 * the output bands that are provided by data tiles. To control which bands to read from each GeoTIFF,
 * use the {@link import("./GeoTIFF.js").SourceInfo bands} property. If, for example, you specify two
 * sources, one with 3 bands and {@link import("./GeoTIFF.js").SourceInfo nodata} configured, and
 * another with 1 band, the resulting data tiles will have 5 bands: 3 from the first source, 1 alpha
 * band from the first source, and 1 band from the second source.
 * @property {boolean} [convertToRGB = false] By default, bands from the sources are read as-is. When
 * reading GeoTIFFs with the purpose of displaying them as RGB images, setting this to `true` will
 * convert other color spaces (YCbCr, CMYK) to RGB.
 * @property {boolean} [opaque=false] Whether the layer is opaque.
 * @property {number} [transition=250] Duration of the opacity transition for rendering.
 * To disable the opacity transition, pass `transition: 0`.
 */
/**
 * @classdesc
 * A source for working with GeoTIFF data.
 * @api
 */
declare class GeoTIFFSource extends DataTile {
    /**
     * @param {Options} options Data tile options.
     */
    constructor(options: Options);
    /**
     * @type {Array<SourceInfo>}
     * @private
     */
    private sourceInfo_;
    /**
     * @type {Array<Array<import("geotiff/src/geotiffimage.js").GeoTIFFImage>>}
     * @private
     */
    private sourceImagery_;
    /**
     * @type {Array<number>}
     * @private
     */
    private resolutionFactors_;
    /**
     * @type {Array<number>}
     * @private
     */
    private samplesPerPixel_;
    /**
     * @type {Array<Array<number>>}
     * @private
     */
    private nodataValues_;
    /**
     * @type {boolean}
     * @private
     */
    private addAlpha_;
    /**
     * @type {Error}
     * @private
     */
    private error_;
    /**
     * @type {'readRasters' | 'readRGB'}
     */
    readMethod_: 'readRasters' | 'readRGB';
    /**
     * @return {Error} A source loading error. When the source state is `error`, use this function
     * to get more information about the error. To debug a faulty configuration, you may want to use
     * a listener like
     * ```js
     * geotiffSource.on('change', () => {
     *   if (geotiffSource.getState() === 'error') {
     *     console.error(geotiffSource.getError());
     *   }
     * });
     * ```
     */
    getError(): Error;
    /**
     * Configure the tile grid based on images within the source GeoTIFFs.  Each GeoTIFF
     * must have the same internal tiled structure.
     * @param {Array<Array<import("geotiff/src/geotiffimage.js").GeoTIFFImage>>} sources Each source is a list of images
     * from a single GeoTIFF.
     * @private
     */
    private configure_;
    loadTile_(z: any, x: any, y: any): Promise<Uint8Array>;
}
import DataTile from "./DataTile.js";
//# sourceMappingURL=GeoTIFF.d.ts.map


text:
'use strict';

var scrollToPosition = function(offset) {
    if (App.Helper.offsetTop != undefined) {
        $('html, body').stop().animate({
            scrollTop: offset
        }, 300);
    }
};

exports.scrollToPosition = scrollToPosition;


text:
/**
 * @author v.lugovsky
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('HomeCash.pages.tables', [])
    .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('tables', {
          url: '/tables',
          template : '<ui-view></ui-view>',
          abstract: true,
          controller: 'TablesPageCtrl',
          title: 'Tables',
          sidebarMeta: {
            icon: 'ion-grid',
            order: 300,
          },
        }).state('tables.basic', {
          url: '/basic',
          templateUrl: 'app/pages/tables/basic/tables.html',
          title: 'Basic Tables',
          sidebarMeta: {
            order: 0,
          },
        }).state('tables.smart', {
          url: '/smart',
          templateUrl: 'app/pages/tables/smart/tables.html',
          title: 'Smart Tables',
          sidebarMeta: {
            order: 100,
          },
        });
    $urlRouterProvider.when('/tables','/tables/basic');
  }

})();


text:
module JSONAPI
  UNAUTHORIZED = '401'
  module Exceptions
    class Unauthorized < Error

      def initialize(name, error_object_overrides = {})
        @name = name
        super(error_object_overrides)
      end

      def name
        @name
      end

      def name=(new_name)
        @name = new_name
      end

      def errors
        [create_error_object(code: JSONAPI::UNAUTHORIZED,
                             status: :unauthorized,
                             title: I18n.translate('jsonapi-resources.exceptions.unauthorized.title',
                                                   default: 'Unauthorized'),
                             detail: I18n.translate('jsonapi-resources.exceptions.unauthorized.detail',
                                                    default: "#{self.name}" ))]
      end

    end
  end
end


text:
package org.apache.spark.deploy.history

import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.zip.ZipOutputStream

import scala.xml.Node

import org.apache.spark.SparkException
import org.apache.spark.ui.SparkUI

private[spark] case class ApplicationAttemptInfo(
    attemptId: Option[String],
    startTime: Long,
    endTime: Long,
    lastUpdated: Long,
    sparkUser: String,
    completed: Boolean = false,
    appSparkVersion: String)

private[spark] case class ApplicationHistoryInfo(
    id: String,
    name: String,
    attempts: List[ApplicationAttemptInfo]) {

  /**
   * Has this application completed?
   * @return true if the most recent attempt has completed
   */
  def completed: Boolean = {
    attempts.nonEmpty && attempts.head.completed
  }
}

/**
 * A loaded UI for a Spark application.
 *
 * Loaded UIs are valid once created, and can be invalidated once the history provider detects
 * changes in the underlying app data (e.g. an updated event log). Invalidating a UI does not
 * unload it; it just signals the [[ApplicationCache]] that the UI should not be used to serve
 * new requests.
 *
 * Reloading of the UI with new data requires collaboration between the cache and the provider;
 * the provider invalidates the UI when it detects updated information, and the cache invalidates
 * the cache entry when it detects the UI has been invalidated. That will trigger a callback
 * on the provider to finally clean up any UI state. The cache should hold read locks when
 * using the UI, and the provider should grab the UI's write lock before making destructive
 * operations.
 *
 * Note that all this means that an invalidated UI will still stay in-memory, and any resources it
 * references will remain open, until the cache either sees that it's invalidated, or evicts it to
 * make room for another UI.
 *
 * @param ui Spark UI
 */
private[history] case class LoadedAppUI(ui: SparkUI) {

  val lock = new ReentrantReadWriteLock()

  @volatile private var _valid = true

  def valid: Boolean = _valid

  def invalidate(): Unit = {
    lock.writeLock().lock()
    try {
      _valid = false
    } finally {
      lock.writeLock().unlock()
    }
  }

}

private[history] abstract class ApplicationHistoryProvider {

  /**
   * Returns the count of application event logs that the provider is currently still processing.
   * History Server UI can use this to indicate to a user that the application listing on the UI
   * can be expected to list additional known applications once the processing of these
   * application event logs completes.
   *
   * A History Provider that does not have a notion of count of event logs that may be pending
   * for processing need not override this method.
   *
   * @return Count of application event logs that are currently under process
   */
  def getEventLogsUnderProcess(): Int = {
    0
  }

  /**
   * Returns the time the history provider last updated the application history information
   *
   * @return 0 if this is undefined or unsupported, otherwise the last updated time in millis
   */
  def getLastUpdatedTime(): Long = {
    0
  }

  /**
   * Returns a list of applications available for the history server to show.
   *
   * @return List of all know applications.
   */
  def getListing(): Iterator[ApplicationHistoryInfo]

  /**
   * Returns the Spark UI for a specific application.
   *
   * @param appId The application ID.
   * @param attemptId The application attempt ID (or None if there is no attempt ID).
   * @return a [[LoadedAppUI]] instance containing the application's UI and any state information
   *         for update probes, or `None` if the application/attempt is not found.
   */
  def getAppUI(appId: String, attemptId: Option[String]): Option[LoadedAppUI]

  /**
   * Called when the server is shutting down.
   */
  def stop(): Unit = { }

  /**
   * Returns configuration data to be shown in the History Server home page.
   *
   * @return A map with the configuration data. Data is show in the order returned by the map.
   */
  def getConfig(): Map[String, String] = Map()

  /**
   * Writes out the event logs to the output stream provided. The logs will be compressed into a
   * single zip file and written out.
   * @throws SparkException if the logs for the app id cannot be found.
   */
  @throws(classOf[SparkException])
  def writeEventLogs(appId: String, attemptId: Option[String], zipStream: ZipOutputStream): Unit

  /**
   * @return the [[ApplicationHistoryInfo]] for the appId if it exists.
   */
  def getApplicationInfo(appId: String): Option[ApplicationHistoryInfo]

  /**
   * @return html text to display when the application list is empty
   */
  def getEmptyListingHtml(): Seq[Node] = Seq.empty

  /**
   * Called when an application UI is unloaded from the history server.
   */
  def onUIDetached(appId: String, attemptId: Option[String], ui: SparkUI): Unit = { }

}


text:
package com.facebook.buck.parser;

import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.parser.api.BuildFileManifest;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.parser.exceptions.BuildTargetException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import java.nio.file.Path;

public class PerBuildState implements AutoCloseable {

  private final CellManager cellManager;
  private final BuildFileRawNodeParsePipeline buildFileRawNodeParsePipeline;
  private final ParsePipeline<TargetNode<?>> targetNodeParsePipeline;

  PerBuildState(
      CellManager cellManager,
      BuildFileRawNodeParsePipeline buildFileRawNodeParsePipeline,
      ParsePipeline<TargetNode<?>> targetNodeParsePipeline) {
    this.cellManager = cellManager;
    this.buildFileRawNodeParsePipeline = buildFileRawNodeParsePipeline;
    this.targetNodeParsePipeline = targetNodeParsePipeline;
  }

  TargetNode<?> getTargetNode(BuildTarget target) throws BuildFileParseException {
    Cell owningCell = cellManager.getCell(target);

    return targetNodeParsePipeline.getNode(owningCell, target);
  }

  ListenableFuture<TargetNode<?>> getTargetNodeJob(BuildTarget target) throws BuildTargetException {
    Cell owningCell = cellManager.getCell(target);

    return targetNodeParsePipeline.getNodeJob(owningCell, target);
  }

  ImmutableList<TargetNode<?>> getAllTargetNodes(Cell cell, Path buildFile)
      throws BuildFileParseException {
    Preconditions.checkState(buildFile.startsWith(cell.getRoot()));

    return targetNodeParsePipeline.getAllNodes(cell, buildFile);
  }

  ListenableFuture<ImmutableList<TargetNode<?>>> getAllTargetNodesJob(Cell cell, Path buildFile)
      throws BuildTargetException {
    Preconditions.checkState(buildFile.startsWith(cell.getRoot()));

    return targetNodeParsePipeline.getAllNodesJob(cell, buildFile);
  }

  BuildFileManifest getBuildFileManifest(Cell cell, Path buildFile) throws BuildFileParseException {
    Preconditions.checkState(buildFile.startsWith(cell.getRoot()));
    return buildFileRawNodeParsePipeline.getAllNodes(cell, buildFile);
  }

  ListenableFuture<BuildFileManifest> getBuildFileManifestJob(Cell cell, Path buildFile)
      throws BuildFileParseException {
    Preconditions.checkState(buildFile.startsWith(cell.getRoot()));
    return buildFileRawNodeParsePipeline.getAllNodesJob(cell, buildFile);
  }

  @Override
  public void close() {
    targetNodeParsePipeline.close();
    buildFileRawNodeParsePipeline.close();
    cellManager.close();
  }
}


text:
@interface HomeTabViewController : RootViewController

@property (nonatomic,strong) NSString *tableViewUrlStr;

@end


text:
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';

import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';

import { BaseListComponent} from '../common/BaseListComponent'

import { AppUserDetailComponent } from './AppUserDetailComponent';

import { AppUserService } from './AppUserService';
import {AppUser} from '../common/AppEntities.ts';

let template = require('./AppUserListComponent.html');

@Component({
  selector: 'appUser-list',
  template: template,
  providers:[AppUserService],
  directives: [AppUserDetailComponent, ROUTER_DIRECTIVES]
})
export class AppUserListComponent extends BaseListComponent<AppUser> implements OnInit {

  @Input()
  appUsers:AppUser[];

  selectedAppUser:AppUser;
  errorMessage:string;

  constructor(
  //  private _router: Router,
  protected _appUserService:AppUserService) { super(_appUserService); }

  setRecords( appUser:AppUser[]){this.appUsers = appUser;}
  getRecords():AppUser[]{return this.appUsers;}

  ngOnInit() {
  	super.getBaseEntitys()
  }

//  gotoDetail() {this._router.navigate(['AppUserDetail', { id: this.selectedAppUser.id }]);}
}


text:
namespace search
{
class Delimiters
{
public:
  bool operator()(strings::UniChar c) const;
};

class DelimitersWithExceptions
{
public:
  explicit DelimitersWithExceptions(std::vector<strings::UniChar> const & exceptions);

  bool operator()(strings::UniChar c) const;

private:
  std::vector<strings::UniChar> m_exceptions;
  Delimiters m_delimiters;
};
}  // namespace search


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.hexpresso.soulevspy">
    android:installLocation="auto" >

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

    <supports-screens
        android:xlargeScreens="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true"
        android:anyDensity="true"/>

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.SettingsActivity"
            android:label="@string/title_activity_settings"
            android:parentActivityName=".activity.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".activity.MainActivity" />
        </activity>
    </application>

</manifest>


text:
<!DOCTYPE html>

	<title>Link to a Stylesheet Quiz</title>
	<link href="css/styles.css" rel=stylesheet>

My Portfolio

				This specific design features a 3D floating mountain above a weathered, rugged font to insinuate a winter outdoor theme. This logo would be a perfect fit for an outdoor product company or ski resort.

				This specific design features a beach-themed fading sunset with palm trees. The fading vertical bars in the sun resemble warmth as it fades away into the sunset.


text:
using System;

namespace OnLineShop.Data.Models.Contracts
{
    public interface IDbModel
    {
         int Id { get; }

        bool IsDeleted { get; set; }
    }
}


text:
package net.wastl.webmail.plugins;

import java.util.Locale;

import net.wastl.webmail.exceptions.WebMailException;
import net.wastl.webmail.server.HTTPSession;
import net.wastl.webmail.server.Plugin;
import net.wastl.webmail.server.Storage;
import net.wastl.webmail.server.URLHandler;
import net.wastl.webmail.server.WebMailServer;
import net.wastl.webmail.server.WebMailSession;
import net.wastl.webmail.server.http.HTTPRequestHeader;
import net.wastl.webmail.ui.html.HTMLDocument;
import net.wastl.webmail.ui.xml.XHTMLDocument;

/**
 * This URLHandler handles error messages.
 *
 * @author Sebastian Schaffert
 */
public class ErrorHandler implements Plugin, URLHandler {
    public static final String VERSION="1.00";
    public static final String URL="/error";

    WebMailServer parent;

    Storage store;

    public ErrorHandler() {
    }

    public void register(WebMailServer parent) {
        parent.getURLHandler().registerHandler(URL,this);
        this.parent=parent;
        store=parent.getStorage();
    }

    public String getName() {
        return "ErrorHandler";
    }

    public String getDescription() {
        return "Handle error messages";
    }

    public String getVersion() {
        return VERSION;
    }

    public String getURL() {
        return URL;
    }

    public HTMLDocument handleURL(String suburl, HTTPSession session, HTTPRequestHeader header) throws WebMailException {
        String theme=WebMailServer.getDefaultTheme();
        Locale locale=WebMailServer.getDefaultLocale();
        if(session instanceof WebMailSession) {
            WebMailSession sess=(WebMailSession)session;
            theme=sess.getUser().getTheme();
            locale=sess.getUser().getPreferredLocale();
        }
        return new XHTMLDocument(session.getModel(),store.getStylesheet("error.xsl",locale,theme));
    }

    public String provides() {
        return "about";
    }

    public String requires() {
        return "";
    }
}


text:
layout: single
title: "Luray 2021 Olympic Duathlon Race Report"
date: 2021-08-23T17:41:43-04:00
modified:
description: "My first race in almost two years, and I've learned that I have to start over." 	# For Twitter, not the Title
categories:
    - "Race Report"
tags:
    - Duathlon
    - Racine Multisports
header:
    image: /assets/images/2021/08/23/Luray-Header.jpg            # Twitter (use 'overlay_image')
    overlay_image: /assets/images/2021/08/23/Luray-Header.jpg    # Article header at 2048x768
    overlay_filter: 0.15
    teaser: /assets/images/2021/08/23/Luray-Header-Twitter.jpg   # Shrink image to 575x216
    caption: "Photo credit: [**Justin Rummel**](https://www.justinrummel.com)"
---

Can you believe your eyes?!  Yes a Race Report!  First one in almost two years, as the last time I wrote anything was in 2019 for the TIN 14.06 Sprint!  I wish this race report was full of accolades and show how wonderful I did maintaining my health over such a long period of time, but my performance was the result of what my body can do at this time.  100%... I did the best that I could do on race day and it was terrible.

Life Background (where I fell apart)
---

February 2020 I was looking forward to a new race season, unsure of which I would participate in, but knew I needed to start working in pushing those WATTS on the bike.  I was doing a on/off thresholds at FTP trainer session in the basement when my chain stuck to the rear hanger... which then **PROPELLED ITSELF INTO MY CARBON FIBER FRAME**.  I can never ride my Tri bike outside again.  NEVER! It is no longer safe with the carbon structure compromised... the day my baby died.

Then COVID.

Motivation was at an all time low as I couldn't swim because the pools had closed, couldn't race without having to buy a new bike, and started working on the basement to get it finished (since I was living there all the time for work).  I was also having some health issues so I decided to get that taken care of at the begging of this year, which gave me more reason to not exercise.  I restarted workouts around mid-to-late April with all endurance lost, all my strength lost, and gained about 20 lbs.

{% include toc icon="gears" title="Race Review ToC" %}

Race Breakdown
---

Now you know WHY I did so terrible, lets talk about the actual race.  This is the first time I participated in an event at Luray, but I knew from other people that Luray's route was hilly.  This is a Duathlon which was setup for a 1.7 mi trail run, 41 km bike, then a 10 km run.

### Run 1

The trail run was great! It started with a quick climb on rock gravel then around the lake and into the trails. The trails were very technical where you needed to stop and make sure you had correct foot placement or else suffer falling over or worse a sprain/broken ankle.  Some of the tree roots were eroding away making it more difficult as you navigated the narrow single track.  We ran around the entire lake, which finally reconnected with the triathletes at the swim exit.  A fun 5-star, fast, and technical trail route that I finished _somewhat_ quickly and is the only thing I did well that day.

- [Training Peaks Swim Data](http://tpks.ws/SR2HVHAQYS22HTI4FEYTRMETSU)

### Bike

Remember I no longer have a street safe triathlon bike (I still use it in the basement on the trainer for indoor workouts) so for the race I had to bring out my old road bike (Red Barron) which was recently upgraded from a 10-speed to an 11-speed with a large 32 tooth gear in the back for climbing.  I thought my ideal race pace would be to hold 175 W throughout the bike course which would be 85% of my FTP.  Unfortunately I have NOT done a single ride grater than one hour and I was about to complete a 40 km ride which I thought would take about 90 minutes.

My estimate was close, I was actually 180 W for the entire ride and it took me 1:34:31, yet I fell apart pushing that ride.  Both legs began to cramp.  My arch in my left foot cramped (no idea why) which required me to unclip and shake out.  For the last climb I had to drop to that 32 tooth cassette but it was terrible as I was going so slow I thought I would tip over, but I couldn't stand up and try to climb my way up the hill as my leg cramps wouldn't allow the balance.

I was a mess, the bike segment killed me.

- [Training Peaks Bike Data](http://tpks.ws/KMADLUNHXQIU5TI4FEYTRMETSU)

### Run 2

Happy to get off the bike, I started the run but again my legs were dead.  I realized I wasn't going to catch up to get third place... so I resorted to "Walk UP; Run DOWN" run plan.  The hills were long and moral was low.  I wasn't going to give up as I'm only going 10km... but my body can't keep up with what my mind thinks is possible.  The rolling hills punished me, one after the other.

- [Training Peaks Run Data](http://tpks.ws/6SYA47LJOMSIVTI4FEYTRMETSU)

Post Race Thoughts
---

The race was not a friendly race for someone restarting their exercise routines.  In my head I know what I am capable of and this is NOT representative of something to be proud of.  But, it is the first race of 2021... no idea if there will be another this year... but I do enjoy the adventure so I look forward to the next event!

Race Results
---

#### Rankings

- Overall: Placed 21st out of 31 (bottom third).
- Gender: Placed 18th out of 23 (bottom fifth).
- Male 45-49: Placed 4th out of 5

#### Race Photos

#### Splits

| EVENT Sprint       | 1.7mi Run    | T1   | 41km Bike      | T2   | 10km Run | Total       |
|:-------------------|:------------:|:----:|:--------------:|:----:|:--------:|------------:|
| Goal Times         | 15:00        | 1:15 | 1:30:00        | 1:15 | 55:00    | 2:42:30     |
|=====
| Actual Times       | 13:51        | 1:03 | 1:35:02        | 1:03 | 1:13:36  | 3:04:32     |

Footnotes
---

[event_results]: https://racinemultisports.com/results-luray-international-2021/#/race/F60Ims/5/results/ALL