text:
(function ($) {

Drupal.ModuleFilter.tabs = {};
Drupal.ModuleFilter.enabling = {};
Drupal.ModuleFilter.disabling = {};

Drupal.ModuleFilter.jQueryIsNewer = function() {
  if (Drupal.ModuleFilter.jQueryNewer == undefined) {
    var v1parts = $.fn.jquery.split('.');
    var v2parts = new Array('1', '4', '4');

    for (var i = 0; i < v1parts.length; ++i) {
      if (v2parts.length == i) {
        Drupal.ModuleFilter.jQueryNewer = true;
        return Drupal.ModuleFilter.jQueryNewer;
      }

      if (v1parts[i] == v2parts[i]) {
        continue;
      }
      else if (v1parts[i] > v2parts[i]) {
        Drupal.ModuleFilter.jQueryNewer = true;
        return Drupal.ModuleFilter.jQueryNewer;
      }
      else {
        Drupal.ModuleFilter.jQueryNewer = false;
        return Drupal.ModuleFilter.jQueryNewer;
      }
    }

    if (v1parts.length != v2parts.length) {
      Drupal.ModuleFilter.jQueryNewer = false;
      return Drupal.ModuleFilter.jQueryNewer;
    }

    Drupal.ModuleFilter.jQueryNewer = false;
  }
  return Drupal.ModuleFilter.jQueryNewer;
};

Drupal.behaviors.moduleFilterTabs = {
  attach: function(context) {
    if (Drupal.settings.moduleFilter.tabs) {
      $('#module-filter-wrapper table:not(.sticky-header)', context).once('module-filter-tabs', function() {
        var $modules = $('#module-filter-modules');
        var moduleFilter = $('input[name="module_filter[name]"]').data('moduleFilter');
        var table = $(this);

        $('thead', table).show();

        // Remove package header rows.
        $('tr.admin-package-header', table).remove();

        var $tabsWrapper = $('

');

        // Build tabs from package title rows.
        var tabs = '
';
        for (var i in Drupal.settings.moduleFilter.packageIDs) {
          var id = Drupal.settings.moduleFilter.packageIDs[i];

          var name = id;
          var tabClass = 'project-tab';
          var title = null;
          var summary = (Drupal.settings.moduleFilter.countEnabled) ? '' + Drupal.ModuleFilter.countSummary(id) + '' : '';

          switch (id) {
            case 'all':
              name = Drupal.t('All');
              break;
            case 'new':
              name = Drupal.t('New');
              title = Drupal.t('Modules installed within the last week.');
              if (Drupal.settings.moduleFilter.enabledCounts['new'].total == 0) {
                tabClass += ' disabled';
                summary += '' + Drupal.t('No modules added within the last week.') + '';
              }
              break;
            case 'recent':
              name = Drupal.t('Recent');
              title = Drupal.t('Modules enabled/disabled within the last week.');
              if (Drupal.settings.moduleFilter.enabledCounts['recent'].total == 0) {
                tabClass += ' disabled';
                summary += '' + Drupal.t('No modules were enabled or disabled within the last week.') + '';
              }
              break;
            default:
              var $row = $('#' + id + '-package');
              name = $.trim($row.text());
              $row.remove();
              break;
          }

          tabs += '
' + name + '' + summary + '
';
        }
        tabs += '
';
        $tabsWrapper.append(tabs);
        $modules.before($tabsWrapper);

        // Index tabs.
        $('#module-filter-tabs li').each(function() {
          var $tab = $(this);
          var id = $tab.attr('id');
          Drupal.ModuleFilter.tabs[id] = new Drupal.ModuleFilter.Tab($tab, id);
        });

        $('tbody td.checkbox input', $modules).change(function() {
          var $checkbox = $(this);
          var key = $checkbox.parents('tr').data('indexKey');

          moduleFilter.index[key].status = $checkbox.is(':checked');

          if (Drupal.settings.moduleFilter.visualAid) {
            var type = ($checkbox.is(':checked')) ? 'enable' : 'disable';
            Drupal.ModuleFilter.updateVisualAid(type, $checkbox.parents('tr'));
          }
        });

        // Sort rows.
        var rows = $('tbody tr.module', table).get();
        rows.sort(function(a, b) {
          var compA = $('td:nth(1)', a).text().toLowerCase();
          var compB = $('td:nth(1)', b).text().toLowerCase();
          return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
        });
        $.each(rows, function(idx, itm) { table.append(itm); });

        // Re-stripe rows.
        $('tr.module', table)
          .removeClass('odd even')
          .filter(':odd').addClass('even').end()
          .filter(':even').addClass('odd');

        moduleFilter.adjustHeight();

        moduleFilter.element.bind('moduleFilter:start', function() {
          moduleFilter.tabResults = {
            'all-tab': { items: {}, count: 0 },
            'recent-tab': { items: {}, count: 0 },
            'new-tab': { items: {}, count: 0 }
          };

          // Empty result info from tabs.
          for (var i in Drupal.ModuleFilter.tabs) {
            if (Drupal.ModuleFilter.tabs[i].resultInfo != undefined) {
              Drupal.ModuleFilter.tabs[i].resultInfo.empty();
            }
          }
        });

        moduleFilter.element.bind('moduleFilter:finish', function(e, data) {
          $.each(moduleFilter.index, function(key, item) {
            if (!item.element.hasClass('js-hide')) {
              var id = Drupal.ModuleFilter.getTabID(item.element);

              if (moduleFilter.tabResults[id] == undefined) {
                moduleFilter.tabResults[id] = { items: {}, count: 0 };
              }
              if (moduleFilter.tabResults[id].items[item.key] == undefined) {
                // All tab
                moduleFilter.tabResults['all-tab'].count++;

                // Recent tab
                if (item.element.hasClass('recent-module')) {
                  moduleFilter.tabResults['recent-tab'].count++;
                }

                // New tab
                if (item.element.hasClass('new-module')) {
                  moduleFilter.tabResults['new-tab'].count++;
                }

                moduleFilter.tabResults[id].items[item.key] = item;
                moduleFilter.tabResults[id].count++;
              }

              if (Drupal.ModuleFilter.activeTab != undefined && Drupal.ModuleFilter.activeTab.id != 'all-tab') {
                if ((Drupal.ModuleFilter.activeTab.id == 'recent-tab' && !item.element.hasClass('recent-module')) || (Drupal.ModuleFilter.activeTab.id == 'new-tab' && !item.element.hasClass('new-module')) || (Drupal.ModuleFilter.activeTab.id != 'recent-tab' && Drupal.ModuleFilter.activeTab.id != 'new-tab' && id != Drupal.ModuleFilter.activeTab.id)) {
                  // The item is not in the active tab, so hide it.
                  item.element.addClass('js-hide');
                }
              }
            }
          });

          if (Drupal.settings.moduleFilter.visualAid) {
            if (moduleFilter.text) {
              // Add result info to tabs.
              for (var id in moduleFilter.tabResults) {
                var tab = Drupal.ModuleFilter.tabs[id];

                if (tab.resultInfo == undefined) {
                  var resultInfo = ''
                  $('a', tab.element).prepend(resultInfo);
                  tab.resultInfo = $('span.result-info', tab.element);
                }

                tab.resultInfo.append(moduleFilter.tabResults[id].count);
              }

              if (Drupal.settings.moduleFilter.hideEmptyTabs) {
                for (var id in Drupal.ModuleFilter.tabs) {
                  if (moduleFilter.tabResults[id] != undefined) {
                    Drupal.ModuleFilter.tabs[id].element.show();
                  }
                  else if (Drupal.ModuleFilter.activeTab == undefined || Drupal.ModuleFilter.activeTab.id != id) {
                    Drupal.ModuleFilter.tabs[id].element.hide();
                  }
                }
              }
            }
            else {
              // Make sure all tabs are visible.
              if (Drupal.settings.moduleFilter.hideEmptyTabs) {
                $('#module-filter-tabs li').show();
              }
            }
          }

          if ((Drupal.ModuleFilter.activeTab != undefined && (moduleFilter.tabResults[Drupal.ModuleFilter.activeTab.id] == undefined || moduleFilter.tabResults[Drupal.ModuleFilter.activeTab.id].count <= 0))) {
            // The current tab contains no results.
            moduleFilter.results = 0;
          }

          moduleFilter.adjustHeight();
        });

        if (Drupal.settings.moduleFilter.useURLFragment) {
          $(window).bind('hashchange.module-filter', $.proxy(Drupal.ModuleFilter, 'eventHandlerOperateByURLFragment')).triggerHandler('hashchange.module-filter');
        }
        else {
          Drupal.ModuleFilter.selectTab();
        }

        if (Drupal.settings.moduleFilter.useSwitch) {
          $('td.checkbox div.form-item').hide();
          $('td.checkbox').each(function(i) {
            var $cell = $(this);
            var $checkbox = $(':checkbox', $cell);
            var $switch = $('.toggle-enable', $cell);
            $switch.removeClass('js-hide').click(function() {
              if (!$(this).hasClass('disabled')) {
                if (Drupal.ModuleFilter.jQueryIsNewer()) {
                  $checkbox.click();
                }
                else {
                  $checkbox.click().change();
                }
              }
            });
            $checkbox.click(function() {
              if (!$switch.hasClass('disabled')) {
                $switch.toggleClass('off');
              }
            });
          });
        }

        var $tabs = $('#module-filter-tabs');

        function getParentTopOffset($obj, offset) {
          var $parent = $obj.offsetParent();
          if ($obj[0] != $parent[0]) {
            offset += $parent.position().top;
            return getParentTopOffset($parent, offset);
          }
          return offset;
        }

        var tabsTopOffset = null;
        function getParentsTopOffset() {
          if (tabsTopOffset === null) {
            tabsTopOffset = getParentTopOffset($tabs.parent(), 0);
          }
          return tabsTopOffset;
        }

        function viewportTop() {
          var top = $(window).scrollTop();
          return top;
        }

        function viewportBottom() {
          var top = $(window).scrollTop();
          var bottom = top + $(window).height();

          bottom -= $('#page-actions').height();

          return bottom;
        }

        function fixToTop(top) {
          if ($tabs.hasClass('bottom-fixed')) {
            $tabs.css({
              'position': 'absolute',
              'top': $tabs.position().top - getParentsTopOffset(),
              'bottom': 'auto'
            });
            $tabs.removeClass('bottom-fixed');
          }

          if (($tabs.css('position') == 'absolute' && $tabs.offset().top - top >= 0) || ($tabs.css('position') != 'absolute' && $tabs.offset().top - top <= 0)) {
            $tabs.addClass('top-fixed');
            $tabs.attr('style', '');
          }
        }

        function fixToBottom(bottom) {
          if ($tabs.hasClass('top-fixed')) {
            $tabs.css({
              'position': 'absolute',
              'top': $tabs.position().top - getParentsTopOffset(),
              'bottom': 'auto'
            });
            $tabs.removeClass('top-fixed');
          }

          if ($tabs.offset().top + $tabs.height() - bottom <= 0) {
            $tabs.addClass('bottom-fixed');
            var style = '';
            var pageActionsHeight = $('#page-actions').height();
            if (pageActionsHeight > 0) {
              style = 'bottom: ' + pageActionsHeight + 'px';
            }
            else if (Drupal.settings.moduleFilter.dynamicPosition) {
              // style = 'bottom: ' + $('#module-filter-submit', $tabs).height() + 'px';
            }
            $tabs.attr('style', style);
          }
        }

        var lastTop = 0;
        $(window).scroll(function() {
          var top = viewportTop();
          var bottom = viewportBottom();

          if ($modules.offset().top >= top) {
            $tabs.removeClass('top-fixed').attr('style', '');
          }
          else {
            if (top > lastTop) { // Downward scroll.
              if ($tabs.height() > bottom - top) {
                fixToBottom(bottom);
              }
              else {
                fixToTop(top);
              }
            }
            else { // Upward scroll.
              fixToTop(top);
            }
          }
          lastTop = top;
        });

        moduleFilter.adjustHeight();
      });
    }
  }
};

Drupal.ModuleFilter.Tab = function(element, id) {
  var self = this;

  this.id = id;
  this.hash = id.substring(0, id.length - 4);
  this.element = element;

  $('a', this.element).click(function() {
    if (!Drupal.settings.moduleFilter.useURLFragment) {
      var hash = (!self.element.hasClass('selected')) ? self.hash : 'all';
      Drupal.ModuleFilter.selectTab(hash);
      return false;
    }

    if (self.element.hasClass('selected')) {
      // Clear the active tab.
      window.location.hash = 'all';
      return false;
    }
  });

  $('tr.' + this.id, $('#system-modules')).hover(
    function() {
      self.element.addClass('suggest');
    },
    function() {
      self.element.removeClass('suggest');
    }
  );
};

Drupal.ModuleFilter.selectTab = function(hash) {
  if (!hash || Drupal.ModuleFilter.tabs[hash + '-tab'] == undefined || Drupal.settings.moduleFilter.enabledCounts[hash].total == 0) {
    if (Drupal.settings.moduleFilter.rememberActiveTab) {
      var activeTab = Drupal.ModuleFilter.getState('activeTab');
      if (activeTab && Drupal.ModuleFilter.tabs[activeTab + '-tab'] != undefined) {
        hash = activeTab;
      }
    }

    if (!hash) {
      hash = 'all';
    }
  }

  if (Drupal.ModuleFilter.activeTab != undefined) {
    Drupal.ModuleFilter.activeTab.element.removeClass('selected');
  }

  Drupal.ModuleFilter.activeTab = Drupal.ModuleFilter.tabs[hash + '-tab'];
  Drupal.ModuleFilter.activeTab.element.addClass('selected');

  var moduleFilter = $('input[name="module_filter[name]"]').data('moduleFilter');
  var filter = moduleFilter.applyFilter();

  if (!Drupal.ModuleFilter.modulesTop) {
    Drupal.ModuleFilter.modulesTop = $('#module-filter-modules').offset().top;
  }
  else {
    // Calculate header offset; this is important in case the site is using
    // admin_menu module which has fixed positioning and is on top of everything
    // else.
    var headerOffset = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0;
    // Scroll back to top of #module-filter-modules.
    $('html, body').animate({
      scrollTop: Drupal.ModuleFilter.modulesTop - headerOffset
    }, 500);
    // $('html, body').scrollTop(Drupal.ModuleFilter.modulesTop);
  }

  Drupal.ModuleFilter.setState('activeTab', hash);
};

Drupal.ModuleFilter.eventHandlerOperateByURLFragment = function(event) {
  var hash = $.param.fragment();
  Drupal.ModuleFilter.selectTab(hash);
};

Drupal.ModuleFilter.countSummary = function(id) {
  return Drupal.t('@enabled of @total', { '@enabled': Drupal.settings.moduleFilter.enabledCounts[id].enabled, '@total': Drupal.settings.moduleFilter.enabledCounts[id].total });
};

Drupal.ModuleFilter.Tab.prototype.updateEnabling = function(name, remove) {
  this.enabling = this.enabling || {};
  if (!remove) {
    this.enabling[name] = name;
  }
  else {
    delete this.enabling[name];
  }
};

Drupal.ModuleFilter.Tab.prototype.updateDisabling = function(name, remove) {
  this.disabling = this.disabling || {};
  if (!remove) {
    this.disabling[name] = name;
  }
  else {
    delete this.disabling[name];
  }
};

Drupal.ModuleFilter.Tab.prototype.updateVisualAid = function() {
  var visualAid = '';
  var enabling = new Array();
  var disabling = new Array();

  if (this.enabling != undefined) {
    for (var i in this.enabling) {
      enabling.push(this.enabling[i]);
    }
    if (enabling.length > 0) {
      enabling.sort();
      visualAid += '+' + enabling.join(', ') + '';
    }
  }
  if (this.disabling != undefined) {
    for (var i in this.disabling) {
      disabling.push(this.disabling[i]);
    }
    if (disabling.length > 0) {
      disabling.sort();
      if (enabling.length > 0) {
        visualAid += '
';
      }
      visualAid += '-' + disabling.join(', ') + '';
    }
  }

  if (this.visualAid == undefined) {
    $('a span.summary', this.element).append('');
    this.visualAid = $('span.visual-aid', this.element);
  }

  this.visualAid.empty().append(visualAid);
};

Drupal.ModuleFilter.getTabID = function($row) {
  var id = $row.data('moduleFilterTabID');
  if (!id) {
    // Find the tab ID.
    var classes = $row.attr('class').split(' ');
    for (var i in classes) {
      if (Drupal.ModuleFilter.tabs[classes[i]] != undefined) {
        id = classes[i];
        break;
      }
    }
    $row.data('moduleFilterTabID', id);
  }
  return id;
};

Drupal.ModuleFilter.updateVisualAid = function(type, $row) {
  var id = Drupal.ModuleFilter.getTabID($row);

  if (!id) {
    return false;
  }

  var tab = Drupal.ModuleFilter.tabs[id];
  var name = $('td:nth(1) strong', $row).text();
  switch (type) {
    case 'enable':
      if (Drupal.ModuleFilter.disabling[id + name] != undefined) {
        delete Drupal.ModuleFilter.disabling[id + name];
        tab.updateDisabling(name, true);
        $row.removeClass('disabling');
      }
      else {
        Drupal.ModuleFilter.enabling[id + name] = name;
        tab.updateEnabling(name);
        $row.addClass('enabling');
      }
      break;
    case 'disable':
      if (Drupal.ModuleFilter.enabling[id + name] != undefined) {
        delete Drupal.ModuleFilter.enabling[id + name];
        tab.updateEnabling(name, true);
        $row.removeClass('enabling');
      }
      else {
        Drupal.ModuleFilter.disabling[id + name] = name;
        tab.updateDisabling(name);
        $row.addClass('disabling');
      }
      break;
  }

  tab.updateVisualAid();
};

Drupal.ModuleFilter.Filter.prototype.adjustHeight = function() {
  // Hack for adjusting the height of the modules section.
  var minHeight = $('#module-filter-tabs ul').height() + 10;
  minHeight += $('#module-filter-tabs #module-filter-submit').height();
  $('#module-filter-modules').css('min-height', minHeight);
  this.element.trigger('moduleFilter:adjustHeight');
}

})(jQuery);


text:
package fake

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	api "k8s.io/kubernetes/pkg/api"
	core "k8s.io/kubernetes/pkg/client/testing/core"
)

