text:
using base::Time;

const int kVerticalPadding = 10;
const int kHorizontalPadding = 10;

////////////////////////////////////////////////////////////////////////////////
// SecurityTabView
class SecurityTabView : public views::View {
 public:
  SecurityTabView(Profile* profile,
                  const GURL& url,
                  const NavigationEntry::SSLStatus& ssl,
                  NavigationEntry::PageType page_type,
                  bool show_history);
  virtual ~SecurityTabView();

  virtual void Layout();

  // Add a section.
  virtual void AddSection(const std::wstring& title,
                          bool state,
                          const std::wstring& head_line,
                          const std::wstring& description);

 private:
  // A section contains an image that shows a status (good or bad), a title,
  // an optional head-line (in bold) and a description.
  class Section : public views::View {
   public:
    Section(const std::wstring& title,
            bool state,
            const std::wstring& head_line,
            const std::wstring& description);
    virtual ~Section();

    virtual int GetHeightForWidth(int w);
    virtual void Layout();

   private:
    // The text placed on top of the section (on the left of the separator bar).
    std::wstring title_;

    // Whether to show the good/bad icon.
    bool state_;

    // The first line of the description, show in bold.
    std::wstring head_line_;

    // The description, displayed below the head line.
    std::wstring description_;

    static SkBitmap* good_state_icon_;
    static SkBitmap* bad_state_icon_;

    views::Label* title_label_;
    views::Separator* separator_;
    views::ImageView* status_image_;
    views::Label* head_line_label_;
    views::Label* description_label_;

    DISALLOW_EVIL_CONSTRUCTORS(Section);
  };

  // Callback from history service with number of visits to url.
  void OnGotVisitCountToHost(HistoryService::Handle handle,
                             bool found_visits,
                             int count,
                             Time first_visit);

  std::vector<Section*> sections_;

  // Used to request number of visits.
  CancelableRequestConsumer request_consumer_;

  DISALLOW_EVIL_CONSTRUCTORS(SecurityTabView);
};

// static
SkBitmap* SecurityTabView::Section::good_state_icon_ = NULL;
SkBitmap* SecurityTabView::Section::bad_state_icon_ = NULL;

// Layout constants.
static const int kHGapToBorder = 6;
static const int kVGapToBorder = 6;
static const int kHGapTitleToSeparator = 2;
static const int kVGapTitleToImage = 6;
static const int kHGapImageToDescription = 6;
static const int kVGapHeadLineToDescription = 2;
static const int kVGapBetweenSections = 20;
static const int kHExtraSeparatorPadding = 2;

SecurityTabView::Section::Section(const std::wstring& title, bool state,
                                  const std::wstring& head_line,
                                  const std::wstring& description)
    : title_(title),
      state_(state),
      head_line_(head_line),
      description_(description) {
  if (!good_state_icon_) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    good_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_GOOD);
    bad_state_icon_ = rb.GetBitmapNamed(IDR_PAGEINFO_BAD);
  }
  title_label_ = new views::Label(title);
  title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(title_label_);

  separator_ = new views::Separator();
  AddChildView(separator_);

  status_image_ = new views::ImageView();
  status_image_->SetImage(state ? good_state_icon_ : bad_state_icon_);
  AddChildView(status_image_);

  head_line_label_ = new views::Label(head_line);
  head_line_label_->SetFont(
      head_line_label_->GetFont().DeriveFont(0, gfx::Font::BOLD));
  head_line_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(head_line_label_);

  description_label_ = new views::Label(description);
  description_label_->SetMultiLine(true);
  description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(description_label_);
}

SecurityTabView::Section::~Section() {
}

int SecurityTabView::Section::GetHeightForWidth(int width) {
  // The height of the section depends on the height of the description label
  // (multi-line).  We need to know the width of the description label to know
  // its height.
  int height = 0;
  gfx::Size size = title_label_->GetPreferredSize();
  height += size.height() + kVGapTitleToImage;

  gfx::Size image_size = status_image_->GetPreferredSize();

  int text_height = 0;
  if (!head_line_label_->GetText().empty()) {
    size = head_line_label_->GetPreferredSize();
    text_height = size.height() + kVGapHeadLineToDescription;
  }

  int description_width =
      width - image_size.width() - kHGapImageToDescription - kHGapToBorder;
  text_height += description_label_->GetHeightForWidth(description_width);

  height += std::max(image_size.height(), text_height);

  return height;
}

void SecurityTabView::Section::Layout() {
  // First, layout the title and separator.
  int x = 0;
  int y = 0;
  gfx::Size size = title_label_->GetPreferredSize();
  title_label_->SetBounds(x, y, size.width(), size.height());
  x += size.width() + kHGapTitleToSeparator;
  separator_->SetBounds(x + kHExtraSeparatorPadding, y,
                        width() - x - 2 * kHExtraSeparatorPadding,
                        size.height());

  // Then the image, head-line and description.
  x = kHGapToBorder;
  y += title_label_->height() + kVGapTitleToImage;
  size = status_image_->GetPreferredSize();
  status_image_->SetBounds(x, y, size.width(), size.height());
  x += size.width() + kHGapImageToDescription;
  int w = width() - x;
  if (!head_line_label_->GetText().empty()) {
    size = head_line_label_->GetPreferredSize();
    head_line_label_->SetBounds(x, y, w > 0 ? w : 0, size.height());
    y += size.height() + kVGapHeadLineToDescription;
  } else {
    head_line_label_->SetBounds(x, y, 0, 0);
  }
  if (w > 0) {
    description_label_->SetBounds(x, y, w,
                                  description_label_->GetHeightForWidth(w));
  } else {
    description_label_->SetBounds(x, y, 0, 0);
  }
}

SecurityTabView::SecurityTabView(Profile* profile,
                                 const GURL& url,
                                 const NavigationEntry::SSLStatus& ssl,
                                 NavigationEntry::PageType page_type,
                                 bool show_history) {
  bool identity_ok = true;
  bool connection_ok = true;
  std::wstring identity_title;
  std::wstring identity_msg;
  std::wstring connection_msg;
  scoped_refptr<net::X509Certificate> cert;

  // Identity section.
  std::wstring subject_name(UTF8ToWide(url.host()));
  bool empty_subject_name = false;
  if (subject_name.empty()) {
    subject_name.assign(
        l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
    empty_subject_name = true;
  }
  if (page_type == NavigationEntry::NORMAL_PAGE && ssl.cert_id() &&
      CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&
      !net::IsCertStatusError(ssl.cert_status())) {
    // OK HTTPS page.
    if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {
      DCHECK(!cert->subject().organization_names.empty());
      identity_title =
          l10n_util::GetStringF(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
              UTF8ToWide(cert->subject().organization_names[0]),
              UTF8ToWide(url.host()));
      // An EV Cert is required to have a city (localityName) and country but
      // state is "if any".
      DCHECK(!cert->subject().locality_name.empty());
      DCHECK(!cert->subject().country_name.empty());
      std::wstring locality;
      if (!cert->subject().state_or_province_name.empty()) {
        locality = l10n_util::GetStringF(
            IDS_PAGEINFO_ADDRESS,
            UTF8ToWide(cert->subject().locality_name),
            UTF8ToWide(cert->subject().state_or_province_name),
            UTF8ToWide(cert->subject().country_name));
      } else {
        locality = l10n_util::GetStringF(
            IDS_PAGEINFO_PARTIAL_ADDRESS,
            UTF8ToWide(cert->subject().locality_name),
            UTF8ToWide(cert->subject().country_name));
      }
      DCHECK(!cert->subject().organization_names.empty());
      identity_msg.assign(l10n_util::GetStringF(
          IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
          UTF8ToWide(cert->subject().organization_names[0]),
          locality,
          UTF8ToWide(PageInfoWindow::GetIssuerName(cert->issuer()))));
    } else {
      // Non EV OK HTTPS.
      if (empty_subject_name)
        identity_title.clear();  // Don't display any title.
      else
        identity_title.assign(subject_name);
      std::wstring issuer_name(UTF8ToWide(
          PageInfoWindow::GetIssuerName(cert->issuer())));
      if (issuer_name.empty()) {
        issuer_name.assign(
            l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
      } else {
        identity_msg.assign(
            l10n_util::GetStringF(IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY,
                                  issuer_name));
      }
    }
  } else {
    // Bad HTTPS.
    identity_msg.assign(
        l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
    identity_ok = false;
  }

  // Connection section.
  // We consider anything less than 80 bits encryption to be weak encryption.
  // TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
  // weakly encrypted connections.
  if (ssl.security_bits() <= 0) {
    connection_ok = false;
    connection_msg.assign(
        l10n_util::GetStringF(
            IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
            subject_name));
  } else if (ssl.security_bits() < 80) {
    connection_ok = false;
    connection_msg.assign(
        l10n_util::GetStringF(
            IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
            subject_name));
  } else {
    connection_msg.assign(
        l10n_util::GetStringF(
            IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
            subject_name,
            IntToWString(ssl.security_bits())));
    if (ssl.has_mixed_content()) {
      connection_ok = false;
      connection_msg.assign(
          l10n_util::GetStringF(
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
              connection_msg,
              l10n_util::GetString(
                  IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_MIXED_CONTENT_WARNING)));
    } else if (ssl.has_unsafe_content()) {
      connection_ok = false;
      connection_msg.assign(
          l10n_util::GetStringF(
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
              connection_msg,
              l10n_util::GetString(
                  IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_BAD_HTTPS_WARNING)));
    }
  }

  // Let's add the different sections.
  AddSection(l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),
             identity_ok, identity_title, identity_msg);
  AddSection(l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),
             connection_ok, std::wstring(), connection_msg);

  // Request the number of visits.
  HistoryService* history = profile->GetHistoryService(
      Profile::EXPLICIT_ACCESS);
  if (show_history && history) {
    history->GetVisitCountToHost(
        url,
        &request_consumer_,
        NewCallback(this, &SecurityTabView::OnGotVisitCountToHost));
  }
}

SecurityTabView::~SecurityTabView() {
}

void SecurityTabView::AddSection(const std::wstring& title,
                                     bool state,
                                     const std::wstring& head_line,
                                     const std::wstring& description) {
  Section* section = new Section(title, state, head_line, description);
  sections_.push_back(section);
  AddChildView(section);
}

void SecurityTabView::Layout() {
  int tab_width = width() - 2 * kHGapToBorder;
  int x = kHGapToBorder;
  int y = kVGapToBorder;
  for (std::vector<Section*>::const_iterator iter = sections_.begin();
       iter != sections_.end(); ++iter) {
    Section* section = *iter;
    int h = section->GetHeightForWidth(tab_width);
    section->SetBounds(x, y, tab_width, h);
    section->Layout();
    y += h + kVGapBetweenSections;
  }
}

void SecurityTabView::OnGotVisitCountToHost(HistoryService::Handle handle,
                                            bool found_visits,
                                            int count,
                                            Time first_visit) {
  if (!found_visits) {
    // This indicates an error, such as the page wasn't http/https; do nothing.
    return;
  }

  bool visited_before_today = false;
  if (count) {
    Time today = Time::Now().LocalMidnight();
    Time first_visit_midnight = first_visit.LocalMidnight();
    visited_before_today = (first_visit_midnight < today);
  }

  if (!visited_before_today) {
    AddSection(
        l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        false, std::wstring(),
        l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY));
  } else {
    AddSection(
        l10n_util::GetString(IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        true, std::wstring(),
        l10n_util::GetStringF(IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
                              base::TimeFormatShortDate(first_visit)));
  }
  Layout();
  SchedulePaint();
}

////////////////////////////////////////////////////////////////////////////////
// PageInfoContentView
class PageInfoContentView : public views::View {
 public:
  PageInfoContentView() : cert_viewer_button_(NULL) {}

  void set_cert_viewer_button(views::NativeButton* cert_viewer_button) {
    cert_viewer_button_ = cert_viewer_button;
  }

  // views::View overrides:
  virtual gfx::Size GetPreferredSize() {
    return gfx::Size(views::Window::GetLocalizedContentsSize(
        IDS_PAGEINFO_DIALOG_WIDTH_CHARS,
        IDS_PAGEINFO_DIALOG_HEIGHT_LINES));
  }

  virtual void Layout() {
    if (cert_viewer_button_) {
      gfx::Size ps = cert_viewer_button_->GetPreferredSize();

      gfx::Rect parent_bounds = GetParent()->GetLocalBounds(false);
      int y_buttons =
          parent_bounds.bottom() - ps.height() - kButtonVEdgeMargin;
      cert_viewer_button_->SetBounds(kPanelHorizMargin, y_buttons, ps.width(),
                                     ps.height());
    }
    View::Layout();
  }

 private:
  views::NativeButton* cert_viewer_button_;

  DISALLOW_EVIL_CONSTRUCTORS(PageInfoContentView);
};

////////////////////////////////////////////////////////////////////////////////
// PageInfoWindowWin

int PageInfoWindowWin::opened_window_count_ = 0;

PageInfoWindow* PageInfoWindow::Factory() {
  return new PageInfoWindowWin();
}

PageInfoWindowWin::PageInfoWindowWin()
    : PageInfoWindow() {
}

PageInfoWindowWin::~PageInfoWindowWin() {
  DCHECK(opened_window_count_ > 0);
  opened_window_count_--;
}

void PageInfoWindowWin::Init(Profile* profile,
                             const GURL& url,
                             const NavigationEntry::SSLStatus& ssl,
                             NavigationEntry::PageType page_type,
                             bool show_history,
                             gfx::NativeView parent) {
  cert_id_ = ssl.cert_id();

  cert_info_button_ = new views::NativeButton(
      this, l10n_util::GetString(IDS_PAGEINFO_CERT_INFO_BUTTON));

  contents_ = new PageInfoContentView();
  DWORD sys_color = ::GetSysColor(COLOR_3DFACE);
  SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),
                                GetBValue(sys_color));
  contents_->set_background(views::Background::CreateSolidBackground(color));

  views::GridLayout* layout = new views::GridLayout(contents_);
  contents_->SetLayoutManager(layout);
  views::ColumnSet* columns = layout->AddColumnSet(0);
  columns->AddPaddingColumn(0, kHorizontalPadding);
  columns->AddColumn(views::GridLayout::FILL,  // Horizontal resize.
                     views::GridLayout::FILL,  // Vertical resize.
                     1,  // Resize weight.
                     views::GridLayout::USE_PREF,  // Size type.
                     0,  // Ignored for USE_PREF.
                     0);  // Minimum size.
  columns->AddColumn(views::GridLayout::FILL,  // Horizontal resize.
                     views::GridLayout::FILL,  // Vertical resize.
                     1,  // Resize weight.
                     views::GridLayout::USE_PREF,  // Size type.
                     0,  // Ignored for USE_PREF.
                     0);  // Minimum size.
  columns->AddPaddingColumn(0, kHorizontalPadding);

  layout->AddPaddingRow(0, kHorizontalPadding);
  layout->StartRow(1, 0);
  layout->AddView(CreateSecurityTabView(profile, url, ssl, page_type,
                                        show_history), 2, 1);

  layout->AddPaddingRow(0, kHorizontalPadding);

  if (opened_window_count_ > 0) {
    // There already is a PageInfo window opened.  Let's shift the location of
    // the new PageInfo window so they don't overlap entirely.
    // Window::Init will position the window from the stored location.
    gfx::Rect bounds;
    bool maximized = false;
    if (GetSavedWindowBounds(&bounds) && GetSavedMaximizedState(&maximized)) {
      CalculateWindowBounds(&bounds);
      SaveWindowPlacement(bounds, maximized);
    }
  }

  views::Window::CreateChromeWindow(parent, gfx::Rect(), this);
  // TODO(beng): (Cleanup) - cert viewer button should use GetExtraView.

  if (cert_id_) {
    scoped_refptr<net::X509Certificate> cert;
    CertStore::GetSharedInstance()->RetrieveCert(cert_id_, &cert);
    // When running with Gears, we have no os certificate, so there is no cert
    // to show. Don't bother showing the cert info button in that case.
    if (cert.get() && cert->os_cert_handle()) {
      contents_->GetParent()->AddChildView(cert_info_button_);
      contents_->set_cert_viewer_button(cert_info_button_);
      contents_->Layout();
    }
  }
}

views::View* PageInfoWindowWin::CreateGeneralTabView() {
  return new views::View();
}

views::View* PageInfoWindowWin::CreateSecurityTabView(
    Profile* profile,
    const GURL& url,
    const NavigationEntry::SSLStatus& ssl,
    NavigationEntry::PageType page_type,
    bool show_history) {
  return new SecurityTabView(profile, url, ssl, page_type, show_history);
}

void PageInfoWindowWin::Show() {
  window()->Show();
  opened_window_count_++;
}

int PageInfoWindowWin::GetDialogButtons() const {
  return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}

std::wstring PageInfoWindowWin::GetWindowTitle() const {
  return l10n_util::GetString(IDS_PAGEINFO_WINDOW_TITLE);
}

std::wstring PageInfoWindowWin::GetWindowName() const {
  return prefs::kPageInfoWindowPlacement;
}

views::View* PageInfoWindowWin::GetContentsView() {
  return contents_;
}

void PageInfoWindowWin::ButtonPressed(views::Button* sender) {
  if (sender == cert_info_button_) {
    DCHECK(cert_id_ != 0);
    ShowCertDialog(cert_id_);
  } else {
    NOTREACHED();
  }
}

void PageInfoWindowWin::CalculateWindowBounds(gfx::Rect* bounds) {
  const int kDefaultOffset = 15;

  gfx::Rect monitor_bounds(win_util::GetMonitorBoundsForRect(*bounds));
  if (monitor_bounds.IsEmpty())
    return;

  // If necessary, move the window so it is visible on the screen.
  gfx::Rect adjusted_bounds = bounds->AdjustToFit(monitor_bounds);
  if (adjusted_bounds != *bounds) {
    // The bounds have moved, we are done.
    *bounds = adjusted_bounds;
    return;
  }

  // Move the window from its specified position, trying to keep it entirely
  // visible.
  int x_offset, y_offset;
  if (bounds->right() + kDefaultOffset >= monitor_bounds.right() &&
      abs(monitor_bounds.x() - bounds->x()) >= kDefaultOffset) {
    x_offset = -kDefaultOffset;
  } else {
    x_offset = kDefaultOffset;
  }

  if (bounds->bottom() + kDefaultOffset >= monitor_bounds.bottom() &&
      abs(monitor_bounds.y() - bounds->y()) >= kDefaultOffset) {
    y_offset = -kDefaultOffset;
  } else {
    y_offset = kDefaultOffset;
  }

  bounds->Offset(x_offset, y_offset);
}

void PageInfoWindowWin::ShowCertDialog(int cert_id) {
  scoped_refptr<net::X509Certificate> cert;
  CertStore::GetSharedInstance()->RetrieveCert(cert_id, &cert);
  if (!cert.get()) {
    // The certificate was not found. Could be that the renderer crashed before
    // we displayed the page info.
    return;
  }

  CRYPTUI_VIEWCERTIFICATE_STRUCT view_info = { 0 };
  view_info.dwSize = sizeof(view_info);
  // We set our parent to the tab window. This makes the cert dialog created
  // in CryptUIDlgViewCertificate modal to the browser.
  view_info.hwndParent = window()->GetNativeWindow();
  view_info.dwFlags = CRYPTUI_DISABLE_EDITPROPERTIES |
                      CRYPTUI_DISABLE_ADDTOSTORE;
  view_info.pCertContext = cert->os_cert_handle();
  // Search the cert store that 'cert' is in when building the cert chain.
  HCERTSTORE cert_store = view_info.pCertContext->hCertStore;
  view_info.cStores = 1;
  view_info.rghStores = &cert_store;
  BOOL properties_changed;

  // This next call blocks but keeps processing windows messages, making it
  // modal to the browser window.
  BOOL rv = ::CryptUIDlgViewCertificate(&view_info, &properties_changed);
}