// FakeLimitRanges implements LimitRangeInterface
type FakeLimitRanges struct {
	Fake *FakeCore
	ns   string
}

var limitrangesResource = schema.GroupVersionResource{Group: "", Version: "", Resource: "limitranges"}

func (c *FakeLimitRanges) Create(limitRange *api.LimitRange) (result *api.LimitRange, err error) {
	obj, err := c.Fake.
		Invokes(core.NewCreateAction(limitrangesResource, c.ns, limitRange), &api.LimitRange{})

	if obj == nil {
		return nil, err
	}
	return obj.(*api.LimitRange), err
}

func (c *FakeLimitRanges) Update(limitRange *api.LimitRange) (result *api.LimitRange, err error) {
	obj, err := c.Fake.
		Invokes(core.NewUpdateAction(limitrangesResource, c.ns, limitRange), &api.LimitRange{})

	if obj == nil {
		return nil, err
	}
	return obj.(*api.LimitRange), err
}

func (c *FakeLimitRanges) Delete(name string, options *api.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(core.NewDeleteAction(limitrangesResource, c.ns, name), &api.LimitRange{})

	return err
}

func (c *FakeLimitRanges) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error {
	action := core.NewDeleteCollectionAction(limitrangesResource, c.ns, listOptions)

	_, err := c.Fake.Invokes(action, &api.LimitRangeList{})
	return err
}