text:
// Code generated by protoc-gen-go.
// source: vtgateservice.proto
// DO NOT EDIT!

/*
Package vtgateservice is a generated protocol buffer package.

It is generated from these files:
	vtgateservice.proto

It has these top-level messages:
*/
package vtgateservice

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import vtgate "github.com/youtube/vitess/go/vt/proto/vtgate"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// Client API for Vitess service

type VitessClient interface {
	// Execute tries to route the query to the right shard.
	// It depends on the query and bind variables to provide enough
	// information in conjonction with the vindexes to route the query.
	// API group: v3 API (alpha)
	Execute(ctx context.Context, in *vtgate.ExecuteRequest, opts ...grpc.CallOption) (*vtgate.ExecuteResponse, error)
	// ExecuteShards executes the query on the specified shards.
	// API group: Custom Sharding
	ExecuteShards(ctx context.Context, in *vtgate.ExecuteShardsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteShardsResponse, error)
	// ExecuteKeyspaceIds executes the query based on the specified keyspace ids.
	// API group: Range-based Sharding
	ExecuteKeyspaceIds(ctx context.Context, in *vtgate.ExecuteKeyspaceIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteKeyspaceIdsResponse, error)
	// ExecuteKeyRanges executes the query based on the specified key ranges.
	// API group: Range-based Sharding
	ExecuteKeyRanges(ctx context.Context, in *vtgate.ExecuteKeyRangesRequest, opts ...grpc.CallOption) (*vtgate.ExecuteKeyRangesResponse, error)
	// ExecuteEntityIds executes the query based on the specified external id to keyspace id map.
	// API group: Range-based Sharding
	ExecuteEntityIds(ctx context.Context, in *vtgate.ExecuteEntityIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteEntityIdsResponse, error)
	// ExecuteBatchShards executes the list of queries on the specified shards.
	// API group: Custom Sharding
	ExecuteBatchShards(ctx context.Context, in *vtgate.ExecuteBatchShardsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteBatchShardsResponse, error)
	// ExecuteBatchKeyspaceIds executes the list of queries based on the specified keyspace ids.
	// API group: Range-based Sharding
	ExecuteBatchKeyspaceIds(ctx context.Context, in *vtgate.ExecuteBatchKeyspaceIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteBatchKeyspaceIdsResponse, error)
	// StreamExecute executes a streaming query based on shards.
	// It depends on the query and bind variables to provide enough
	// information in conjonction with the vindexes to route the query.
	// Use this method if the query returns a large number of rows.
	// API group: v3 API (alpha)
	StreamExecute(ctx context.Context, in *vtgate.StreamExecuteRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteClient, error)
	// StreamExecuteShards executes a streaming query based on shards.
	// Use this method if the query returns a large number of rows.
	// API group: Custom Sharding
	StreamExecuteShards(ctx context.Context, in *vtgate.StreamExecuteShardsRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteShardsClient, error)
	// StreamExecuteKeyspaceIds executes a streaming query based on keyspace ids.
	// Use this method if the query returns a large number of rows.
	// API group: Range-based Sharding
	StreamExecuteKeyspaceIds(ctx context.Context, in *vtgate.StreamExecuteKeyspaceIdsRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteKeyspaceIdsClient, error)
	// StreamExecuteKeyRanges executes a streaming query based on key ranges.
	// Use this method if the query returns a large number of rows.
	// API group: Range-based Sharding
	StreamExecuteKeyRanges(ctx context.Context, in *vtgate.StreamExecuteKeyRangesRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteKeyRangesClient, error)
	// Begin a transaction.
	// API group: Transactions
	Begin(ctx context.Context, in *vtgate.BeginRequest, opts ...grpc.CallOption) (*vtgate.BeginResponse, error)
	// Commit a transaction.
	// API group: Transactions
	Commit(ctx context.Context, in *vtgate.CommitRequest, opts ...grpc.CallOption) (*vtgate.CommitResponse, error)
	// Rollback a transaction.
	// API group: Transactions
	Rollback(ctx context.Context, in *vtgate.RollbackRequest, opts ...grpc.CallOption) (*vtgate.RollbackResponse, error)
	// Split a query into non-overlapping sub queries
	// API group: Map Reduce
	SplitQuery(ctx context.Context, in *vtgate.SplitQueryRequest, opts ...grpc.CallOption) (*vtgate.SplitQueryResponse, error)
	// GetSrvKeyspace returns a SrvKeyspace object (as seen by this vtgate).
	// This method is provided as a convenient way for clients to take a
	// look at the sharding configuration for a Keyspace. Looking at the
	// sharding information should not be used for routing queries (as the
	// information may change, use the Execute calls for that).
	// It is convenient for monitoring applications for instance, or if
	// using custom sharding.
	// API group: Topology
	GetSrvKeyspace(ctx context.Context, in *vtgate.GetSrvKeyspaceRequest, opts ...grpc.CallOption) (*vtgate.GetSrvKeyspaceResponse, error)
}

type vitessClient struct {
	cc *grpc.ClientConn
}

func NewVitessClient(cc *grpc.ClientConn) VitessClient {
	return &vitessClient{cc}
}