func (c *FakeLimitRanges) Get(name string, options v1.GetOptions) (result *api.LimitRange, err error) {
	obj, err := c.Fake.
		Invokes(core.NewGetAction(limitrangesResource, c.ns, name), &api.LimitRange{})

	if obj == nil {
		return nil, err
	}
	return obj.(*api.LimitRange), err
}

func (c *FakeLimitRanges) List(opts api.ListOptions) (result *api.LimitRangeList, err error) {
	obj, err := c.Fake.
		Invokes(core.NewListAction(limitrangesResource, c.ns, opts), &api.LimitRangeList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := core.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &api.LimitRangeList{}
	for _, item := range obj.(*api.LimitRangeList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested limitRanges.
func (c *FakeLimitRanges) Watch(opts api.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(core.NewWatchAction(limitrangesResource, c.ns, opts))

}

// Patch applies the patch and returns the patched limitRange.
func (c *FakeLimitRanges) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *api.LimitRange, err error) {
	obj, err := c.Fake.
		Invokes(core.NewPatchSubresourceAction(limitrangesResource, c.ns, name, data, subresources...), &api.LimitRange{})

	if obj == nil {
		return nil, err
	}
	return obj.(*api.LimitRange), err
}

redpajama_set_name: RedPajamaGithub


text:
#include "extensions/tracers/zipkin/span_context_extractor.h"

#include "common/common/assert.h"
#include "common/common/utility.h"

#include "extensions/tracers/zipkin/span_context.h"
#include "extensions/tracers/zipkin/zipkin_core_constants.h"

namespace Envoy {
namespace Extensions {
namespace Tracers {
namespace Zipkin {
namespace {
constexpr int FormatMaxLength = 32 + 1 + 16 + 3 + 16; // traceid128-spanid-1-parentid
bool validSamplingFlags(char c) {
  if (c == '1' || c == '0' || c == 'd') {
    return true;
  }
  return false;
}

bool getSamplingFlags(char c, const Tracing::Decision tracing_decision) {
  if (validSamplingFlags(c)) {
    return c == '0' ? false : true;
  } else {
    return tracing_decision.traced;
  }
}

} // namespace

SpanContextExtractor::SpanContextExtractor(Http::HeaderMap& request_headers)
    : request_headers_(request_headers) {}

SpanContextExtractor::~SpanContextExtractor() = default;

bool SpanContextExtractor::extractSampled(const Tracing::Decision tracing_decision) {
  bool sampled(false);
  auto b3_header_entry = request_headers_.get(ZipkinCoreConstants::get().B3);
  if (b3_header_entry) {
    absl::string_view b3 = b3_header_entry->value().getStringView();
    int sampled_pos = 0;
    switch (b3.length()) {
    case 1:
      break;
    case 35: // 16 + 1 + 16 + 2
      sampled_pos = 34;
      break;
    case 51: // 32 + 1 + 16 + 2
      sampled_pos = 50;
      break;
    case 52: // 16 + 1 + 16 + 2 + 1 + 16
      sampled_pos = 34;
      break;
    case 68: // 32 + 1 + 16 + 2 + 1 + 16
      sampled_pos = 50;
      break;
    default:
      return tracing_decision.traced;
    }
    return getSamplingFlags(b3[sampled_pos], tracing_decision);
  }

  auto x_b3_sampled_entry = request_headers_.get(ZipkinCoreConstants::get().X_B3_SAMPLED);
  if (!x_b3_sampled_entry) {
    return tracing_decision.traced;
  }
  // Checking if sampled flag has been specified. Also checking for 'true' value, as some old
  // zipkin tracers may still use that value, although should be 0 or 1.
  absl::string_view xb3_sampled = x_b3_sampled_entry->value().getStringView();
  sampled = xb3_sampled == SAMPLED || xb3_sampled == "true";
  return sampled;
}

std::pair<SpanContext, bool> SpanContextExtractor::extractSpanContext(bool is_sampled) {
  if (request_headers_.get(ZipkinCoreConstants::get().B3)) {
    return extractSpanContextFromB3SingleFormat(is_sampled);
  }
  uint64_t trace_id(0);
  uint64_t trace_id_high(0);
  uint64_t span_id(0);
  uint64_t parent_id(0);

  auto b3_trace_id_entry = request_headers_.get(ZipkinCoreConstants::get().X_B3_TRACE_ID);
  auto b3_span_id_entry = request_headers_.get(ZipkinCoreConstants::get().X_B3_SPAN_ID);
  if (b3_span_id_entry && b3_trace_id_entry) {
    // Extract trace id - which can either be 128 or 64 bit. For 128 bit,
    // it needs to be divided into two 64 bit numbers (high and low).
    const std::string tid(b3_trace_id_entry->value().getStringView());
    if (b3_trace_id_entry->value().size() == 32) {
      const std::string high_tid = tid.substr(0, 16);
      const std::string low_tid = tid.substr(16, 16);
      if (!StringUtil::atoull(high_tid.c_str(), trace_id_high, 16) ||
          !StringUtil::atoull(low_tid.c_str(), trace_id, 16)) {
        throw ExtractorException(
            fmt::format("Invalid traceid_high {} or tracid {}", high_tid.c_str(), low_tid.c_str()));
      }
    } else if (!StringUtil::atoull(tid.c_str(), trace_id, 16)) {
      throw ExtractorException(absl::StrCat("Invalid trace_id ", tid.c_str()));
    }

    const std::string spid(b3_span_id_entry->value().getStringView());
    if (!StringUtil::atoull(spid.c_str(), span_id, 16)) {
      throw ExtractorException(absl::StrCat("Invalid span id ", spid.c_str()));
    }

    auto b3_parent_id_entry = request_headers_.get(ZipkinCoreConstants::get().X_B3_PARENT_SPAN_ID);
    if (b3_parent_id_entry && !b3_parent_id_entry->value().empty()) {
      const std::string pspid(b3_parent_id_entry->value().getStringView());
      if (!StringUtil::atoull(pspid.c_str(), parent_id, 16)) {
        throw ExtractorException(absl::StrCat("Invalid parent span id ", pspid.c_str()));
      }
    }
  } else {
    return {SpanContext(), false};
  }

  return {SpanContext(trace_id_high, trace_id, span_id, parent_id, is_sampled), true};
}

std::pair<SpanContext, bool>
SpanContextExtractor::extractSpanContextFromB3SingleFormat(bool is_sampled) {
  auto b3_head_entry = request_headers_.get(ZipkinCoreConstants::get().B3);
  ASSERT(b3_head_entry);
  const std::string b3(b3_head_entry->value().getStringView());
  if (!b3.length()) {
    throw ExtractorException("Invalid input: empty");
  }

  if (b3.length() == 1) { // possibly sampling flags
    if (validSamplingFlags(b3[0])) {
      return std::pair<SpanContext, bool>(SpanContext(), false);
    }
    throw ExtractorException(fmt::format("Invalid input: invalid sampling flag {}", b3[0]));
  }

  if (b3.length() < 16 + 1 + 16 /* traceid64-spanid */) {
    throw ExtractorException("Invalid input: truncated");
  } else if (b3.length() > FormatMaxLength) {
    throw ExtractorException("Invalid input: too long");
  }

  uint64_t trace_id(0);
  uint64_t trace_id_high(0);
  uint64_t span_id(0);
  uint64_t parent_id(0);

  uint64_t pos = 0;

  const std::string trace_id_str = b3.substr(pos, 16);
  if (b3[pos + 32] == '-') {
    if (!StringUtil::atoull(trace_id_str.c_str(), trace_id_high, 16)) {
      throw ExtractorException(
          fmt::format("Invalid input: invalid trace id high {}", trace_id_str.c_str()));
    }
    pos += 16;
    const std::string trace_id_low_str = b3.substr(pos, 16);
    if (!StringUtil::atoull(trace_id_low_str.c_str(), trace_id, 16)) {
      throw ExtractorException(
          fmt::format("Invalid input: invalid trace id {}", trace_id_low_str.c_str()));
    }
  } else {
    if (!StringUtil::atoull(trace_id_str.c_str(), trace_id, 16)) {
      throw ExtractorException(
          fmt::format("Invalid input: invalid trace id {}", trace_id_str.c_str()));
    }
  }

  pos += 16; // traceId ended
  if (!(b3[pos++] == '-')) {
    throw ExtractorException("Invalid input: not exists span id");
  }

  const std::string span_id_str = b3.substr(pos, 16);
  if (!StringUtil::atoull(span_id_str.c_str(), span_id, 16)) {
    throw ExtractorException(fmt::format("Invalid input: invalid span id {}", span_id_str.c_str()));
  }
  pos += 16; // spanId ended

  if (b3.length() > pos) {
    // If we are at this point, we have more than just traceId-spanId.
    // If the sampling field is present, we'll have a delimiter 2 characters from now. Ex "-1"
    // If it is absent, but a parent ID is (which is strange), we'll have at least 17 characters.
    // Therefore, if we have less than two characters, the input is truncated.
    if (b3.length() == (pos + 1)) {
      throw ExtractorException("Invalid input: truncated");
    }

    if (!(b3[pos++] == '-')) {
      throw ExtractorException("Invalid input: not exists sampling field");
    }

    // If our position is at the end of the string, or another delimiter is one character past our
    // position, try to read sampled status.
    if (b3.length() == pos + 1 || ((b3.length() >= pos + 2) && (b3[pos + 1] == '-'))) {
      if (!validSamplingFlags(b3[pos])) {
        throw ExtractorException(fmt::format("Invalid input: invalid sampling flag {}", b3[pos]));
      }
      pos++; // consume the sampled status
    } else {
      throw ExtractorException("Invalid input: truncated");
    }

    if (b3.length() > pos) {
      // If we are at this point, we should have a parent ID, encoded as "-[0-9a-f]{16}"
      if (b3.length() != pos + 17) {
        throw ExtractorException("Invalid input: truncated");
      }

      ASSERT(b3[pos] == '-');
      pos++;

      const std::string parent_id_str = b3.substr(pos, b3.length() - pos);
      if (!StringUtil::atoull(parent_id_str.c_str(), parent_id, 16)) {
        throw ExtractorException(
            fmt::format("Invalid input: invalid parent id {}", parent_id_str.c_str()));
      }
    }
  }

  return {SpanContext(trace_id_high, trace_id, span_id, parent_id, is_sampled), true};
}

} // namespace Zipkin
} // namespace Tracers
} // namespace Extensions
} // namespace Envoy


text:
package org.jenkinsci.plugins.openconnect;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OpenConnectStream extends BufferedInputStream implements Runnable {

	private Pattern invalidCertPattern = Pattern.compile("Certificate from VPN server \".*?\" failed verification.");
	private Pattern usernamePattern = Pattern.compile("Username:");
	private Pattern passwordPattern = Pattern.compile("Password:");
	private Pattern connectedPattern = Pattern.compile("Established DTLS connection");
	private Pattern pidPattern = Pattern.compile("Continuing in background; pid (\\d+)");
	private String pid;
	private boolean terminate;
    private static final String className = OpenConnectStream.class.getName();
    private static Logger log = Logger.getLogger(className);

	public OpenConnectStream(InputStream inputStream) {
		super(inputStream);
	}

	@Override
	public void run() {
		try {
			byte[] data = new byte[4096];
			while(!terminate) {
				int available = available();
				if(available > 0) {
					if(read(data,0,available) != -1) {
						processData(new String(data,0,available));
					}
				} else {
					Thread.sleep(300); //sleep to reduce CPU cycles
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
			log.severe("Stream shutdown unexpectedly: "+e.getMessage());
		}
	}

	private void processData(String data) {
		log.info(data);
		OpenConnect process = OpenConnect.getInstance();
		Matcher invalidCertMatcher = invalidCertPattern.matcher(data);
		if(invalidCertMatcher.find()) {
			log.warning("Invalid certificate found, shutting down");
			OpenConnect.getInstance().disconnect();
			return;
		}
		Matcher usernameMatcher = usernamePattern.matcher(data);
		if(usernameMatcher.find()) {
			process.writeString(process.getUsername()+"\n");
			return;
		}
		Matcher passwordMatcher = passwordPattern.matcher(data);
		if(passwordMatcher.find()) {
			process.writeString(process.getPassword()+"\n");
			return;
		}
		Matcher pidMatcher = pidPattern.matcher(data);
		if(pidMatcher.find()) {
			pid = pidMatcher.group(1);
			process.setProcessId(pid);
			process.setConnected(true);
		}
		Matcher connectedMatcher = connectedPattern.matcher(data);
		if(connectedMatcher.find()) {
			process.setConnected(true);
		}
	}

	public void terminate() {
		this.terminate = true;
	}

}


text:
#include "base/polygraph.h"

#include "xstd/Rnd.h"
#include "xstd/gadgets.h"
#include "base/ConnCloseStat.h"
#include "runtime/ConnIdx.h"
#include "runtime/ConnMgr.h"
#include "runtime/ErrorMgr.h"
#include "runtime/BcastSender.h"
#include "runtime/polyBcastChannels.h"
#include "runtime/polyErrors.h"
#include "runtime/globals.h"

ObjFarm<Connection> ConnMgr::TheConnFarm;
ConnIdx ConnMgr::TheConnIdx;

ConnMgr::ConnMgr(): thePconnUseLmt(0), theSslCtx(0), theConnLvl(0) {
	// init static arrays (could init more than once, but that's ok)
	TheConnFarm.limit(Socket::TheMaxLevel+1);
	TheConnIdx.fdLimit(Socket::TheMaxLevel+1);
}

void ConnMgr::configure(const SockOpt &anOpt, RndDistr *aPconnUseLmt) {
	Assert(!thePconnUseLmt);
	thePconnUseLmt = aPconnUseLmt;
	theSockOpt = anOpt;
}

void ConnMgr::configureSsl(SslCtx *aCtx, const SslWrap *) {
	Assert(!theSslCtx);
	theSslCtx = aCtx;
}

void ConnMgr::idleTimeout(Time aTout) {
	theIdleTimeout = aTout;
}

void ConnMgr::put(Connection *conn) {
	conn->finishUse();

	// ignore if somebody is still using this connection
	if (conn->inUse())
		return;

	TheConnIdx.check(conn);

	// see if we want to keep this connection open
	if (conn->reusable())
		putIdle(conn); // may close due to external limits
	else
		closeBusy(conn);
}

// adds freshly opened connection
void ConnMgr::opened(Connection *conn) {
	conn->mgr(this);
	TheConnIdx.add(conn);
	setUseLimit(conn);
	theConnLvl++;
}

void ConnMgr::setUseLimit(Connection *conn) {
	int limit = 1; // no pconns by default
	if (thePconnUseLmt)
		limit = Max(1, (int)thePconnUseLmt->trial());
	conn->useCountLimit(limit);
}

void ConnMgr::putIdle(Connection *conn) {
	// start waiting for a foreign close
	if (theIdleTimeout >= 0)
		conn->theRd.start(this, theIdleTimeout);
	else
		conn->theRd.start(this);
	TheFileScanner->setPriority(conn->sock().fd(), fsupBestEffort);
	Broadcast(TheConnIdleBegChannel, conn);
}

void ConnMgr::endedIdle(Connection *conn) {
	Broadcast(TheConnIdleEndChannel, conn);
}

void ConnMgr::closeIdle(Connection *conn, CloseKind ck) {
	conn->closeKind(ck);
	delIdle(conn); // must go before endedIdle() to sync CltConnMgr::theIdle*
	endedIdle(conn); // may Broadcast(), end test, and trigger closeAllIdle()
	closeBeg(conn);
}

void ConnMgr::closeBusy(Connection *conn) {
	conn->closeKind(ConnCloseStat::ckBusy);
	closeBeg(conn);
}

void ConnMgr::closePrep(Connection *) {
}

// start closing a connection
// may take a while if conenction needs to negotiate closing (e.g., SSL)
void ConnMgr::closeBeg(Connection *conn) {
	closePrep(conn);
	closeCont(conn);
}

void ConnMgr::closeCont(Connection *conn) {
	bool fatal = false;
	if (conn->closeAsync(this, fatal))
		closeEnd(conn);
	else
	if (fatal)
		closeEnd(conn);
	else
		TheFileScanner->setTimeout(conn->fd(), theIdleTimeout); // wait for I/O
}

void ConnMgr::closeEnd(Connection *conn) {
	TheConnIdx.del(conn);
	conn->closeNow();
	TheConnFarm.put(conn);
	theConnLvl--;
}

// this may be called for in-closing connections only
void ConnMgr::noteReadReady(int fd) {
	Connection *conn = TheConnIdx[fd];
	Assert(conn);
	TheConnIdx.check(conn);
	closeCont(conn);
}

// this may be called for in-closing connections only
void ConnMgr::noteWriteReady(int fd) {
	Connection *conn = TheConnIdx[fd];
	Assert(conn);
	TheConnIdx.check(conn);
	closeCont(conn);
}

void ConnMgr::noteTimeout(int fd, Time) {
	Connection *conn = TheConnIdx[fd];
	Assert(conn);
	if (conn->closing()) {
		ReportError2(errSslCloseTout, conn->logCat());
		conn->bad(true);
		closeEnd(conn);
	} else {
		conn->theRd.stop(this);
		closeIdle(conn, ConnCloseStat::ckIdleLocal);
	}
}


text:
import junit.framework.TestCase;

public class BookJavaTest extends TestCase {

    public void testOpen() {
        new Book().open();
    }

}


text:
#include <algorithm>
#include <queue>
#include <set>
#include <vector>
using namespace std;

/*
Solution 1: see comments.

Time complexity: O(n log n + d(n log n)) [where n is the length of events]
Space complexity: O(n)
*/

class Solution
{
    public:
        int maxEvents(vector<vector<int>> & events)
        {
            int result=0;

            int n=events.size();

            //Sort the events based on starting time O(n log n)
            sort(begin(events), end(events), [] (auto & lhs, auto & rhs) {return lhs[0] < rhs[0];});

            int index=0;

            //Min heap to store ending times of events
            //The earliest ending time will be on top of the heap
            priority_queue<int, vector<int>, greater<int>> minHeap;

            for(int day=1;day<100001;day++)
            {
                //Remove ending times of events that ended before the current day
                while(!minHeap.empty() && minHeap.top() < day)
                {
                    minHeap.pop();
                }

                //Add all the ending times of events that start on the current day
                while(index < n && events[index][0]==day)
                {
                    minHeap.emplace(events[index][1]);

                    index++;
                }

                //If the min heap is not empty, that means that there is at least one event that starts on the curren day that we can attend
                //Since we can only attend one event per day, attend the event that ends the soonest so we can attend other events on other days
                if(!minHeap.empty())
                {
                    minHeap.pop();

                    result++;
                }
            }

            return result;
        }
};

/*
Solution 2: see comments.

Time complexity: O(n log n + d(n log n)) [where n is the length of events]
Space complexity: O(n)
*/

class Solution
{
    public:
        int maxEvents(vector<vector<int>> & events)
        {
            int result=0;

            int n=events.size();

            //Sort the events based on starting time O(n log n)
            sort(begin(events), end(events), [] (auto & lhs, auto & rhs) {return lhs[0] < rhs[0];});

            int index=0;

            //Min heap to store ending times of events
            //The earliest ending time will be on top of the heap
            multiset<int> minHeap;

            for(int day=1;day<100001;day++)
            {
                //Remove ending times of events that ended before the current day
                while(!minHeap.empty() && *(begin(minHeap)) < day)
                {
                    minHeap.erase(begin(minHeap));
                }

                //Add all the ending times of events that start on the current day
                while(index < n && events[index][0]==day)
                {
                    minHeap.insert(events[index][1]);

                    index++;
                }

                //If the min heap is not empty, that means that there is at least one event that starts on the curren day that we can attend
                //Since we can only attend one event per day, attend the event that ends the soonest so we can attend other events on other days
                if(!minHeap.empty())
                {
                    minHeap.erase(begin(minHeap));

                    result++;
                }
            }

            return result;
        }
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <meta charset="ISO-8859-1">

    <title>Login</title>

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

    <link rel="stylesheet" type="text/css" href="../css/index.css">
    <link href="../css/criarLogin.css" rel="stylesheet">
    <link href="../css/stylish-portfolio.css" rel="stylesheet">

    <link href="../css/stylish-portfolio.css" rel="stylesheet">

    <link href="../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

            Menu 01

            Menu 02

            Menu 03

            Menu 04

            Menu 05

            <legend> Registre-se!</legend>
            <form action="#" method="post" class="form" role="form">

                        <input class="form-control" name="firstname" placeholder="Primeiro Nome" type="text"
                               required autofocus />

                        <input class="form-control" name="lastname" placeholder="Último Nome" type="text" required />

                <input class="form-control" name="youremail" placeholder="Seu email" type="email" />
                <input class="form-control" name="reenteremail" placeholder="Confirme seu email" type="email" />
                <input class="form-control" name="cpf" placeholder="Informe seu CPF" />
                <input class="form-control" name="carteira" placeholder="Informe numero da carteira do plano" />
                <input class="form-control" name="password" placeholder="Senha" type="password" />
                <input class="form-control" name="password" placeholder="Confirmar senha" type="password" />

                    Data de Nascimento

                        <select class="form-control">
                            <option>Dia</option>
                            <?php for($i=1; $i<=31; $i++){ echo "<option value='$i'>$i</option>";} ?>
                        </select>

                        <select class="form-control">
                            <option>Mês</option>
                            <option value="Janeiro">Janeiro</option>
                            <option value="Fevereiro">Fevereiro</option>
                            <option value="Março">Março</option>
                            <option value="Abril">Abril</option>
                            <option value="Maio">Maio</option>
                            <option value="Junho">Junho</option>
                            <option value="Julho">Julho</option>
                            <option value="Agosto">Agosto</option>
                            <option value="Setembro">Setembro</option>
                            <option value="Outubro">Outubro</option>
                            <option value="Novembro">Novembro</option>
                            <option value="Dezembro">Dezembro</option>
                        </select>

                        <select class="form-control">
                            <option>Ano</option>
                            <?php $year = date("Y"); while ($year > 1899) {
                            echo '<option value="'.$year.'">'.$year.'</option>';
                            $year = $year - '1';}
                            ?>
                        </select>

                    <input type="radio" name="sex" id="inlineCheckbox1" value="masculino" />
                    Masculino

                    <input type="radio" name="sex" id="inlineCheckbox2" value="feminino" />
                    Feminino

                <button class="btn btn-lg btn-primary btn-block" type="submit">
                    Cadastrar</button>
            </form>


text:
using testing::_;
using testing::AnyNumber;
using testing::InSequence;

namespace quic {
namespace test {

class MockStream : public QuicStreamSequencer::StreamInterface {
 public:
  MOCK_METHOD0(OnFinRead, void());
  MOCK_METHOD0(OnDataAvailable, void());
  MOCK_METHOD2(CloseConnectionWithDetails,
               void(QuicErrorCode error, const QuicString& details));
  MOCK_METHOD1(Reset, void(QuicRstStreamErrorCode error));
  MOCK_METHOD0(OnCanWrite, void());
  MOCK_METHOD1(AddBytesConsumed, void(QuicByteCount bytes));

  QuicStreamId id() const override { return 1; }

  const QuicSocketAddress& PeerAddressOfLatestPacket() const override {
    return peer_address_;
  }

 protected:
  QuicSocketAddress peer_address_ =
      QuicSocketAddress(QuicIpAddress::Any4(), 65535);
};

namespace {

static const char kPayload[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

class QuicStreamSequencerTest : public QuicTest {
 public:
  void ConsumeData(size_t num_bytes) {
    char buffer[1024];
    ASSERT_GT(QUIC_ARRAYSIZE(buffer), num_bytes);
    struct IOVEC iov;
    iov.iov_base = buffer;
    iov.iov_len = num_bytes;
    ASSERT_EQ(static_cast<int>(num_bytes), sequencer_->Readv(&iov, 1));
  }

 protected:
  QuicStreamSequencerTest()
      : stream_(), sequencer_(new QuicStreamSequencer(&stream_)) {}

  // Verify that the data in first region match with the expected[0].
  bool VerifyReadableRegion(const std::vector<QuicString>& expected) {
    return VerifyReadableRegion(*sequencer_, expected);
  }

  // Verify that the data in each of currently readable regions match with each
  // item given in |expected|.
  bool VerifyReadableRegions(const std::vector<QuicString>& expected) {
    return VerifyReadableRegions(*sequencer_, expected);
  }

  bool VerifyIovecs(IOVEC* IOVECs,
                    size_t num_IOVECs,
                    const std::vector<QuicString>& expected) {
    return VerifyIovecs(*sequencer_, IOVECs, num_IOVECs, expected);
  }

  bool VerifyReadableRegion(const QuicStreamSequencer& sequencer,
                            const std::vector<QuicString>& expected) {
    IOVEC IOVECs[1];
    if (sequencer.GetReadableRegions(IOVECs, 1)) {
      return (VerifyIovecs(sequencer, IOVECs, 1,
                           std::vector<QuicString>{expected[0]}));
    }
    return false;
  }

  // Verify that the data in each of currently readable regions match with each
  // item given in |expected|.
  bool VerifyReadableRegions(const QuicStreamSequencer& sequencer,
                             const std::vector<QuicString>& expected) {
    IOVEC IOVECs[5];
    size_t num_IOVECs =
        sequencer.GetReadableRegions(IOVECs, QUIC_ARRAYSIZE(IOVECs));
    return VerifyReadableRegion(sequencer, expected) &&
           VerifyIovecs(sequencer, IOVECs, num_IOVECs, expected);
  }

  bool VerifyIovecs(const QuicStreamSequencer& sequencer,
                    IOVEC* IOVECs,
                    size_t num_IOVECs,
                    const std::vector<QuicString>& expected) {
    int start_position = 0;
    for (size_t i = 0; i < num_IOVECs; ++i) {
      if (!VerifyIovec(IOVECs[i],
                       expected[0].substr(start_position, IOVECs[i].iov_len))) {
        return false;
      }
      start_position += IOVECs[i].iov_len;
    }
    return true;
  }

  bool VerifyIovec(const IOVEC& IOVEC, QuicStringPiece expected) {
    if (IOVEC.iov_len != expected.length()) {
      QUIC_LOG(ERROR) << "Invalid length: " << IOVEC.iov_len << " vs "
                      << expected.length();
      return false;
    }
    if (memcmp(IOVEC.iov_base, expected.data(), expected.length()) !=
        0) {
      QUIC_LOG(ERROR) << "Invalid data: " << static_cast<char*>(IOVEC.iov_base)
                      << " vs " << expected;
      return false;
    }
    return true;
  }

  void OnFinFrame(QuicStreamOffset byte_offset, const char* data) {
    QuicStreamFrame frame;
    frame.stream_id = 1;
    frame.offset = byte_offset;
    frame.data_buffer = data;
    frame.data_length = strlen(data);
    frame.fin = true;
    sequencer_->OnStreamFrame(frame);
  }

  void OnFrame(QuicStreamOffset byte_offset, const char* data) {
    QuicStreamFrame frame;
    frame.stream_id = 1;
    frame.offset = byte_offset;
    frame.data_buffer = data;
    frame.data_length = strlen(data);
    frame.fin = false;
    sequencer_->OnStreamFrame(frame);
  }

  size_t NumBufferedBytes() {
    return QuicStreamSequencerPeer::GetNumBufferedBytes(sequencer_.get());
  }

  testing::StrictMock<MockStream> stream_;
  std::unique_ptr<QuicStreamSequencer> sequencer_;
};

// TODO(rch): reorder these tests so they build on each other.

TEST_F(QuicStreamSequencerTest, RejectOldFrame) {
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));

  OnFrame(0, "abc");

  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
  // Ignore this - it matches a past packet number and we should not see it
  // again.
  OnFrame(0, "def");
  EXPECT_EQ(0u, NumBufferedBytes());
}

TEST_F(QuicStreamSequencerTest, RejectBufferedFrame) {
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());

  // Ignore this - it matches a buffered frame.
  // Right now there's no checking that the payload is consistent.
  OnFrame(0, "def");
  EXPECT_EQ(3u, NumBufferedBytes());
}

TEST_F(QuicStreamSequencerTest, FullFrameConsumed) {
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));

  OnFrame(0, "abc");
  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) {
  sequencer_->SetBlockedUntilFlush();

  OnFrame(0, "abc");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));
  sequencer_->SetUnblocked();
  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(3u, sequencer_->NumBytesConsumed());

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));
  EXPECT_FALSE(sequencer_->IsClosed());
  OnFinFrame(3, "def");
  EXPECT_TRUE(sequencer_->IsClosed());
}

TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) {
  sequencer_->SetBlockedUntilFlush();

  OnFinFrame(0, "abc");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));
  EXPECT_FALSE(sequencer_->IsClosed());
  sequencer_->SetUnblocked();
  EXPECT_TRUE(sequencer_->IsClosed());
  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, EmptyFrame) {
  EXPECT_CALL(stream_,
              CloseConnectionWithDetails(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _));
  OnFrame(0, "");
  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, EmptyFinFrame) {
  EXPECT_CALL(stream_, OnDataAvailable());
  OnFinFrame(0, "");
  EXPECT_EQ(0u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, PartialFrameConsumed) {
  EXPECT_CALL(stream_, AddBytesConsumed(2));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(2);
  }));

  OnFrame(0, "abc");
  EXPECT_EQ(1u, NumBufferedBytes());
  EXPECT_EQ(2u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, NextxFrameNotConsumed) {
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, FutureFrameNotProcessed) {
  OnFrame(3, "abc");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}

TEST_F(QuicStreamSequencerTest, OutOfOrderFrameProcessed) {
  // Buffer the first
  OnFrame(6, "ghi");
  EXPECT_EQ(3u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
  // Buffer the second
  OnFrame(3, "def");
  EXPECT_EQ(6u, NumBufferedBytes());
  EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(6u, sequencer_->NumBytesBuffered());

  EXPECT_CALL(stream_, AddBytesConsumed(9));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(9);
  }));

  // Now process all of them at once.
  OnFrame(0, "abc");
  EXPECT_EQ(9u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());

  EXPECT_EQ(0u, NumBufferedBytes());
}

TEST_F(QuicStreamSequencerTest, BasicHalfCloseOrdered) {
  InSequence s;

  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  OnFinFrame(0, "abc");

  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
}

TEST_F(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) {
  OnFinFrame(6, "");
  EXPECT_EQ(6u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  OnFrame(3, "def");
  EXPECT_CALL(stream_, AddBytesConsumed(6));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(6);
  }));
  EXPECT_FALSE(sequencer_->IsClosed());
  OnFrame(0, "abc");
  EXPECT_TRUE(sequencer_->IsClosed());
}

TEST_F(QuicStreamSequencerTest, BasicHalfUnordered) {
  OnFinFrame(3, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() {
    ConsumeData(3);
  }));
  EXPECT_FALSE(sequencer_->IsClosed());
  OnFrame(0, "abc");
  EXPECT_TRUE(sequencer_->IsClosed());
}

TEST_F(QuicStreamSequencerTest, TerminateWithReadv) {
  char buffer[3];

  OnFinFrame(3, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  EXPECT_FALSE(sequencer_->IsClosed());

  EXPECT_CALL(stream_, OnDataAvailable());
  OnFrame(0, "abc");

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  IOVEC iov = {&buffer[0], 3};
  int bytes_read = sequencer_->Readv(&iov, 1);
  EXPECT_EQ(3, bytes_read);
  EXPECT_TRUE(sequencer_->IsClosed());
}

TEST_F(QuicStreamSequencerTest, MutipleOffsets) {
  OnFinFrame(3, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  EXPECT_CALL(stream_, Reset(QUIC_MULTIPLE_TERMINATION_OFFSETS));
  OnFinFrame(5, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  EXPECT_CALL(stream_, Reset(QUIC_MULTIPLE_TERMINATION_OFFSETS));
  OnFinFrame(1, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));

  OnFinFrame(3, "");
  EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
}

class QuicSequencerRandomTest : public QuicStreamSequencerTest {
 public:
  typedef std::pair<int, QuicString> Frame;
  typedef std::vector<Frame> FrameList;

  void CreateFrames() {
    int payload_size = QUIC_ARRAYSIZE(kPayload) - 1;
    int remaining_payload = payload_size;
    while (remaining_payload != 0) {
      int size = std::min(OneToN(6), remaining_payload);
      int index = payload_size - remaining_payload;
      list_.push_back(
          std::make_pair(index, QuicString(kPayload + index, size)));
      remaining_payload -= size;
    }
  }

  QuicSequencerRandomTest() {
    uint64_t seed = QuicRandom::GetInstance()->RandUint64();
    QUIC_LOG(INFO) << "**** The current seed is " << seed << " ****";
    random_.set_seed(seed);

    CreateFrames();
  }

  int OneToN(int n) { return random_.RandUint64() % n + 1; }

  void ReadAvailableData() {
    // Read all available data
    char output[QUIC_ARRAYSIZE(kPayload) + 1];
    IOVEC iov;
    iov.iov_base = output;
    iov.iov_len = QUIC_ARRAYSIZE(output);
    int bytes_read = sequencer_->Readv(&iov, 1);
    EXPECT_NE(0, bytes_read);
    output_.append(output, bytes_read);
  }

  QuicString output_;
  // Data which peek at using GetReadableRegion if we back up.
  QuicString peeked_;
  SimpleRandom random_;
  FrameList list_;
};

// All frames are processed as soon as we have sequential data.
// Infinite buffering, so all frames are acked right away.
TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) {
  EXPECT_CALL(stream_, OnDataAvailable())
      .Times(AnyNumber())
      .WillRepeatedly(
          Invoke(this, &QuicSequencerRandomTest::ReadAvailableData));
  QuicByteCount total_bytes_consumed = 0;
  EXPECT_CALL(stream_, AddBytesConsumed(_))
      .Times(AnyNumber())
      .WillRepeatedly(
          testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) {
            total_bytes_consumed += bytes;
          }));

  while (!list_.empty()) {
    int index = OneToN(list_.size()) - 1;
    QUIC_LOG(ERROR) << "Sending index " << index << " " << list_[index].second;
    OnFrame(list_[index].first, list_[index].second.data());

    list_.erase(list_.begin() + index);
  }

  ASSERT_EQ(QUIC_ARRAYSIZE(kPayload) - 1, output_.size());
  EXPECT_EQ(kPayload, output_);
  EXPECT_EQ(QUIC_ARRAYSIZE(kPayload) - 1, total_bytes_consumed);
}

TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) {
  char buffer[10];
  IOVEC iov[2];
  iov[0].iov_base = &buffer[0];
  iov[0].iov_len = 5;
  iov[1].iov_base = &buffer[5];
  iov[1].iov_len = 5;

  EXPECT_CALL(stream_, OnDataAvailable()).Times(AnyNumber());
  QuicByteCount total_bytes_consumed = 0;
  EXPECT_CALL(stream_, AddBytesConsumed(_))
      .Times(AnyNumber())
      .WillRepeatedly(
          testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) {
            total_bytes_consumed += bytes;
          }));

  while (output_.size() != QUIC_ARRAYSIZE(kPayload) - 1) {
    if (!list_.empty() && OneToN(2) == 1) {  // Send data
      int index = OneToN(list_.size()) - 1;
      OnFrame(list_[index].first, list_[index].second.data());
      list_.erase(list_.begin() + index);
    } else {  // Read data
      bool has_bytes = sequencer_->HasBytesToRead();
      IOVEC peek_iov[20];
      int iovs_peeked = sequencer_->GetReadableRegions(peek_iov, 20);
      if (has_bytes) {
        ASSERT_LT(0, iovs_peeked);
        ASSERT_TRUE(sequencer_->GetReadableRegion(peek_iov));
      } else {
        ASSERT_EQ(0, iovs_peeked);
        ASSERT_FALSE(sequencer_->GetReadableRegion(peek_iov));
      }
      int total_bytes_to_peek = QUIC_ARRAYSIZE(buffer);
      for (int i = 0; i < iovs_peeked; ++i) {
        int bytes_to_peek =
            std::min<int>(peek_iov[i].iov_len, total_bytes_to_peek);
        peeked_.append(static_cast<char*>(peek_iov[i].iov_base), bytes_to_peek);
        total_bytes_to_peek -= bytes_to_peek;
        if (total_bytes_to_peek == 0) {
          break;
        }
      }
      int bytes_read = sequencer_->Readv(iov, 2);
      output_.append(buffer, bytes_read);
      ASSERT_EQ(output_.size(), peeked_.size());
    }
  }
  EXPECT_EQ(QuicString(kPayload), output_);
  EXPECT_EQ(QuicString(kPayload), peeked_);
  EXPECT_EQ(QUIC_ARRAYSIZE(kPayload) - 1, total_bytes_consumed);
}