func (c *vitessClient) Execute(ctx context.Context, in *vtgate.ExecuteRequest, opts ...grpc.CallOption) (*vtgate.ExecuteResponse, error) {
	out := new(vtgate.ExecuteResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/Execute", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteShards(ctx context.Context, in *vtgate.ExecuteShardsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteShardsResponse, error) {
	out := new(vtgate.ExecuteShardsResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteShards", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteKeyspaceIds(ctx context.Context, in *vtgate.ExecuteKeyspaceIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteKeyspaceIdsResponse, error) {
	out := new(vtgate.ExecuteKeyspaceIdsResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteKeyspaceIds", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteKeyRanges(ctx context.Context, in *vtgate.ExecuteKeyRangesRequest, opts ...grpc.CallOption) (*vtgate.ExecuteKeyRangesResponse, error) {
	out := new(vtgate.ExecuteKeyRangesResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteKeyRanges", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteEntityIds(ctx context.Context, in *vtgate.ExecuteEntityIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteEntityIdsResponse, error) {
	out := new(vtgate.ExecuteEntityIdsResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteEntityIds", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteBatchShards(ctx context.Context, in *vtgate.ExecuteBatchShardsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteBatchShardsResponse, error) {
	out := new(vtgate.ExecuteBatchShardsResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteBatchShards", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) ExecuteBatchKeyspaceIds(ctx context.Context, in *vtgate.ExecuteBatchKeyspaceIdsRequest, opts ...grpc.CallOption) (*vtgate.ExecuteBatchKeyspaceIdsResponse, error) {
	out := new(vtgate.ExecuteBatchKeyspaceIdsResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/ExecuteBatchKeyspaceIds", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) StreamExecute(ctx context.Context, in *vtgate.StreamExecuteRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Vitess_serviceDesc.Streams[0], c.cc, "/vtgateservice.Vitess/StreamExecute", opts...)
	if err != nil {
		return nil, err
	}
	x := &vitessStreamExecuteClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type Vitess_StreamExecuteClient interface {
	Recv() (*vtgate.StreamExecuteResponse, error)
	grpc.ClientStream
}

type vitessStreamExecuteClient struct {
	grpc.ClientStream
}

func (x *vitessStreamExecuteClient) Recv() (*vtgate.StreamExecuteResponse, error) {
	m := new(vtgate.StreamExecuteResponse)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *vitessClient) StreamExecuteShards(ctx context.Context, in *vtgate.StreamExecuteShardsRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteShardsClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Vitess_serviceDesc.Streams[1], c.cc, "/vtgateservice.Vitess/StreamExecuteShards", opts...)
	if err != nil {
		return nil, err
	}
	x := &vitessStreamExecuteShardsClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type Vitess_StreamExecuteShardsClient interface {
	Recv() (*vtgate.StreamExecuteShardsResponse, error)
	grpc.ClientStream
}

type vitessStreamExecuteShardsClient struct {
	grpc.ClientStream
}

func (x *vitessStreamExecuteShardsClient) Recv() (*vtgate.StreamExecuteShardsResponse, error) {
	m := new(vtgate.StreamExecuteShardsResponse)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *vitessClient) StreamExecuteKeyspaceIds(ctx context.Context, in *vtgate.StreamExecuteKeyspaceIdsRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteKeyspaceIdsClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Vitess_serviceDesc.Streams[2], c.cc, "/vtgateservice.Vitess/StreamExecuteKeyspaceIds", opts...)
	if err != nil {
		return nil, err
	}
	x := &vitessStreamExecuteKeyspaceIdsClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type Vitess_StreamExecuteKeyspaceIdsClient interface {
	Recv() (*vtgate.StreamExecuteKeyspaceIdsResponse, error)
	grpc.ClientStream
}

type vitessStreamExecuteKeyspaceIdsClient struct {
	grpc.ClientStream
}

func (x *vitessStreamExecuteKeyspaceIdsClient) Recv() (*vtgate.StreamExecuteKeyspaceIdsResponse, error) {
	m := new(vtgate.StreamExecuteKeyspaceIdsResponse)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *vitessClient) StreamExecuteKeyRanges(ctx context.Context, in *vtgate.StreamExecuteKeyRangesRequest, opts ...grpc.CallOption) (Vitess_StreamExecuteKeyRangesClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_Vitess_serviceDesc.Streams[3], c.cc, "/vtgateservice.Vitess/StreamExecuteKeyRanges", opts...)
	if err != nil {
		return nil, err
	}
	x := &vitessStreamExecuteKeyRangesClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type Vitess_StreamExecuteKeyRangesClient interface {
	Recv() (*vtgate.StreamExecuteKeyRangesResponse, error)
	grpc.ClientStream
}

type vitessStreamExecuteKeyRangesClient struct {
	grpc.ClientStream
}

func (x *vitessStreamExecuteKeyRangesClient) Recv() (*vtgate.StreamExecuteKeyRangesResponse, error) {
	m := new(vtgate.StreamExecuteKeyRangesResponse)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

func (c *vitessClient) Begin(ctx context.Context, in *vtgate.BeginRequest, opts ...grpc.CallOption) (*vtgate.BeginResponse, error) {
	out := new(vtgate.BeginResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/Begin", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) Commit(ctx context.Context, in *vtgate.CommitRequest, opts ...grpc.CallOption) (*vtgate.CommitResponse, error) {
	out := new(vtgate.CommitResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/Commit", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) Rollback(ctx context.Context, in *vtgate.RollbackRequest, opts ...grpc.CallOption) (*vtgate.RollbackResponse, error) {
	out := new(vtgate.RollbackResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/Rollback", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) SplitQuery(ctx context.Context, in *vtgate.SplitQueryRequest, opts ...grpc.CallOption) (*vtgate.SplitQueryResponse, error) {
	out := new(vtgate.SplitQueryResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/SplitQuery", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *vitessClient) GetSrvKeyspace(ctx context.Context, in *vtgate.GetSrvKeyspaceRequest, opts ...grpc.CallOption) (*vtgate.GetSrvKeyspaceResponse, error) {
	out := new(vtgate.GetSrvKeyspaceResponse)
	err := grpc.Invoke(ctx, "/vtgateservice.Vitess/GetSrvKeyspace", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for Vitess service

type VitessServer interface {
	// Execute tries to route the query to the right shard.
	// It depends on the query and bind variables to provide enough
	// information in conjonction with the vindexes to route the query.
	// API group: v3 API (alpha)
	Execute(context.Context, *vtgate.ExecuteRequest) (*vtgate.ExecuteResponse, error)
	// ExecuteShards executes the query on the specified shards.
	// API group: Custom Sharding
	ExecuteShards(context.Context, *vtgate.ExecuteShardsRequest) (*vtgate.ExecuteShardsResponse, error)
	// ExecuteKeyspaceIds executes the query based on the specified keyspace ids.
	// API group: Range-based Sharding
	ExecuteKeyspaceIds(context.Context, *vtgate.ExecuteKeyspaceIdsRequest) (*vtgate.ExecuteKeyspaceIdsResponse, error)
	// ExecuteKeyRanges executes the query based on the specified key ranges.
	// API group: Range-based Sharding
	ExecuteKeyRanges(context.Context, *vtgate.ExecuteKeyRangesRequest) (*vtgate.ExecuteKeyRangesResponse, error)
	// ExecuteEntityIds executes the query based on the specified external id to keyspace id map.
	// API group: Range-based Sharding
	ExecuteEntityIds(context.Context, *vtgate.ExecuteEntityIdsRequest) (*vtgate.ExecuteEntityIdsResponse, error)
	// ExecuteBatchShards executes the list of queries on the specified shards.
	// API group: Custom Sharding
	ExecuteBatchShards(context.Context, *vtgate.ExecuteBatchShardsRequest) (*vtgate.ExecuteBatchShardsResponse, error)
	// ExecuteBatchKeyspaceIds executes the list of queries based on the specified keyspace ids.
	// API group: Range-based Sharding
	ExecuteBatchKeyspaceIds(context.Context, *vtgate.ExecuteBatchKeyspaceIdsRequest) (*vtgate.ExecuteBatchKeyspaceIdsResponse, error)
	// StreamExecute executes a streaming query based on shards.
	// It depends on the query and bind variables to provide enough
	// information in conjonction with the vindexes to route the query.
	// Use this method if the query returns a large number of rows.
	// API group: v3 API (alpha)
	StreamExecute(*vtgate.StreamExecuteRequest, Vitess_StreamExecuteServer) error
	// StreamExecuteShards executes a streaming query based on shards.
	// Use this method if the query returns a large number of rows.
	// API group: Custom Sharding
	StreamExecuteShards(*vtgate.StreamExecuteShardsRequest, Vitess_StreamExecuteShardsServer) error
	// StreamExecuteKeyspaceIds executes a streaming query based on keyspace ids.
	// Use this method if the query returns a large number of rows.
	// API group: Range-based Sharding
	StreamExecuteKeyspaceIds(*vtgate.StreamExecuteKeyspaceIdsRequest, Vitess_StreamExecuteKeyspaceIdsServer) error
	// StreamExecuteKeyRanges executes a streaming query based on key ranges.
	// Use this method if the query returns a large number of rows.
	// API group: Range-based Sharding
	StreamExecuteKeyRanges(*vtgate.StreamExecuteKeyRangesRequest, Vitess_StreamExecuteKeyRangesServer) error
	// Begin a transaction.
	// API group: Transactions
	Begin(context.Context, *vtgate.BeginRequest) (*vtgate.BeginResponse, error)
	// Commit a transaction.
	// API group: Transactions
	Commit(context.Context, *vtgate.CommitRequest) (*vtgate.CommitResponse, error)
	// Rollback a transaction.
	// API group: Transactions
	Rollback(context.Context, *vtgate.RollbackRequest) (*vtgate.RollbackResponse, error)
	// Split a query into non-overlapping sub queries
	// API group: Map Reduce
	SplitQuery(context.Context, *vtgate.SplitQueryRequest) (*vtgate.SplitQueryResponse, error)
	// GetSrvKeyspace returns a SrvKeyspace object (as seen by this vtgate).
	// This method is provided as a convenient way for clients to take a
	// look at the sharding configuration for a Keyspace. Looking at the
	// sharding information should not be used for routing queries (as the
	// information may change, use the Execute calls for that).
	// It is convenient for monitoring applications for instance, or if
	// using custom sharding.
	// API group: Topology
	GetSrvKeyspace(context.Context, *vtgate.GetSrvKeyspaceRequest) (*vtgate.GetSrvKeyspaceResponse, error)
}

func RegisterVitessServer(s *grpc.Server, srv VitessServer) {
	s.RegisterService(&_Vitess_serviceDesc, srv)
}

func _Vitess_Execute_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).Execute(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteShards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteShardsRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteShards(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteKeyspaceIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteKeyspaceIdsRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteKeyspaceIds(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteKeyRanges_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteKeyRangesRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteKeyRanges(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteEntityIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteEntityIdsRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteEntityIds(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteBatchShards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteBatchShardsRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteBatchShards(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_ExecuteBatchKeyspaceIds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.ExecuteBatchKeyspaceIdsRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).ExecuteBatchKeyspaceIds(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_StreamExecute_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(vtgate.StreamExecuteRequest)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(VitessServer).StreamExecute(m, &vitessStreamExecuteServer{stream})
}

type Vitess_StreamExecuteServer interface {
	Send(*vtgate.StreamExecuteResponse) error
	grpc.ServerStream
}

type vitessStreamExecuteServer struct {
	grpc.ServerStream
}

func (x *vitessStreamExecuteServer) Send(m *vtgate.StreamExecuteResponse) error {
	return x.ServerStream.SendMsg(m)
}

func _Vitess_StreamExecuteShards_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(vtgate.StreamExecuteShardsRequest)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(VitessServer).StreamExecuteShards(m, &vitessStreamExecuteShardsServer{stream})
}

type Vitess_StreamExecuteShardsServer interface {
	Send(*vtgate.StreamExecuteShardsResponse) error
	grpc.ServerStream
}

type vitessStreamExecuteShardsServer struct {
	grpc.ServerStream
}

func (x *vitessStreamExecuteShardsServer) Send(m *vtgate.StreamExecuteShardsResponse) error {
	return x.ServerStream.SendMsg(m)
}

func _Vitess_StreamExecuteKeyspaceIds_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(vtgate.StreamExecuteKeyspaceIdsRequest)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(VitessServer).StreamExecuteKeyspaceIds(m, &vitessStreamExecuteKeyspaceIdsServer{stream})
}

type Vitess_StreamExecuteKeyspaceIdsServer interface {
	Send(*vtgate.StreamExecuteKeyspaceIdsResponse) error
	grpc.ServerStream
}

type vitessStreamExecuteKeyspaceIdsServer struct {
	grpc.ServerStream
}

func (x *vitessStreamExecuteKeyspaceIdsServer) Send(m *vtgate.StreamExecuteKeyspaceIdsResponse) error {
	return x.ServerStream.SendMsg(m)
}

func _Vitess_StreamExecuteKeyRanges_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(vtgate.StreamExecuteKeyRangesRequest)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(VitessServer).StreamExecuteKeyRanges(m, &vitessStreamExecuteKeyRangesServer{stream})
}

type Vitess_StreamExecuteKeyRangesServer interface {
	Send(*vtgate.StreamExecuteKeyRangesResponse) error
	grpc.ServerStream
}

type vitessStreamExecuteKeyRangesServer struct {
	grpc.ServerStream
}

func (x *vitessStreamExecuteKeyRangesServer) Send(m *vtgate.StreamExecuteKeyRangesResponse) error {
	return x.ServerStream.SendMsg(m)
}

func _Vitess_Begin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.BeginRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).Begin(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_Commit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.CommitRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).Commit(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_Rollback_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.RollbackRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).Rollback(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_SplitQuery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.SplitQueryRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).SplitQuery(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func _Vitess_GetSrvKeyspace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
	in := new(vtgate.GetSrvKeyspaceRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	out, err := srv.(VitessServer).GetSrvKeyspace(ctx, in)
	if err != nil {
		return nil, err
	}
	return out, nil
}

var _Vitess_serviceDesc = grpc.ServiceDesc{
	ServiceName: "vtgateservice.Vitess",
	HandlerType: (*VitessServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Execute",
			Handler:    _Vitess_Execute_Handler,
		},
		{
			MethodName: "ExecuteShards",
			Handler:    _Vitess_ExecuteShards_Handler,
		},
		{
			MethodName: "ExecuteKeyspaceIds",
			Handler:    _Vitess_ExecuteKeyspaceIds_Handler,
		},
		{
			MethodName: "ExecuteKeyRanges",
			Handler:    _Vitess_ExecuteKeyRanges_Handler,
		},
		{
			MethodName: "ExecuteEntityIds",
			Handler:    _Vitess_ExecuteEntityIds_Handler,
		},
		{
			MethodName: "ExecuteBatchShards",
			Handler:    _Vitess_ExecuteBatchShards_Handler,
		},
		{
			MethodName: "ExecuteBatchKeyspaceIds",
			Handler:    _Vitess_ExecuteBatchKeyspaceIds_Handler,
		},
		{
			MethodName: "Begin",
			Handler:    _Vitess_Begin_Handler,
		},
		{
			MethodName: "Commit",
			Handler:    _Vitess_Commit_Handler,
		},
		{
			MethodName: "Rollback",
			Handler:    _Vitess_Rollback_Handler,
		},
		{
			MethodName: "SplitQuery",
			Handler:    _Vitess_SplitQuery_Handler,
		},
		{
			MethodName: "GetSrvKeyspace",
			Handler:    _Vitess_GetSrvKeyspace_Handler,
		},
	},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "StreamExecute",
			Handler:       _Vitess_StreamExecute_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "StreamExecuteShards",
			Handler:       _Vitess_StreamExecuteShards_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "StreamExecuteKeyspaceIds",
			Handler:       _Vitess_StreamExecuteKeyspaceIds_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "StreamExecuteKeyRanges",
			Handler:       _Vitess_StreamExecuteKeyRanges_Handler,
			ServerStreams: true,
		},
	},
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.theborakompanioni.gn.fetch;

import de.jetwick.snacktory.HtmlFetcher;
import de.jetwick.snacktory.JResult;

/**
 * Created by void on 21.09.15.
 */
public class SnacktoryContentFetcherImpl implements ContentFetcher {
    private static int FETCH_TIMEOUT_IN_MILLISECONDS = 15_000;

    private HtmlFetcher fetcher;
    private HtmlCleaner cleaner;
    private LanguageDetector languageDetector;

    public SnacktoryContentFetcherImpl(HtmlFetcher fetcher, HtmlCleaner cleaner, LanguageDetector languageDetector) {
        this.fetcher = fetcher;
        this.cleaner = cleaner;
        this.languageDetector = languageDetector;
    }

    @Override
    public Content fetch(ContentFetchContext context) throws Exception {

        final JResult jResult = fetcher.fetchAndExtract(context.getUrl(), FETCH_TIMEOUT_IN_MILLISECONDS, true);

        return createContent(jResult);
    }

    private Content createContent(JResult jResult) {
        SimpleContent newContent = new SimpleContent();
        newContent.setUrl(clean(jResult.getUrl()));
        newContent.setTitle(clean(jResult.getTitle()));
        newContent.setDescription(clean(jResult.getDescription()));
        newContent.setText(clean(jResult.getText()));
        newContent.setDateString(clean(jResult.getDate()));
        newContent.setVideoUrl(clean(jResult.getVideoUrl()));
        newContent.setKeywords(jResult.getKeywords());

        languageDetector.detect(newContent.getText())
                .ifPresent(newContent::setLanguage);

        return newContent;
    }

    private String clean(String html) {
        return cleaner.clean(html);
    }
}


text:
package io.webfolder.cormorant.internal.jaxrs;

import static java.lang.Long.parseLong;
import static java.lang.Long.toHexString;
import static java.lang.String.valueOf;
import static java.nio.ByteBuffer.allocateDirect;
import static java.nio.ByteBuffer.wrap;
import static java.nio.channels.Channels.newChannel;
import static java.nio.channels.Channels.newInputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
import static java.util.concurrent.ThreadLocalRandom.current;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.regex.Pattern.compile;
import static javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT;
import static javax.ws.rs.core.Response.Status.NOT_MODIFIED;
import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.PARTIAL_CONTENT;
import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED;
import static javax.ws.rs.core.Response.Status.REQUESTED_RANGE_NOT_SATISFIABLE;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response.Status;

import io.webfolder.cormorant.api.Util;
import io.webfolder.cormorant.api.model.Segment;
import io.webfolder.cormorant.api.service.ObjectService;

class ResourceHandler<T> implements Util {

    private static final Pattern RANGE_PATTERN        = compile("^bytes=[0-9]*-[0-9]*(,[0-9]*-[0-9]*)*$");
    private static final long    ONE_SECOND_IN_MILLIS = SECONDS.toMillis(1);
    private static final int     BUFFER_SIZE          = 16 * 1024;
    private static final byte[]  NEW_LINE             = "\r\n".getBytes(UTF_8);

    private final ObjectService<T> objectService;

    private final Resource<T> resource;

    public ResourceHandler(
            final ObjectService<T> objectService,
            final Resource<T>      response) {
        this.objectService = objectService;
        this.resource      = response;
    }

    public Status handle(
                    final HttpServletRequest  request,
                    final HttpServletResponse response) throws IOException, SQLException {

        if (preconditionFailed(request, resource)) {
            return PRECONDITION_FAILED;
        }

        response.setHeader("ETag", resource.getETag());
        response.setDateHeader("Last-Modified", resource.getLastModified());

        if (notModified(request, resource)) {
            return NOT_MODIFIED;
        }

        final List<Range> ranges = getRanges(request, resource);

        if (ranges == null) {
            response.setHeader("Content-Range", "bytes */" + resource.getLength());
            return REQUESTED_RANGE_NOT_SATISFIABLE;
        }

        final Status status;

        if ( ! ranges.isEmpty() ) {
            status = PARTIAL_CONTENT;
        } else {
            status = OK;
            final String boundary = toHexString(current().nextLong());
            ranges.add(new Range(0, resource.getLength() - 1, boundary)); // Full content.
        }

        final String contentType = setContentHeaders(request, response, resource, ranges);

        write(response, resource, ranges, contentType);

        return status;
    }

    protected boolean preconditionFailed(
                            final HttpServletRequest request,
                            final Resource<T>        resource) {
        final String match      = request.getHeader("If-Match");
        final long   unmodified = request.getDateHeader("If-Unmodified-Since");
        return ( match != null ) ? ! matches(match, resource.getETag())
                : ( unmodified != -1 && isModified(unmodified, resource.getLastModified()) );
    }

    protected boolean notModified(
                            final HttpServletRequest request,
                            final Resource<T>        resource) {
        final String noMatch  = request.getHeader("If-None-Match");
        final long   modified = request.getDateHeader("If-Modified-Since");
        return ( noMatch != null ) ? matches(noMatch, resource.getETag())
                : (modified != -1 && ! isModified(modified, resource.getLastModified()));
    }

    protected List<Range> getRanges(
                            final HttpServletRequest request,
                            final Resource<T>        resource) {
        final List<Range> ranges      = new ArrayList<>(1);
        final String      rangeHeader = request.getHeader("Range");

        if (rangeHeader == null) {
            return ranges;
        } else if ( ! RANGE_PATTERN.matcher(rangeHeader).matches() ) {
            return null; // Syntax error.
        }

        final String ifRange = request.getHeader("If-Range");

        if ( ifRange != null && ! ifRange.equals(resource.getETag()) ) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range");

                if ( ifRangeTime != -1 && isModified(ifRangeTime, resource.getLastModified()) ) {
                    return ranges;
                }
            } catch (IllegalArgumentException e) {
                // If-Range header is invalid. Return full content then.
                return ranges;
            }
        }

        final String boundary = toHexString(current().nextLong());

        for (final String rangeHeaderPart : rangeHeader.split("=")[1].split(",")) {
            final Range range = parseRange(rangeHeaderPart.trim(), resource.getLength(), boundary);

            if (range == null) {
                return null; // Logic error.
            }

            ranges.add(range);
        }

        return ranges;
    }

    protected Range parseRange(
                        final String range,
                        final long   length,
                        final String boundary) {
        long start = toLong(range, 0, range.indexOf('-'));
        long end   = toLong(range, range.indexOf('-') + 1, range.length());

        if (start == -1) {
            start = length - end;
            end = length - 1;
        } else if (end == -1 || end > length - 1) {
            end = length - 1;
        }

        if (start > end) {
            return null; // Logic error.
        }

        return new Range(start, end, boundary);
    }

    protected String setContentHeaders(
                            final HttpServletRequest  request,
                            final HttpServletResponse response,
                            final Resource<T>         resource,
                            final List<Range>         ranges) throws IOException, SQLException {

        if ( resource.getContentDisposition() != null ) {
            response.setHeader("Content-Disposition", resource.getContentDisposition());
        }

        response.setHeader("Accept-Ranges", "bytes");

        if (ranges.size() == 1) {
            final Range range = ranges.get(0);
            response.setContentType(resource.getContentType());
            if ( ! resource.isDynamicLargeObject() ) {
                response.setContentLengthLong(range.getLength());
            } else {
                final long size = objectService.getDyanmicObjectSize(resource.getContainer(), resource.getObject());
                response.setContentLengthLong(size);
            }

            final boolean all = range.getStart() == 0 && (range.getEnd() + 1) == resource.getLength();

            if ( ! all ) {
                response.setStatus(SC_PARTIAL_CONTENT);
                response.setHeader("Content-Range", "bytes " + range.getStart() + '-' + range.getEnd() + '/' + resource.getLength());
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + ranges.get(0).getBoundary());
        }

        response.setHeader("X-Trans-Id", generateTxId());
        response.setHeader("X-Timestamp", valueOf(resource.getCreationTime()));

        for (Entry<String, String> entry : resource.getHeaders().entrySet()) {
            response.setHeader(entry.getKey(), valueOf(entry.getValue()));
        }

        return resource.getContentType();
    }

    protected void write(
                        final HttpServletResponse response,
                        final Resource<T>         resource,
                        final List<Range>         ranges,
                        final String              contentType)
            throws IOException, SQLException {
        if (ranges.size() == 1) {
            final Range range = ranges.get(0);
            if ( ! resource.isStaticLargeObject() && ! resource.isDynamicLargeObject() ) {
                try (final FileChannel readableChannel = (FileChannel) objectService.getReadableChannel(resource.getObject());
                        final WritableByteChannel writableChannel = newChannel(response.getOutputStream())) {
                    readableChannel.transferTo(range.getStart(), range.getLength(), writableChannel);
                }
            } else {
                final boolean fullRange = range.getStart() == 0L && (range.getEnd() + 1) == range.getLength();
                if (fullRange) {
                    List<T> objects = new ArrayList<>();
                    if (resource.isDynamicLargeObject()) {
                        objects = objectService.listDynamicLargeObject(resource.getContainer(), resource.getObject());
                    } else {
                        for (Segment<T> next : resource.getSegments()) {
                            objects.add(next.getObject());
                        }
                    }
                    try (final WritableByteChannel writableChannel = newChannel(response.getOutputStream())) {
                        for (T next : objects) {
                            try (FileChannel readableChannel = (FileChannel) objectService.getReadableChannel(next)) {
                                long size = objectService.getSize(next);
                                readableChannel.transferTo(0L, size, writableChannel);
                            }
                        }
                    }
                } else {
                    if (resource.isDynamicLargeObject()) {
                        Vector<InputStream> streams = new Vector<>();
                        for (T next : objectService.listDynamicLargeObject(resource.getContainer(), resource.getObject())) {
                            InputStream is = newInputStream(objectService.getReadableChannel(next));
                            streams.add(is);
                        }
                        long totalSize = objectService.getDyanmicObjectSize(resource.getContainer(), resource.getObject());
                        try (ServletOutputStream sos = response.getOutputStream();
                                SequenceInputStream is = new SequenceInputStream(streams.elements())) {
                            for (Range next : ranges) {
                                copy(is, totalSize, response.getOutputStream(), next.getStart(), next.getLength());
                            }
                        }
                    } else if(resource.isStaticLargeObject()) {
                        Vector<InputStream> streams = new Vector<>();
                        for (Segment<T> next : resource.getSegments()) {
                            InputStream is = newInputStream(objectService.getReadableChannel(next.getObject()));
                            streams.add(is);
                        }
                        long totalSize = 0L;
                        for (Segment<T> segment : resource.getSegments()) {
                            long size = objectService.getSize(segment.getObject());
                            totalSize += size;
                        }
                        try (ServletOutputStream sos = response.getOutputStream();
                                SequenceInputStream is = new SequenceInputStream(streams.elements())) {
                            for (Range next : ranges) {
                                copy(is, totalSize, response.getOutputStream(), next.getStart(), next.getLength());
                            }
                        }
                    }
                }
            }
        } else {
            if (resource.isDynamicLargeObject()) {
                Vector<InputStream> streams = new Vector<>();
                for (T next : objectService.listDynamicLargeObject(resource.getContainer(), resource.getObject())) {
                    InputStream is = newInputStream(objectService.getReadableChannel(next));
                    streams.add(is);
                }
                long totalSize = objectService.getDyanmicObjectSize(resource.getContainer(), resource.getObject());
                try (ServletOutputStream sos = response.getOutputStream();
                        SequenceInputStream is = new SequenceInputStream(streams.elements())) {
                    for (Range r : ranges) {
                        sos.println();
                        sos.println("--" + r.getBoundary());
                        sos.println("Content-Type: " + contentType);
                        sos.println("Content-Range: bytes " + r.getStart() + "-" + r.getEnd() + "/" + totalSize);
                        copy(is, totalSize, response.getOutputStream(), r.getStart(), r.getLength());
                    }
                    sos.println();
                    sos.println("--" + ranges.get(0).getBoundary() + "--");
                }
            } else if (resource.isStaticLargeObject()) {
                Vector<InputStream> streams = new Vector<>();
                for (Segment<T> next : resource.getSegments()) {
                    InputStream is = newInputStream(objectService.getReadableChannel(next.getObject()));
                    streams.add(is);
                }
                long totalSize = 0L;
                for (Segment<T> segment : resource.getSegments()) {
                    long size = objectService.getSize(segment.getObject());
                    totalSize += size;
                }
                try (ServletOutputStream sos = response.getOutputStream();
                        SequenceInputStream is = new SequenceInputStream(streams.elements())) {
                    for (Range next : ranges) {
                        sos.println();
                        sos.println("--" + next.getBoundary());
                        sos.println("Content-Type: " + contentType);
                        sos.println("Content-Range: bytes " + next.getStart() + "-" + next.getEnd() + "/" + totalSize);
                        copy(is, totalSize, response.getOutputStream(), next.getStart(), next.getLength());
                    }
                    sos.println();
                    sos.println("--" + ranges.get(0).getBoundary() + "--");
                }
            } else {
                try (final FileChannel readableChannel = (FileChannel) objectService.getReadableChannel(resource.getObject());
                        final WritableByteChannel writableChannel = newChannel(response.getOutputStream())) {
                    ByteBuffer NL = wrap(NEW_LINE);
                    for (final Range range : ranges) {
                        NL.clear();
                        writableChannel.write(NL);
                        writableChannel.write(wrap(("--" + range.getBoundary()).getBytes(UTF_8)));
                        NL.clear();
                        writableChannel.write(NL);
                        writableChannel.write(wrap(("Content-Type: " + contentType).getBytes(UTF_8)));
                        NL.clear();
                        writableChannel.write(NL);
                        writableChannel.write(wrap(("Content-Range: bytes " + range.getStart() + '-' + range.getEnd() + '/' + range.getLength()).getBytes(UTF_8)));
                        NL.clear();
                        writableChannel.write(NL);
                        NL.clear();
                        writableChannel.write(NL);
                        NL.clear();

                        readableChannel.position(0L);

                        final ByteBuffer buffer = allocateDirect(BUFFER_SIZE);
                        long size = 0;
                        while ( readableChannel.read(buffer, range.getStart() + size) != -1 ) {
                            buffer.flip();
                            if (size + buffer.limit() > range.getLength()) {
                                buffer.limit((int) (range.getLength() - size));
                            }
                            size += writableChannel.write(buffer);
                            if (size >= range.getLength()) {
                                break;
                            }
                            buffer.clear();
                        }
                    }

                    writableChannel.write(NL);
                    NL.clear();
                    writableChannel.write(wrap(("--" + ranges.get(0).getBoundary() + "--").getBytes(UTF_8)));
                    writableChannel.write(NL);
                }
            }
        }
    }

    protected void copy(final InputStream  input,
                        final long         totalSize,
                        final OutputStream output,
                        final long         start,
                        final long         length) throws IOException {
        byte[] buffer = new byte[1024 * 16];
        int read;
        if (totalSize == length) {
            while ((read = input.read(buffer)) > 0) {
                output.write(buffer, 0, read);
            }
        } else {
            input.skip(start);
            long toRead = length;

            while ((read = input.read(buffer)) > 0) {
                if ((toRead -= read) > 0) {
                    output.write(buffer, 0, read);
                } else {
                    output.write(buffer, 0, (int) toRead + read);
                    break;
                }
            }
        }
    }

    protected boolean matches(
                        final String matchHeader,
                        final String eTag) {
        final String[] matchValues = matchHeader.split("\\s*,\\s*");
        sort(matchValues);
        return binarySearch(matchValues, eTag) > -1 || binarySearch(matchValues, "*") > -1;
    }

    protected boolean isModified(
                        final long modifiedHeader,
                        final long lastModified) {
        return modifiedHeader + ONE_SECOND_IN_MILLIS <= lastModified;
    }

    protected long toLong(
                        final String value,
                        final int    beginIndex,
                        final int    endIndex) {
        final String str = value.substring(beginIndex, endIndex);
        return str.isEmpty() ? -1 : parseLong(str);
    }
}


text:
/**
 * Created by huyhu on 26/06/16.
 */
angular.module('vipct')
  .controller('ProjectCtrl',
    function ($window, $state, $scope, $stateParams, fbRef, $firebaseArray, $firebaseObject, $filter, $uibModal) {
      if(null == $stateParams.param1){
        $state.go("projects");
      }

      var projects = $firebaseArray(fbRef.getProjectsRef());
      projects.$loaded().then(function () {
        $scope.project = projects.$getRecord($stateParams.param1);
        console.log($scope.project);
      }).catch(function (error) {
        console.log("error:", error);
      })

      $scope.back = function () {
        $window.history.back();
      }
    });


text:
{-# LANGUAGE OverloadedStrings, RecordWildCards, TemplateHaskell, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Tests.Syntax
    ( roundtripAST
    , compareAST
    , failBadSyntax
    , aliasResolution
    , verifySchemaDef
    ) where

import Control.Exception
import Data.Maybe
import Data.List
import Data.Aeson (encode, decode)
import Data.Aeson.Encode.Pretty (Config(..), encodePretty')
import Data.DeriveTH
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import System.FilePath
import Test.QuickCheck
import Test.HUnit
import Test.Tasty
import Test.Tasty.Golden
import Language.Bond.Syntax.Types
import Language.Bond.Syntax.Util
import Language.Bond.Syntax.SchemaDef
import IO

derive makeArbitrary ''Attribute
derive makeArbitrary ''Bond
derive makeArbitrary ''Constant
derive makeArbitrary ''Constraint
derive makeArbitrary ''Declaration
derive makeArbitrary ''Default
derive makeArbitrary ''Field
derive makeArbitrary ''Import
derive makeArbitrary ''Language
derive makeArbitrary ''Modifier
derive makeArbitrary ''Namespace
derive makeArbitrary ''Type
derive makeArbitrary ''TypeParam
derive makeArbitrary ''MethodType

instance Arbitrary Method where
  arbitrary = oneof
    [ Function <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
    , Event <$> arbitrary <*> arbitrary <*> eventInput]
    where
      -- events cannot have streaming input, so we need to customize the
      -- arbitrary input to omit Streaming
      eventInput = oneof [return Void,  Unary <$> arbitrary]

roundtripAST :: Bond -> Property
roundtripAST x = (decode . encode) x === Just x

assertException :: String -> IO a -> Assertion
assertException errMsg action = do
    e <- try action
    case e of
        Left (_ :: SomeException) -> return ()
        Right _ -> assertFailure errMsg

failBadSyntax :: String -> FilePath -> Assertion
failBadSyntax errMsg file = assertException errMsg (parseBondFile [] $ "tests" </> "schema" </> "error" </> file <.> "bond")

compareAST :: FilePath -> Assertion
compareAST file = do
    bond <- parseBondFile [] $ "tests" </> "schema" </> file <.> "bond"
    json <- parseASTFile $ "tests" </> "schema" </> file <.> "json"
    assertEqual "" bond json

aliasResolution :: Assertion
aliasResolution = do
    let p1 = TypeParam "T" Nothing
    let p2 = TypeParam "U" Nothing
    let a1 = Alias [] "" [] BT_Bool
    let a2 = Alias [] "" [p1] $ BT_TypeParam p1
    let a3 = Alias [] "" [p1] $ BT_List $ BT_TypeParam p1
    let a4 = Alias [] "" [p1, p2] $ BT_Nullable $ BT_Map (BT_TypeParam p2) (BT_Nullable $ BT_TypeParam p1)
    let a5 = Alias [] "" [p1] $ BT_List $ BT_UserDefined a3 [BT_TypeParam p1]
    let a6 = Alias [] "" [p1, p2] $ BT_Vector $ BT_Vector $ BT_TypeParam p2

    assertEqual "" BT_Bool $
        resolveAlias a1 []

    assertEqual "" BT_Int32 $
        resolveAlias a2 [BT_Int32]

    assertEqual "" (BT_Set BT_Int32) $
        resolveAlias a2 [BT_Set BT_Int32]

    assertEqual "" (BT_TypeParam p2) $
        resolveAlias a2 [BT_TypeParam p2]

    assertEqual "" (BT_TypeParam p1) $
        resolveAlias a2 [BT_TypeParam p1]

    assertEqual "" (BT_List BT_Int32) $
        resolveAlias a3 [BT_Int32]

    assertEqual "" (BT_List $ BT_UserDefined a1 []) $
        resolveAlias a3 [BT_UserDefined a1 []]

    assertEqual "" (BT_Nullable $ BT_Map BT_Bool $ BT_Nullable BT_String) $
        resolveAlias a4 [BT_String, BT_Bool]

    assertEqual "" (BT_List $ BT_UserDefined a3 [BT_Set BT_Bool]) $
        resolveAlias a5 [BT_Set BT_Bool]

    assertEqual "" (BT_Vector $ BT_Vector $ BT_List BT_Double) $
        resolveAlias a6 [BT_IntTypeArg 10, BT_List BT_Double]

verifySchemaDef :: FilePath -> String -> TestTree
verifySchemaDef baseName schemaName =
    goldenVsString
        schemaName
        ("tests" </> "generated" </> "schemadef" </> baseName <.> schemaName <.> "json")
        schemaDef
  where
    schemaDef = do
        (Bond _ _ declarations) <- parseBondFile [] $ "tests" </> "schema" </> baseName <.> "bond"
        let schema = fromJust $ find ((schemaName ==) . declName) declarations
        return $
            -- some versions aeson encode angle brackets
            BL.fromStrict $
            replace "\\u003c" "<" $
            replace "\\u003e" ">" $
            BL.toStrict $ prettyEncode $ makeSchemaDef $ BT_UserDefined schema []
      where
        prettyEncode = encodePretty' (Config indentSpaces compare)
          where
            indentSpaces = 2
        replace s r bs = if B.null t then h else
            B.append h (B.append r $ replace s r (B.drop (B.length s) t))
          where
            (h, t) = B.breakSubstring s bs


text:
module.exports = DataAdapter;

function DataAdapter(options) {
  this.options = options || {};
}

/**
 * `request`
 *
 * This is method that Rendr calls to ask for data. Stubbed out here, to be
 * subclassed to connect to whatever data souce you want your models and
 * collections to talk to.
 *
 * `req`: Actual request object from Express/Connect.
 * `api`: Object describing API call; properties including 'path', 'query', etc.
 *        Passed to `url.format()`.
 * `options`: (optional) Options.
 * `callback`: Callback.
 */
DataAdapter.prototype.request = function(req, api, options, callback) {
  throw new Exception('Implement me!');
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2005-2013 the original author or authors.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd">
	<import resource="classpath:/conf/commonTestContext.xml" />

    <ldap:context-source
            password="secret"
            url="ldap://localhost:1888"
            username="uid=admin,ou=system"
            base="dc=261consulting,dc=com">

        <ldap:pooling
                max-active="1"
                max-total="1"
                max-idle="1"
                min-idle="1" />
    </ldap:context-source>

    <ldap:ldap-template />
</beans>


text:
@class IDERunOperationWorker, NSError;

@protocol IDERunOperationWorkerTracker <NSObject>
- (void)runningDidFinish:(IDERunOperationWorker *)arg1 withError:(NSError *)arg2;
@end


text:
require 'rack/json_parser/error'

module Rack
  class JSONParser
    # A error signaling that the application should respond with bad request
    class BadRequest < Error
      def initialize(detail)
        super('Bad request', detail: detail, status_code: 400)
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>tdh-collection</artifactId>
        <groupId>io.transwarp.collection</groupId>
        <version>0.4v</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>flumeInterceptor</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.apache.flume</groupId>
            <artifactId>flume-ng-configuration</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flume</groupId>
            <artifactId>flume-ng-sdk</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flume</groupId>
            <artifactId>flume-ng-core</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.5.2-transwarp-tdh460</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.5.2-transwarp-tdh460</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

</project>


text:
require 'test_helper'

class NotasTecnicasHelperTest < ActionView::TestCase
end


text:
title: March 4th Announcements
subtitle: Here are your March 4th Announcements with Pastor Mark Hornback and Richie Runnells
layout: default
modal-id: 7
date:  2018-03-04T16:34:11+00:00
img: white_pixel.png
thumbnail: http://img.youtube.com/vi/w60P4sRkBvQ/0.jpg
alt: https://i4.ytimg.com/vi/w60P4sRkBvQ/hqdefault.jpg
project-date:
description: <iframe width="560" height="315" src="https://www.youtube.com/embed/w60P4sRkBvQ" frameborder="0" allowfullscreen></iframe>
---


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.das</groupId>
        <artifactId>wso2das-parent</artifactId>
        <version>3.2.0-beta2-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>wso2das-features-parent</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Data Analytics Server - Features Parent</name>
    <description>WSO2 Data Analytics Server Features Parent</description>

    <modules>
        <module>product</module>
        <module>service</module>
    </modules>
</project>


text:
<?php

namespace Overtrue\Wechat\Shop\Foundation;

/**
 * 分组管理
 *
 * Interface Group
 * @package Shop
 */
interface Group
{
    /**
     * 添加分组
     *
     * @param $groupName
     * @param $productList
     * @return int
     */
    public function add($groupName, array $productList);

    /**
     * 删除分组
     *
     * @param $groupId
     * @return bool
     */
    public function delete($groupId);

    /**
     * 修改分组属性
     *
     * @param $groupId
     * @param $groupName
     * @return bool
     */
    public function updateAttribute($groupId, $groupName);

    /**
     * 修改分组商品
     *
     * @param $groupId
     * @param $product
     * @return bool
     */
    public function updateProduct($groupId, array $product);

    /**
     * 获得全部商品
     *
     * @return array
     */
    public function lists();

    /**
     * 根据分组ID获取分组信息
     *
     * @param $groupId
     * @return array
     */
    public function getById($groupId);
}


text:
"use strict";

const nock = require('nock');

nock.recorder.rec();

exports.handler = require('../src/main').handler;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>CmdMessenger: CommandMessengerTests.MultipleArguments Class Reference</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

CmdMessenger
    4.0.0

CmdMessenger is a serial port messaging library for the .Net / Mono Platform.

Main Page

Packages

Classes

Class List

Class Index

Class Hierarchy

Class Members

CommandMessengerTests

MultipleArguments

Public Member Functions

CommandMessengerTests.MultipleArguments Class Reference

List of all members.

Public Member Functions

 	MultipleArguments (systemSettings systemSettings, Enumerator command)

void 	RunTests ()

void 	SetUpConnection ()

void 	CloseConnection ()

void 	TestSendMultipleValues ()

The documentation for this class was generated from the following file:

D:/My Documents/Github/Arduino/Own Arduino libraries/CmdMessenger/Arduino-CmdMessenger/extras/CSharp/CommandMessengerTests/Tests/MultipleArguments.cs

<address class="footer">
Generated on Fri Apr 24 2015 23:15:52 for CmdMessenger by

 1.7.6.1
</address>


text:
<?xml version="1.0" encoding="Windows-1252" ?>
<NotepadPlus>
	<AutoComplete>
		<KeyWord name="ACCELERATORS" />
		<KeyWord name="ALT" />
		<KeyWord name="AUTO3STATE" />
		<KeyWord name="AUTOCHECKBOX" />
		<KeyWord name="AUTORADIOBUTTON" />
		<KeyWord name="BEGIN" />
		<KeyWord name="BITMAP" />
		<KeyWord name="BLOCK" />
		<KeyWord name="BUTTON" />
		<KeyWord name="CAPTION" />
		<KeyWord name="CHARACTERISTICS" />
		<KeyWord name="CHECKBOX" />
		<KeyWord name="CLASS" />
		<KeyWord name="COMBOBOX" />
		<KeyWord name="CONTROL" />
		<KeyWord name="CTEXT" />
		<KeyWord name="CURSOR" />
		<KeyWord name="DEFPUSHBUTTON" />
		<KeyWord name="DIALOG" />
		<KeyWord name="DIALOGEX" />
		<KeyWord name="DISCARDABLE" />
		<KeyWord name="EDITTEXT" />
		<KeyWord name="END" />
		<KeyWord name="EXSTYLE" />
		<KeyWord name="FONT" />
		<KeyWord name="GROUPBOX" />
		<KeyWord name="ICON" />
		<KeyWord name="LANGUAGE" />
		<KeyWord name="LISTBOX" />
		<KeyWord name="LTEXT" />
		<KeyWord name="MENU" />
		<KeyWord name="MENUEX" />
		<KeyWord name="MENUITEM" />
		<KeyWord name="MESSAGETABLE" />
		<KeyWord name="POPUP" />
		<KeyWord name="PUSHBUTTON" />
		<KeyWord name="RADIOBUTTON" />
		<KeyWord name="RCDATA" />
		<KeyWord name="RTEXT" />
		<KeyWord name="SCROLLBAR" />
		<KeyWord name="SEPARATOR" />
		<KeyWord name="SHIFT" />
		<KeyWord name="STATE3" />
		<KeyWord name="STRINGTABLE" />
		<KeyWord name="STYLE" />
		<KeyWord name="TEXTINCLUDE" />
		<KeyWord name="VALUE" />
		<KeyWord name="VERSION" />
		<KeyWord name="VERSIONINFO" />
		<KeyWord name="VIRTKEY" />
	</AutoComplete>
</NotepadPlus>


text:
This pipeline analyses WaferGen's ICELL8 single cell sequencing
data. It uses [umis](https://github.com/vals/umis) and
[scRNApipe](https://github.com/MarinusVL/scRNApipe) for the core
analysis.

In a first step reads are quality trimmed and adapter sequences are
removed (both achieved with Skewer).  Reads are then further processed
by the umis package (facilitated by scRNApipe). The preprocessed reads
are aligned by two different methods
1. with STAR against the given reference genome and
2. with Kallisto against the transcripts.

The mapped BAM files from STAR aligner are deduplicated (user option) and
meta-features (genes) are counted using featurecounts. The
pseudo-aligned reads with transcripts are counted by unique UMI
(gene-UMI). The analysis provides the expression matrix of genes and
transcripts for cell barcodes.

The pipeline also provides generic stats, coverage, mappability,
MultiQC, RNA-SeQC (per cellular barcode) and FastQC output.

## Input:

Cellular barcode list (see option `-c`): All samples barcodes must be
listed in this file (for non-demux use "1")

See `cfg/references.yaml` for reference data (reference genome, index,
annotation and gene id files) used by default (also refer to option
`--references-cfg`).

In addition you will need to provide sample definitions, either
through a config file (`--sample-cfg`) or through a full definition on
the commandline (options `-1`, `-2` and `-s`).

## Output:

The following lists the most important files/directories that are
created per sample in correspondingly named subfolders of `out`:

- `Results/gene_ExpressionMatrix.csv`: Expression matrix from STAR aligned BAM file
- `kallisto/kallisto.tagcount.txt`: Expression matrix by Kallisto
- `mb-histogram.txt`: Number of of raw reads from each cell barcode-UMI
- `cb-histogram.txt`: Number of of raw reads from each cell barcode

Reports:
- `Reports/FinalReport.html`: MultiQC output
- `Reports//QCreports/{sample}_fastqc.html`: FastQC output
- `Reports/SummarisedStats.csv`: Summary stats of reads preprocessing, STAR, featurecount, dedup logs etc.

## Notes

Deduplication can be very slow for large data-sets. We recommend to not use it unless necessary (`--dedup`).

## References

- scRNApipe: [website](https://github.com/MarinusVL/scRNApipe)
- umis: [website](https://github.com/vals/umis)
- Kallisto [website](https://pachterlab.github.io/kallisto/about) and [publication](https://www.ncbi.nlm.nih.gov/pubmed/27043002)
- Skewer: [publication](https://www.ncbi.nlm.nih.gov/pubmed/24925680) and [website](https://github.com/relipmoc/skewer)


text: Visa Bulletin


text:
using System;
using System.Collections.Generic;
using System.Fabric;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ServiceFabric.Services.Communication.AspNetCore;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;

namespace WebFrontEnd
{
    /// <summary>
    /// The FabricRuntime creates an instance of this class for each service type instance.
    /// </summary>
    internal sealed class WebFrontEnd : StatelessService
    {
        public WebFrontEnd(StatelessServiceContext context)
            : base(context)
        { }

        /// <summary>
        /// Optional override to create listeners (like tcp, http) for this service instance.
        /// </summary>
        /// <returns>The collection of listeners.</returns>
        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>
                    new WebListenerCommunicationListener(serviceContext, "ServiceEndpoint", url =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting WebListener on {url}");

                        return new WebHostBuilder().UseWebListener()
                                    .ConfigureServices(
                                        services => services
                                            .AddSingleton<StatelessServiceContext>(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .UseStartup<Startup>()
                                    .UseApplicationInsights()
                                    .UseUrls(url)
                                    .Build();
                    }), "unsecure"),
                new ServiceInstanceListener(serviceContext =>
                    new WebListenerCommunicationListener(serviceContext, "SecureServiceEndpoint", url =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting WebListener on {url}");

                        return new WebHostBuilder().UseWebListener()
                                    .ConfigureServices(
                                        services => services
                                            .AddSingleton<StatelessServiceContext>(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .UseStartup<Startup>()
                                    .UseApplicationInsights()
                                    .UseUrls(url)
                                    .Build();
                    }), "secure")
            };
        }
    }
}


text:
<root>
  <item name='com.sun.jna.Native T load(java.lang.String, java.lang.Class<T>) 0'>
    <annotation name='org.jetbrains.annotations.NonNls'/>
  </item>
  <item name='com.sun.jna.Native T load(java.lang.String, java.lang.Class<T>, java.util.Map<java.lang.String,?>) 0'>
    <annotation name='org.jetbrains.annotations.NonNls'/>
  </item>
  <item name='com.sun.jna.Native void register(java.lang.String) 0'>
    <annotation name='org.jetbrains.annotations.NonNls'/>
  </item>
</root>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Этот код создан программой.
//     Исполняемая версия:4.0.30319.42000
//
//     Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
//     повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PowerLib.System {
    using System;

    /// <summary>
    ///   Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
    /// </summary>
    // Этот класс создан автоматически классом StronglyTypedResourceBuilder
    // с помощью такого средства, как ResGen или Visual Studio.
    // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
    // с параметром /str или перестройте свой проект VS.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class ConditionCriteria {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal ConditionCriteria() {
        }

        /// <summary>
        ///   Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PowerLib.System.ConditionCriteria", typeof(ConditionCriteria).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Перезаписывает свойство CurrentUICulture текущего потока для всех
        ///   обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string BetweenCriteria_ExcludeBoth {
            get {
                return ResourceManager.GetString("BetweenCriteria_ExcludeBoth", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string BetweenCriteria_ExcludeLower {
            get {
                return ResourceManager.GetString("BetweenCriteria_ExcludeLower", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string BetweenCriteria_ExcludeUpper {
            get {
                return ResourceManager.GetString("BetweenCriteria_ExcludeUpper", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string BetweenCriteria_IncludeBoth {
            get {
                return ResourceManager.GetString("BetweenCriteria_IncludeBoth", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_Equal {
            get {
                return ResourceManager.GetString("ComparisonCriteria_Equal", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_GreaterThan {
            get {
                return ResourceManager.GetString("ComparisonCriteria_GreaterThan", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_GreaterThanOrEqual {
            get {
                return ResourceManager.GetString("ComparisonCriteria_GreaterThanOrEqual", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_LessThan {
            get {
                return ResourceManager.GetString("ComparisonCriteria_LessThan", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_LessThanOrEqual {
            get {
                return ResourceManager.GetString("ComparisonCriteria_LessThanOrEqual", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string ComparisonCriteria_NotEqual {
            get {
                return ResourceManager.GetString("ComparisonCriteria_NotEqual", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string GroupCriteria_And {
            get {
                return ResourceManager.GetString("GroupCriteria_And", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string GroupCriteria_Or {
            get {
                return ResourceManager.GetString("GroupCriteria_Or", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string QuantifyCriteria_All {
            get {
                return ResourceManager.GetString("QuantifyCriteria_All", resourceCulture);
            }
        }

        /// <summary>
        ///   Ищет локализованную строку, похожую на .
        /// </summary>
        internal static string QuantifyCriteria_Any {
            get {
                return ResourceManager.GetString("QuantifyCriteria_Any", resourceCulture);
            }
        }
    }
}


text:
import * as mosca from 'mosca';

import { Server, CustomTransportStrategy } from '@nestjs/microservices';
import { Observable } from 'rxjs/Observable';
import { db } from '../config/db.connection'

export class MqttBroker extends Server implements CustomTransportStrategy {
  private broker = null;

  constructor(
    private readonly puerto: string,
    private readonly socket: string) {
    super();
  }

  public async listen(callback: () => void) {
    await this.init()
  }

  public close() { }

  private handleMessage(message) {
  }

  private sendMessage(message) {
  }

  private async init() {

    // Acepta la conexión si el usuario y contraseña son válidos
    var authenticate = function(client, username, password, callback) {
      var authorized = (username === '1000003' && password.toString() === '25bd95c4-484a-11e7-8835-0242ac110002');
      console.log(authorized);

      if (authorized) client.user = username;
      callback(null, authorized);
    }

    // In this case the client authorized as alice can publish to /users/alice taking
    // the username from the topic and verifing it is the same of the authorized user
    var authorizePublish = function(client, topic, payload, callback) {

      callback(null, client.user == topic.split('/')[1]);
    }

    // In this case the client authorized as alice can subscribe to /users/alice taking
    // the username from the topic and verifing it is the same of the authorized user
    var authorizeSubscribe = function(client, topic, callback) {
      console.log(topic.split('/')[1])

      callback(null, client.user == topic.split('/')[1]);
    }

    var server = new mosca.Server({
      port: 1883,
      http: {
        port: 4000,
        bundle: true,
        static: './src/mqtt/public'
      }
    });
    server.on('ready', setup);

    function setup() {
      console.log("conectado mqtt")
      server.authenticate = authenticate;
      server.authorizePublish = authorizePublish;
      server.authorizeSubscribe = authorizeSubscribe;
    }

    server.on('clientConnected', function(client) {
      console.log('Client connected', client.id)
    })

  }
}