// Same as above, just using a different method for reading.
TEST_F(QuicStreamSequencerTest, MarkConsumed) {
  InSequence s;
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  OnFrame(3, "def");
  OnFrame(6, "ghi");

  // abcdefghi buffered.
  EXPECT_EQ(9u, sequencer_->NumBytesBuffered());

  // Peek into the data.
  std::vector<QuicString> expected = {"abcdefghi"};
  ASSERT_TRUE(VerifyReadableRegions(expected));

  // Consume 1 byte.
  EXPECT_CALL(stream_, AddBytesConsumed(1));
  sequencer_->MarkConsumed(1);
  // Verify data.
  std::vector<QuicString> expected2 = {"bcdefghi"};
  ASSERT_TRUE(VerifyReadableRegions(expected2));
  EXPECT_EQ(8u, sequencer_->NumBytesBuffered());

  // Consume 2 bytes.
  EXPECT_CALL(stream_, AddBytesConsumed(2));
  sequencer_->MarkConsumed(2);
  // Verify data.
  std::vector<QuicString> expected3 = {"defghi"};
  ASSERT_TRUE(VerifyReadableRegions(expected3));
  EXPECT_EQ(6u, sequencer_->NumBytesBuffered());

  // Consume 5 bytes.
  EXPECT_CALL(stream_, AddBytesConsumed(5));
  sequencer_->MarkConsumed(5);
  // Verify data.
  std::vector<QuicString> expected4{"i"};
  ASSERT_TRUE(VerifyReadableRegions(expected4));
  EXPECT_EQ(1u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, MarkConsumedError) {
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  OnFrame(9, "jklmnopqrstuvwxyz");

  // Peek into the data.  Only the first chunk should be readable because of the
  // missing data.
  std::vector<QuicString> expected{"abc"};
  ASSERT_TRUE(VerifyReadableRegions(expected));

  // Now, attempt to mark consumed more data than was readable and expect the
  // stream to be closed.
  EXPECT_CALL(stream_, Reset(QUIC_ERROR_PROCESSING_STREAM));
  EXPECT_QUIC_BUG(sequencer_->MarkConsumed(4),
                  "Invalid argument to MarkConsumed."
                  " expect to consume: 4, but not enough bytes available.");
}

TEST_F(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) {
  InSequence s;
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  OnFrame(3, "def");
  // Missing packet: 6, ghi.
  OnFrame(9, "jkl");

  std::vector<QuicString> expected = {"abcdef"};
  ASSERT_TRUE(VerifyReadableRegions(expected));

  EXPECT_CALL(stream_, AddBytesConsumed(6));
  sequencer_->MarkConsumed(6);
}

TEST_F(QuicStreamSequencerTest, Move) {
  InSequence s;
  EXPECT_CALL(stream_, OnDataAvailable());

  OnFrame(0, "abc");
  OnFrame(3, "def");
  OnFrame(6, "ghi");

  // abcdefghi buffered.
  EXPECT_EQ(9u, sequencer_->NumBytesBuffered());

  // Peek into the data.
  std::vector<QuicString> expected = {"abcdefghi"};
  ASSERT_TRUE(VerifyReadableRegions(expected));

  QuicStreamSequencer sequencer2(std::move(*sequencer_));
  ASSERT_TRUE(VerifyReadableRegions(sequencer2, expected));
}

TEST_F(QuicStreamSequencerTest, OverlappingFramesReceived) {
  // The peer should never send us non-identical stream frames which contain
  // overlapping byte ranges - if they do, we close the connection.
  QuicStreamId id = 1;

  QuicStreamFrame frame1(id, false, 1, QuicStringPiece("hello"));
  sequencer_->OnStreamFrame(frame1);

  QuicStreamFrame frame2(id, false, 2, QuicStringPiece("hello"));
  EXPECT_CALL(stream_,
              CloseConnectionWithDetails(QUIC_OVERLAPPING_STREAM_DATA, _))
      .Times(0);
  sequencer_->OnStreamFrame(frame2);
}

TEST_F(QuicStreamSequencerTest, DataAvailableOnOverlappingFrames) {
  QuicStreamId id = 1;
  const QuicString data(1000, '.');

  // Received [0, 1000).
  QuicStreamFrame frame1(id, false, 0, data);
  EXPECT_CALL(stream_, OnDataAvailable());
  sequencer_->OnStreamFrame(frame1);
  // Consume [0, 500).
  EXPECT_CALL(stream_, AddBytesConsumed(500));
  QuicStreamSequencerTest::ConsumeData(500);
  EXPECT_EQ(500u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(500u, sequencer_->NumBytesBuffered());

  // Received [500, 1500).
  QuicStreamFrame frame2(id, false, 500, data);
  // Do not call OnDataAvailable as there are readable bytes left in the buffer.
  EXPECT_CALL(stream_, OnDataAvailable()).Times(0);
  sequencer_->OnStreamFrame(frame2);
  // Consume [1000, 1500).
  EXPECT_CALL(stream_, AddBytesConsumed(1000));
  QuicStreamSequencerTest::ConsumeData(1000);
  EXPECT_EQ(1500u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());

  // Received [1498, 1503).
  QuicStreamFrame frame3(id, false, 1498, QuicStringPiece("hello"));
  EXPECT_CALL(stream_, OnDataAvailable());
  sequencer_->OnStreamFrame(frame3);
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  QuicStreamSequencerTest::ConsumeData(3);
  EXPECT_EQ(1503u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());

  // Received [1000, 1005).
  QuicStreamFrame frame4(id, false, 1000, QuicStringPiece("hello"));
  EXPECT_CALL(stream_, OnDataAvailable()).Times(0);
  sequencer_->OnStreamFrame(frame4);
  EXPECT_EQ(1503u, sequencer_->NumBytesConsumed());
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, OnDataAvailableWhenReadableBytesIncrease) {
  sequencer_->set_level_triggered(true);
  QuicStreamId id = 1;

  // Received [0, 5).
  QuicStreamFrame frame1(id, false, 0, "hello");
  EXPECT_CALL(stream_, OnDataAvailable());
  sequencer_->OnStreamFrame(frame1);
  EXPECT_EQ(5u, sequencer_->NumBytesBuffered());

  // Without consuming the buffer bytes, continue receiving [5, 11).
  QuicStreamFrame frame2(id, false, 5, " world");
  // OnDataAvailable should still be called because there are more data to read.
  EXPECT_CALL(stream_, OnDataAvailable());
  sequencer_->OnStreamFrame(frame2);
  EXPECT_EQ(11u, sequencer_->NumBytesBuffered());

  // Without consuming the buffer bytes, continue receiving [12, 13).
  QuicStreamFrame frame3(id, false, 5, "a");
  // OnDataAvailable shouldn't be called becasue there are still only 11 bytes
  // available.
  EXPECT_CALL(stream_, OnDataAvailable()).Times(0);
  sequencer_->OnStreamFrame(frame3);
  EXPECT_EQ(11u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, ReadSingleFrame) {
  EXPECT_CALL(stream_, OnDataAvailable());
  OnFrame(0u, "abc");
  QuicString actual;
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  sequencer_->Read(&actual);
  EXPECT_EQ("abc", actual);
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, ReadMultipleFramesWithMissingFrame) {
  EXPECT_CALL(stream_, OnDataAvailable());
  OnFrame(0u, "abc");
  OnFrame(3u, "def");
  OnFrame(6u, "ghi");
  OnFrame(10u, "xyz");  // Byte 9 is missing.
  QuicString actual;
  EXPECT_CALL(stream_, AddBytesConsumed(9));
  sequencer_->Read(&actual);
  EXPECT_EQ("abcdefghi", actual);
  EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, ReadAndAppendToString) {
  EXPECT_CALL(stream_, OnDataAvailable());
  OnFrame(0u, "def");
  OnFrame(3u, "ghi");
  QuicString actual = "abc";
  EXPECT_CALL(stream_, AddBytesConsumed(6));
  sequencer_->Read(&actual);
  EXPECT_EQ("abcdefghi", actual);
  EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
}

TEST_F(QuicStreamSequencerTest, StopReading) {
  EXPECT_CALL(stream_, OnDataAvailable()).Times(0);
  EXPECT_CALL(stream_, OnFinRead());

  EXPECT_CALL(stream_, AddBytesConsumed(0));
  sequencer_->StopReading();

  EXPECT_CALL(stream_, AddBytesConsumed(3));
  OnFrame(0u, "abc");
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  OnFrame(3u, "def");
  EXPECT_CALL(stream_, AddBytesConsumed(3));
  OnFinFrame(6u, "ghi");
}

TEST_F(QuicStreamSequencerTest, StopReadingWithLevelTriggered) {
  if (GetQuicReloadableFlag(quic_stop_reading_when_level_triggered)) {
    EXPECT_CALL(stream_, AddBytesConsumed(0));
    EXPECT_CALL(stream_, AddBytesConsumed(3)).Times(3);
    EXPECT_CALL(stream_, OnDataAvailable()).Times(0);
    EXPECT_CALL(stream_, OnFinRead());
  } else {
    EXPECT_CALL(stream_, AddBytesConsumed(0));
    EXPECT_CALL(stream_, OnDataAvailable()).Times(3);
  }

  sequencer_->set_level_triggered(true);
  sequencer_->StopReading();

  OnFrame(0u, "abc");
  OnFrame(3u, "def");
  OnFinFrame(6u, "ghi");
}

}  // namespace
}  // namespace test
}  // namespace quic


text:
import pytest
from git import GitCommandError

from semantic_release.errors import GitError
from semantic_release.vcs_helpers import (checkout, commit_new_version, get_commit_log,
                                          get_current_head_hash, get_repository_owner_and_name,
                                          push_new_version, tag_new_version)

from . import mock

@pytest.fixture
def mock_git(mocker):
    return mocker.patch('semantic_release.vcs_helpers.repo.git')

def test_first_commit_is_not_initial_commit():
    assert next(get_commit_log()) != 'Initial commit'

def test_add_and_commit(mock_git):
    commit_new_version('1.0.0')
    mock_git.add.assert_called_once_with('semantic_release/__init__.py')
    mock_git.commit.assert_called_once_with(m='1.0.0', author="semantic-release <semantic-release>")

def test_tag_new_version(mock_git):
    tag_new_version('1.0.0')
    mock_git.tag.assert_called_with('-a', 'v1.0.0', m='v1.0.0')

def test_push_new_version(mock_git):
    push_new_version()
    mock_git.push.assert_has_calls([
        mock.call('origin', 'master'),
        mock.call('--tags', 'origin', 'master'),
    ])

def test_get_repository_owner_and_name():
    assert get_repository_owner_and_name()[0] == 'relekang'
    assert get_repository_owner_and_name()[1] == 'python-semantic-release'

def test_get_current_head_hash(mocker):
    mocker.patch('git.objects.commit.Commit.name_rev', 'commit-hash branch-name')
    assert get_current_head_hash() == 'commit-hash'

def test_push_should_not_print_gh_token(mock_git):
    mock_git.configure_mock(**{
        'push.side_effect': GitCommandError('gh--token', 1, b'gh--token', b'gh--token')
    })
    with pytest.raises(GitError) as excinfo:
        push_new_version(gh_token='gh--token')
    assert 'gh--token' not in str(excinfo)

def test_checkout_should_checkout_correct_branch(mock_git):
    checkout('a-branch')
    mock_git.checkout.assert_called_once_with('a-branch')


text:
<?php declare(strict_types=1);

namespace Debril\RssAtomBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DebrilRssAtomExtension extends Extension implements CompilerPassInterface
{

    /**
     * @var array
     */
    protected $defaultDateFormats = [
        \DateTime::RFC3339,
        \DateTime::RSS,
        \DateTime::W3C,
        'Y-m-d\TH:i:s.uP',
        'Y-m-d',
        'd/m/Y',
        'd M Y H:i:s P',
        'D, d M Y H:i O',
        'D, d M Y H:i:s O',
        'D M d Y H:i:s e',
    ];

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container) : void
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');

        $this->setDateFormats($container, $config);
        $container->setParameter('debril_rss_atom.public_feeds', !$config['private']);
        $container->setParameter('debril_rss_atom.force_refresh', $config['force_refresh']);
        $container->setParameter('debril_rss_atom.content_type_json', $config['content_type_json']);
        $container->setParameter('debril_rss_atom.content_type_xml', $config['content_type_xml']);
    }

    /**
     * @param ContainerBuilder $container
     * @param array $config
     * @return $this
     */
    protected function setDateFormats(ContainerBuilder $container, array $config) : self
    {
        $dateFormats = isset($config['date_formats']) ?
            array_merge($this->defaultDateFormats, $config['date_formats']):
            $this->defaultDateFormats;

        $container->setParameter(
            'debril_rss_atom.date_formats',
            $dateFormats
        );

        return $this;
    }

    /**
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container) : void
    {
        $this->setDefinition($container, 'logger', 'Psr\Log\NullLogger');
    }

    /**
     * @param ContainerBuilder $container
     * @param string $serviceName
     * @param string $className
     * @return DebrilRssAtomExtension
     */
    protected function setDefinition(ContainerBuilder $container, string $serviceName, string $className) : self
    {
        if ( ! $container->has($serviceName) ) {
            $container->setDefinition($serviceName, new Definition($className));
        }

        return $this;
    }
}


text:
package org.mdpeg.ast

sealed trait Target
final case class Ref(label:Seq[Inline], ref: String) extends Target
final case object ShortcutRef extends Target
final case class Src(uri:String, title: Option[String]) extends Target


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/col_red" android:state_window_focused="false"/>
    <item android:drawable="@color/col_red" android:state_focused="true" android:state_pressed="true"/>
    <item android:drawable="@color/col_red" android:state_focused="false" android:state_pressed="true"/>
    <item android:drawable="@color/col_red" android:state_selected="true"/>
    <item android:drawable="@color/col_white" android:state_focused="true"/>

</selector>


text:
namespace g{namespace Fuse{struct Node;}}
namespace g{namespace Fuse{struct UserEvent;}}
namespace g{namespace Fuse{struct UserEventDispatch;}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}

namespace g{
namespace Fuse{

// public sealed class UserEvent :255
// {
::g::Fuse::Behavior_type* UserEvent_typeof();
void UserEvent__ctor_1_fn(UserEvent* __this, uString* name);
void UserEvent__get_Name_fn(UserEvent* __this, uString** __retval);
void UserEvent__set_Name_fn(UserEvent* __this, uString* value);
void UserEvent__New1_fn(uString* name, UserEvent** __retval);
void UserEvent__Raise_fn(UserEvent* __this, ::g::Uno::Collections::Dictionary* args);
void UserEvent__add_Raised_fn(UserEvent* __this, uDelegate* value);
void UserEvent__remove_Raised_fn(UserEvent* __this, uDelegate* value);
void UserEvent__RaiseEvent_fn(::g::Fuse::Node* from, uString* name, ::g::Uno::Collections::Dictionary* args);
void UserEvent__ScanTree_fn(::g::Fuse::Node* at, uString* name, ::g::Fuse::Node** node, UserEvent** __retval);

struct UserEvent : ::g::Fuse::Behavior
{
    uStrong< ::g::Fuse::UserEventDispatch*> Dispatch;
    uStrong<uString*> _Name;
    uStrong<uDelegate*> Raised1;

    void ctor_1(uString* name);
    uString* Name();
    void Name(uString* value);
    void Raise(::g::Uno::Collections::Dictionary* args);
    void add_Raised(uDelegate* value);
    void remove_Raised(uDelegate* value);
    static UserEvent* New1(uString* name);
    static void RaiseEvent(::g::Fuse::Node* from, uString* name, ::g::Uno::Collections::Dictionary* args);
    static UserEvent* ScanTree(::g::Fuse::Node* at, uString* name, ::g::Fuse::Node** node);
};
// }

}} // ::g::Fuse


text:
<img src="http://www.elao.com/images/corpo/logo_red_small.png"/>

# Ansible Role: mysql

This role will assume the setup of [mysql](https://www.mysql.com/)

It's part of the ELAO [Ansible stack](http://ansible.elao.com) but can be used as a stand alone component.

## Requirements

- Ansible 1.7.2+

## Installation

Using ansible galaxy:

```bash
ansible-galaxy install elao.mysql
```
You can add this role as a dependency for other roles by adding the role to the meta/main.yml file of your own role:

```yaml
dependencies:
  - { role: elao.mysql }
```

## Role Handlers

| Name          | Type    | Description          |
| ------------- | ------- | -------------------- |
| mysql restart | Service | Restart MySQL server |

## Role Variables

| Name                           | Default                | Type          | Description                                            |
| -----------------------------  | ---------------------- | ------------- | ------------------------------------------------------ |
| `elao_mysql_tasks_include`     | ~                      | Array         | Execute only specified tasks                           |
| `elao_mysql_tasks_exlude`      | [ ]                    | Array         | Exclude tasks (install, configs, services)             |
| `elao_mysql_configs_dir`       | /etc/mysql/conf.d      | String (path) | Configurations directory path                          |
| `elao_mysql_configs_template`  | configs/default.cnf.j2 | String (path) | Default configuration template                         |
| `elao_mysql_configs_exclusive` | false                  | Boolean       | Whether to remove all other non-specified config files |
| `elao_mysql_configs`           | [ ]                    | Array         | Mysql configuration files                              |

### Configuration example

```
# use a default custom template
elao_mysql_configs_template: "{{ playbook_dir ~ '/templates/mysql/custom_template.cnf.j2' }}"

# clean configs directory
elao_mysql_configs_exclusive: true

elao_mysql_configs:
  - file: my.cnf
    template: configs/default.cnf.j2
    config:
      client:
        port:                   3306
        socket:                 /var/run/mysqld/mysqld.sock
      mysqld_safe:
        nice:                   0
        socket:                 /var/run/mysqld/mysqld.sock
      mysqld:
        user:                   mysql
        socket:                 /var/run/mysqld/mysqld.sock
        bind_address:           127.0.0.1
        port:                   3306
        character_set_server:   utf8
        collation_server:       utf8_general_ci
        max_connections:        100
        thread_concurrency:     10
        slow_query_log:         1
        slow_query_log_file:    /var/log/mysql/mysql-slow.log
        long_query_time:        2
  - file: mysqld_safe_syslog.cnf
    config:
      mysqld_safe:
        syslog: true

```

## Example playbook

    - hosts: servers
      roles:
        - { role: elao.mysql }

# Licence

MIT

# Author information

ELAO [**(http://www.elao.com/)**](http://www.elao.com)