text:
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChild,
  ElementRef,
  Inject,
  Input,
  Renderer2,
  OnChanges,
  OnInit,
  OnDestroy,
  TemplateRef,
  Output,
  EventEmitter,
  AfterContentInit
  } from '@angular/core';
import {
  LyTheme2,
  mixinBg,
  mixinColor,
  mixinElevation,
  mixinShadowColor,
  mixinStyleUpdater,
  toBoolean
  } from '@alyle/ui';

import { LyAccordion } from './accordion';
import { lyExpansionAnimations } from './expansion-animations';
import { LyExpansionPanelContent } from './expansion-panel-content';
import { Subscription, Subject } from 'rxjs';
import { startWith, filter, first, distinctUntilChanged } from 'rxjs/operators';
import { AnimationEvent } from '@angular/animations';

/** LyExpansionPanel's states. */
export type LyExpansionPanelState = 'expanded' | 'collapsed';

/** @docs-private */
export class LyExpansionPanelBase {
  constructor(
    public _theme: LyTheme2
  ) { }
}

/** @docs-private */
export const LyButtonMixinBase = mixinStyleUpdater(
  mixinBg(
    mixinColor(
      mixinElevation(
        mixinShadowColor(LyExpansionPanelBase)))));

@Component({
  selector: 'ly-expansion-panel',
  templateUrl: './expansion-panel.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  exportAs: 'lyExpansionPanel',
  animations: [
    lyExpansionAnimations.contentExpansion
  ],
  inputs: [
    'bg',
    'color',
    'elevation',
    'shadowColor'
  ]
})
export class LyExpansionPanel extends LyButtonMixinBase implements OnChanges, OnInit, AfterContentInit, OnDestroy {

  /** @docs-private */
  readonly classes = this._accordion.classes;

  readonly _panelAnimationTiming = `${
    this._theme.variables.animations.durations.entering
  }ms ${
    this._theme.variables.animations.curves.standard
  }`;

  /** Subscription to openAll/closeAll events. */
  private _openCloseAllSubscription = Subscription.EMPTY;

  private _disabled: boolean;
  private _expanded: boolean;
  private _hasToggle = !!this._accordion.hasToggle;

  _lazyContentRef: TemplateRef<any>;

  /** Content that will be rendered lazily. */
  @ContentChild(LyExpansionPanelContent) readonly _lazyContent: LyExpansionPanelContent;

  /** Event emitted every time the LyExpansionPanel is closed. */
  @Output() closed: EventEmitter<void> = new EventEmitter<void>();

  /** Event emitted every time the LyExpansionPanel is opened. */
  @Output() opened: EventEmitter<void> = new EventEmitter<void>();

  /** An event emitted after the body's collapse animation happens. */
  @Output() afterCollapse: EventEmitter<void> = new EventEmitter<void>();

  /** An event emitted after the body's expansion animation happens. */
  @Output() afterExpand: EventEmitter<void> = new EventEmitter<void>();

  /** Event emitted when the LyExpansionPanel is destroyed. */
  @Output() destroyed: EventEmitter<void> = new EventEmitter<void>();

  /** Stream of body animation done events. */
  _bodyAnimationDone = new Subject<AnimationEvent>();

  @Input()
  set disabled(val: boolean) {
    const newVal = toBoolean(val);

    if (newVal !== this.disabled) {
      this._disabled = newVal;
      if (newVal) {
        this._renderer.addClass(this._el.nativeElement, this._accordion.classes.disabled);
      } else {
        this._renderer.removeClass(this._el.nativeElement, this._accordion.classes.disabled);
      }
    }
  }
  get disabled() {
    return this._disabled;
  }

  @Input()
  set expanded(val: boolean) {
    const newVal = toBoolean(val);

    if (newVal !== this.expanded && !this.disabled) {

      // unselect other panels
      if (newVal && !this._accordion.multiple) {
        this._accordion._openCloseAllActions.next(false);
      }
      this._expanded = newVal;
      if (newVal) {
        this._renderer.addClass(this._el.nativeElement, this._accordion.classes.expanded);
        this.opened.emit();
      } else {
        this._renderer.removeClass(this._el.nativeElement, this._accordion.classes.expanded);
        this.closed.emit();
      }
      this._cd.markForCheck();
    }
  }
  get expanded() {
    return this._expanded;
  }

  @Input()
  set hasToggle(val: boolean) {
    this._hasToggle = toBoolean(val);
  }
  get hasToggle() {
    return this._hasToggle == null ? this._accordion.hasToggle : this._hasToggle;
  }

  constructor(
    private _el: ElementRef,
    private _renderer: Renderer2,
    private _cd: ChangeDetectorRef,
    _theme: LyTheme2,
    @Inject(LyAccordion) private _accordion: LyAccordion
  ) {
    super(_theme);
    _renderer.addClass(_el.nativeElement, this._accordion.classes.panel);
    this._openCloseAllSubscription = this._subscribeToOpenCloseAllActions();

    this._bodyAnimationDone.pipe(distinctUntilChanged((x, y) => {
      return x.fromState === y.fromState && x.toState === y.toState;
    })).subscribe(event => {
      if (event.fromState !== 'void') {
        if (event.toState === 'expanded') {
          this.afterExpand.emit();
        } else if (event.toState === 'collapsed') {
          this.afterCollapse.emit();
        }
      }
    });
  }

  ngOnChanges() {
    this.updateStyle(this._el);
  }

  ngOnInit() {

    let requireUpdate: boolean = false;

    if (this.bg == null) {
      this.bg = 'paper';
      requireUpdate = true;
    }
    if (this.color == null) {
      this.color = 'text';
      requireUpdate = true;
    }
    if (this.elevation == null) {
      this.elevation = 2;
      requireUpdate = true;
    }

    if (requireUpdate) {
      this.ngOnChanges();
    }
  }

  ngAfterContentInit() {
    if (this._lazyContent) {
      this.opened.pipe(
        startWith<void>(null!),
        filter(() => !!this.expanded && !this._lazyContentRef),
        first()
      ).subscribe(() => this._lazyContentRef = this._lazyContent._template);
    }
  }

  ngOnDestroy() {
    this._openCloseAllSubscription.unsubscribe();
  }

  close() {
    this.expanded = false;
  }

  open() {
    this.expanded = true;
  }

  toggle() {
    this.expanded = !this.expanded;
  }

  /** Gets the expanded state string. */
  _getExpandedState(): LyExpansionPanelState {
    return this.expanded ? 'expanded' : 'collapsed';
  }

  private _subscribeToOpenCloseAllActions(): Subscription {
    return this._accordion._openCloseAllActions.subscribe(expanded => {
      this.expanded = expanded;
    });
  }

}


text:
require_relative "../../test_helper"

describe SimpleTemplates::AST::Text do
  let(:target)  {SimpleTemplates::AST::Text}
  let(:valid)   {target.new("a", 0, true)}
  let(:context) {Struct.new(:a).new("result1")}

  describe "render" do
    it "succeeds" do
      valid.render(context).must_equal("a")
    end
  end

  describe "+" do
    it "adds valid" do
      valid.+(target.new("b", 1, true)).must_equal target.new("ab", 0, true)
    end
    it "adds invalid" do
      valid.+(target.new("b", 1, false)).must_equal target.new("ab", 0, false)
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
package sds.classfile.constant_pool

class Utf8Info(_value: String) extends ConstantInfo {
    def value: String = _value
    override def toString(): String = s"Utf8\t$value"
}


text:
package org.daisy.pipeline.braille.css.saxon.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import javax.xml.namespace.QName;
import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.TransformerException;

import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;

import com.xmlcalabash.core.XProcException;

import cz.vutbr.web.css.Declaration;
import cz.vutbr.web.css.Rule;
import cz.vutbr.web.css.RuleBlock;
import cz.vutbr.web.css.Selector;
import cz.vutbr.web.css.Selector.PseudoClass;
import cz.vutbr.web.css.Selector.SelectorPart;
import cz.vutbr.web.csskit.AbstractRuleBlock;

import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;

import org.daisy.braille.css.InlineStyle;
import org.daisy.braille.css.InlineStyle.RuleMainBlock;
import org.daisy.braille.css.InlineStyle.RuleRelativeBlock;
import org.daisy.braille.css.SelectorImpl;
import org.daisy.braille.css.SelectorImpl.PseudoClassImpl;
import org.daisy.braille.css.SelectorImpl.PseudoElementImpl;

import org.daisy.common.stax.XMLStreamWriterHelper.ToStringWriter;
import org.daisy.common.stax.XMLStreamWriterHelper.WriterEvent;
import org.daisy.common.transform.InputValue;
import org.daisy.common.transform.SingleInSingleOutXMLTransformer;
import org.daisy.common.transform.XMLInputValue;
import org.daisy.common.transform.XMLOutputValue;
import org.daisy.common.saxon.SaxonInputValue;
import org.daisy.common.saxon.SaxonOutputValue;
import org.daisy.common.stax.BaseURIAwareXMLStreamReader;
import org.daisy.common.stax.BaseURIAwareXMLStreamWriter;
import static org.daisy.common.stax.XMLStreamWriterHelper.writeAttribute;
import static org.daisy.common.stax.XMLStreamWriterHelper.writeStartElement;
import org.daisy.pipeline.braille.css.impl.BrailleCssSerializer;

import org.osgi.service.component.annotations.Component;

@Component(
	name = "css:render-table-by",
	service = { ExtensionFunctionDefinition.class }
)
public class RenderTableByDefinition extends ExtensionFunctionDefinition {

	private static final String XMLNS_CSS = "http://www.daisy.org/ns/pipeline/braille-css";

	private static final StructuredQName funcname = new StructuredQName("css", XMLNS_CSS, "render-table-by");

	public StructuredQName getFunctionQName() {
		return funcname;
	}

	@Override
	public int getMinimumNumberOfArguments() {
		return 2;
	}

	@Override
	public int getMaximumNumberOfArguments() {
		return 2;
	}

	public SequenceType[] getArgumentTypes() {
		return new SequenceType[] {
			SequenceType.SINGLE_STRING,
			SequenceType.SINGLE_NODE // SINGLE_ELEMENT_NODE
		};
	}

	public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
		return SequenceType.SINGLE_NODE; // SINGLE_ELEMENT_NODE
	}

	public ExtensionFunctionCall makeCallExpression() {
		return new ExtensionFunctionCall() {
			public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
				try {
					String axes = arguments[0].head().getStringValue();
					NodeInfo tableElement = (NodeInfo)arguments[1].head();

					// FIXME: why does this not work?
					// URI base = new URI(tableElement.getBaseURI());
					List<XdmItem> result = new ArrayList<>();
					new TableAsList(axes)
					.transform(
						new SaxonInputValue(tableElement),
						new SaxonOutputValue(result::add, context.getConfiguration()))
					.run();
					if (result.size() != 1 || !(result.get(0) instanceof XdmNode))
						throw new TransformerException(new RuntimeException()); // should not happen
					return ((XdmNode)result.get(0)).getUnderlyingNode();
				} catch (TransformerException e) {
					throw new XPathException("css:render-table-by failed", XProcException.javaError(e, 0)); }
			}
		};
	}

	private static final QName _STYLE = new QName("style");
	private static final QName _ID = new QName("id");

	private static final String XMLNS_HTML = "http://www.w3.org/1999/xhtml";
	private static final String XMLNS_DTB = "http://www.daisy.org/z3986/2005/dtbook/";

	private static final String TABLE = "table";
	private static final String THEAD = "thead";
	private static final String TFOOT = "tfoot";
	private static final String TBODY = "tbody";
	private static final String TR = "tr";
	private static final String TD = "td";
	private static final String TH = "th";
	private static final String COLGROUP = "colgroup";
	private static final String COL = "col";

	private static final QName _HEADERS = new QName("headers");
	private static final QName _SCOPE = new QName("scope");
	private static final QName _AXIS = new QName("axis");
	private static final QName _ROWSPAN = new QName("rowspan");
	private static final QName _COLSPAN = new QName("colspan");

	private static final QName CSS_TABLE_HEADER_POLICY = new QName(XMLNS_CSS, "table-header-policy");

	private static final Splitter HEADERS_SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();
	private static final Splitter AXIS_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

	private static class TableAsList extends SingleInSingleOutXMLTransformer {

		final List<String> axes;

		private TableAsList(String axes) {
			this.axes = new ArrayList<String>(AXIS_SPLITTER.splitToList(axes));
			if (this.axes.remove("auto"))
				if (!this.axes.isEmpty())
					throw new RuntimeException();
		}

		List<WriterEvent> writeActionsBefore;
		List<WriterEvent> writeActionsAfter;
		List<TableCell> cells;
		Set<CellCoordinates> coveredCoordinates;
		String ns;

		public Runnable transform(XMLInputValue<?> source, XMLOutputValue<?> result, InputValue<?> params) throws IllegalArgumentException {
			if (source == null || result == null)
				throw new IllegalArgumentException();
			return () -> transform(source.ensureSingleItem().asXMLStreamReader(), result.asXMLStreamWriter());
		}

		void transform(BaseURIAwareXMLStreamReader reader, BaseURIAwareXMLStreamWriter writer) {
			try {

			writeActionsBefore = new ArrayList<WriterEvent>();
			writeActionsAfter = new ArrayList<WriterEvent>();
			cells = new ArrayList<TableCell>();
			coveredCoordinates = new HashSet<CellCoordinates>();
			List<WriterEvent> writeActions = writeActionsBefore;
			int depth = 0;
			TableCell withinCell = null;
			TableCell.RowType rowType = TableCell.RowType.TBODY;
			int rowGroup = 1;
			int row = 1;
			int col = 1;
			while (true)
				try {
					switch (reader.next()) {
					case START_ELEMENT: {
						QName name = reader.getName();
						depth++;
						boolean isCell = false;
						if (depth == 1) {
							if (!isHTMLorDTBookElement(TABLE, name))
								throw new RuntimeException("Expected table element (html|dtb).");
							if (XMLNS_HTML.equals(name.getNamespaceURI()))
								ns = XMLNS_HTML;
							else if (XMLNS_DTB.equals(name.getNamespaceURI()))
								ns = XMLNS_DTB; }
						else if (isHTMLorDTBookElement(THEAD, name)) {
							rowType = TableCell.RowType.THEAD;
							// TODO: if style != default, warning that style on thead element is ignored
							break; }
						else if (isHTMLorDTBookElement(TFOOT, name)) {
							rowType = TableCell.RowType.TFOOT;
							// TODO: if style != default, warning that style on tfoot element is ignored
							break; }
						else if (isHTMLorDTBookElement(TBODY, name)) {
							rowType = TableCell.RowType.TBODY;
							// TODO: if style != default, warning that style on tbody element is ignored
							break; }
						else if (isHTMLorDTBookElement(TR, name)) {
							// TODO: if style != default, warning that style on tr element is ignored
							break; }
						else if (isHTMLorDTBookElement(COLGROUP, name) || isHTMLorDTBookElement(COL, name))
							throw new RuntimeException("Elements colgroup and col not supported yet.");
						else if (isHTMLorDTBookElement(TD, name) || isHTMLorDTBookElement(TH, name)) {
							isCell = true;
							withinCell = new TableCell();
							withinCell.row = row;
							withinCell.col = col;
							withinCell.rowGroup = rowGroup;
							withinCell.rowType = rowType;
							setCovered(row, col);
							cells.add(withinCell);
							if (isHTMLorDTBookElement(TH, name))
								withinCell.type = TableCell.CellType.TH;
							writeActions = withinCell.writeActions; }
						writeActions.add(w -> writeStartElement(w, name));
						for (int i = 0; i < reader.getNamespaceCount(); i++) {
							String prf = reader.getNamespacePrefix(i);
							String ns = reader.getNamespaceURI(i);
							writeActions.add(w -> w.writeNamespace(prf, ns)); }
						for (int i = 0; i < reader.getAttributeCount(); i++) {
							QName attrName = reader.getAttributeName(i);
							String attrValue = reader.getAttributeValue(i);
							if (CSS_TABLE_HEADER_POLICY.equals(attrName)) {
								if (isCell)
									if ("once".equals(attrValue))
										withinCell.headerPolicy = TableCell.HeaderPolicy.ONCE;
									else if ("always".equals(attrValue))
										withinCell.headerPolicy = TableCell.HeaderPolicy.ALWAYS;
									else if ("front".equals(attrValue))
										withinCell.headerPolicy = TableCell.HeaderPolicy.FRONT;
									else
										throw new RuntimeException(
											"Expected value once|always for table-header-policy property but got " + attrValue); }
							else if (isCell && _HEADERS.equals(attrName))
								withinCell.headers = HEADERS_SPLITTER.splitToList(attrValue);
							else if (isCell && _SCOPE.equals(attrName)) {
								if ("row".equals(attrValue))
									withinCell.scope = TableCell.Scope.ROW;
								else if ("col".equals(attrValue))
									withinCell.scope = TableCell.Scope.COL;
								else if ("colgroup".equals(attrValue) || "rowgroup".equals(attrValue))
									throw new RuntimeException(
											"Value " + attrValue + " for scope attribute not supported yet.");
								else
									throw new RuntimeException(
											"Expected value col|row|colgroup|rowgroup for scope attribute but got " + attrValue); }
							else if (isCell && _AXIS.equals(attrName))
								withinCell.axis = AXIS_SPLITTER.splitToList(attrValue);
							else if (isCell && _ROWSPAN.equals(attrName)) {
								int rowspan = nonNegativeInteger(attrValue);
								if (rowspan == 0)
									throw new RuntimeException("rowspan 0 not supported yet.");
								withinCell.rowspan = rowspan;
								for (int m = 1; m < rowspan; m++)
									for (int n = 0; n < withinCell.colspan; n++)
										setCovered(row + m, col + n); }
							else if (isCell && _COLSPAN.equals(attrName)) {
								int colspan = nonNegativeInteger(attrValue);
								if (colspan == 0)
									throw new RuntimeException("colspan 0 not supported yet.");
								withinCell.colspan = colspan;
								for (int m = 0; m < withinCell.rowspan; m++)
									for (int n = 1; n < withinCell.colspan; n++)
										setCovered(row + m, col + n); }

							// TODO: check that there are no duplicate IDs?
							else if (isCell && _ID.equals(attrName))
								withinCell.id = attrValue;
							else if (depth == 1 && _STYLE.equals(attrName)) {
								String newStyle; {
									InlineStyle style = new InlineStyle(attrValue);
									List<RuleBlock<? extends Rule<?>>> builder = new ArrayList<>();
									for (RuleBlock<?> block : style) {
										if (block instanceof RuleMainBlock)
											builder.add(style.getMainStyle());
										else if (block instanceof RuleRelativeBlock) {
											RuleRelativeBlock ruleblock = (RuleRelativeBlock)block;
											List<Selector> selector = ruleblock.getSelector();
											if (selector.size() > 0) { // should always be true
												if (selector.get(0).size() > 0) { // should always be true
													// the first part is normally a PseudoElementImpl, i.e. a pseudo element or a custom
													// pseudo class like :-obfl-alternate-scenario
													// other parts are possible too, but will in practice already have been processed
													// by css:inline
													if (selector.get(0).get(0) instanceof PseudoElementImpl) {
														// selector.get(0).size() should normally always be 1
														// pseudo classes and pseudo elements are stacked onto the first pseudo element,
														// and for other parts (classes or attributes) it does not makes sense to come after
														// a pseudo element
														PseudoElementImpl pseudo = (PseudoElementImpl)selector.get(0).get(0);
														if ("list-item".equals(pseudo.getName()))
															addListItemStyle(
																pseudo.getPseudoClasses(),
																new ListItemStyle(rest(ruleblock)));
														else if ("list-header".equals(pseudo.getName())) {
															if (pseudo.getPseudoClasses().isEmpty())
																addListHeaderStyle(
																	new ListItemStyle(rest(ruleblock))); }
														else if ("table-by".equals(pseudo.getName())) {
															String axis = pseudo.getArguments()[0];
															if (pseudo.getPseudoClasses().isEmpty()) {
																if (pseudo.hasStackedPseudoElement()) {
																	pseudo = pseudo.getStackedPseudoElement();
																	ruleblock = (RuleRelativeBlock)rest(ruleblock);
																	if ("list-item".equals(pseudo.getName()))
																		getTableByStyle(axis).addListItemStyle(
																			pseudo.getPseudoClasses(),
																			new ListItemStyle(rest(ruleblock)));
																	else if ("list-header".equals(pseudo.getName())) {
																		if (pseudo.getPseudoClasses().isEmpty())
																			getTableByStyle(axis).addListHeaderStyle(
																				new ListItemStyle(rest(ruleblock))); }
																	else
																		getTableByStyle(axis).addRuleBlock(ruleblock); }
																else
																	getTableByStyle(axis).addRuleBlock(rest(ruleblock)); }}
														else
															// could be some other pseudo element or a custom pseudo class like
															// :-obfl-alternate-scenario (yes, it is implemented as a PseudoElementImpl even
															// though it is a class)
															// in the case a ::list-item, ::list-header or ::table-by follows later in the
															// selector, they will be handled later in a subsequent call to css:render-table-by,
															// after the pseudo elements/classes have been handled elsewhere
															builder.add(ruleblock); }
													else
														builder.add(ruleblock); }
												else
													builder.add(ruleblock); }}
										else
											throw new RuntimeException("Unexpected style " + block); }
									newStyle = serializeRuleBlockList(builder); }
								if (!newStyle.isEmpty())
									writeActions.add(w -> writeAttribute(w, attrName, newStyle)); }
							else
								writeActions.add(w -> writeAttribute(w, attrName, attrValue)); }
						break; }
					case CHARACTERS:
						String chars = reader.getText();
						writeActions.add(w -> w.writeCharacters(chars));
						break;
					case END_ELEMENT: {
						QName name = reader.getName();
						depth--;
						if (isHTMLorDTBookElement(THEAD, name)
						    || isHTMLorDTBookElement(TFOOT, name)
						    || isHTMLorDTBookElement(TBODY, name)) {
							rowGroup++;
							break; }
						else if (isHTMLorDTBookElement(TR, name)) {
							row++;
							col = 1;
							while (isCovered(row, col)) col++;
							break; }
						writeActions.add(w -> w.writeEndElement());
						if (isHTMLorDTBookElement(TD, name) || isHTMLorDTBookElement(TH, name)) {
							withinCell = null;
							writeActions = writeActionsAfter;
							while (isCovered(row, col)) col++; }
						break; }}}
				catch (NoSuchElementException e) {
					break; }

			// handle colspan and rowspan on data cells by simply splitting them into several identical ones for now
			List<TableCell> moreCells = new ArrayList<TableCell>();
			for (TableCell c : cells)
				if (!isHeader(c)) {
					if (c.rowspan > 1) {
						int span = c.rowspan;
						c.rowspan = 1;
						for (int i = 1; i < span; i++) {
							TableCell dup = c.clone();
							dup.row = c.row + i;
							moreCells.add(dup); }}
					if (c.colspan > 1) {
						int span = c.colspan;
						c.colspan = 1;
						for (int i = 1; i < span; i++) {
							TableCell dup = c.clone();
							dup.col = c.col + i;
							moreCells.add(dup); }}}
			cells.addAll(moreCells);

			// rearrange row groups and order cells by row
			Collections.sort(cells, compose(sortByRowType, sortByRow, sortByColumn));
			rowGroup = 0;
			row = 0;
			int newRowGroup = rowGroup = 0;
			int newRow = row = 0;
			for (TableCell c : cells) {
				if (c.rowGroup != rowGroup) {
					rowGroup = c.rowGroup;
					newRowGroup++; }
				if (c.row != row) {
					row = c.row;
					newRow++; }
				c.rowGroup = newRowGroup;
				c.row = newRow; }

			write(writer);

			} catch (XMLStreamException e) {
				throw new RuntimeException(e);
			}
		}

		private boolean isHTMLorDTBookElement(String element, QName name) {
			return ((XMLNS_HTML.equals(name.getNamespaceURI())
			        || XMLNS_DTB.equals(name.getNamespaceURI()))
			        && name.getLocalPart().equalsIgnoreCase(element));
		}

		private void setCovered(int row, int col) {
			CellCoordinates coords = new CellCoordinates(row, col);
			if (coveredCoordinates.contains(coords))
				throw new RuntimeException("Table structure broken: cells overlap");
			coveredCoordinates.add(coords);
		}

		private boolean isCovered(int row, int col) {
			return coveredCoordinates.contains(new CellCoordinates(row, col));
		}

		private void write(XMLStreamWriter writer) throws XMLStreamException {
			for (WriterEvent action : writeActionsBefore)
				action.writeTo(writer);
			List<TableCell> dataCells = new ArrayList<TableCell>();
			for (TableCell c : cells)
				if (!isHeader(c))
					dataCells.add(c);
			new TableCellGroup(dataCells, axes.iterator()).write(writer);
			for (WriterEvent action : writeActionsAfter)
				action.writeTo(writer);
		}

		private static final List<TableCell> emptyList = new ArrayList<TableCell>();

		private abstract class TableCellCollection {
			public abstract List<TableCell> newlyRenderedHeaders();
			public abstract List<TableCell> newlyPromotedHeaders();
			public abstract void write(XMLStreamWriter writer) throws XMLStreamException;
		}

		private class SingleTableCell extends TableCellCollection {

			private final TableCell cell;
			private final TableCellGroup parent;
			private final SingleTableCell precedingSibling;
			private final boolean columnAppliedBeforeRow;

			private SingleTableCell(TableCell cell, TableCellGroup parent, SingleTableCell precedingSibling, boolean columnAppliedBeforeRow) {
				this.cell = cell;
				this.parent = parent;
				this.precedingSibling = precedingSibling;
				this.columnAppliedBeforeRow = columnAppliedBeforeRow;
			}

			private List<TableCell> newlyAppliedHeaders;
			public List<TableCell> newlyAppliedHeaders() {
				if (newlyAppliedHeaders == null) {
					newlyAppliedHeaders = new ArrayList<TableCell>();
					for (TableCell h : findHeaders(cell, !columnAppliedBeforeRow))
						if (!parent.appliedHeaders().contains(h))
							newlyAppliedHeaders.add(h); }
				return newlyAppliedHeaders;
			}

			private List<TableCell> newlyRenderedOrPromotedHeaders;
			private List<TableCell> newlyRenderedOrPromotedHeaders() {
				if (newlyRenderedOrPromotedHeaders == null) {
					newlyRenderedOrPromotedHeaders = new ArrayList<TableCell>();
					Iterator<TableCell> lastAppliedHeaders = (
						precedingSibling != null ? precedingSibling.newlyAppliedHeaders() : emptyList
					).iterator();
					boolean canOmit = true;
					for (TableCell h : parent.deferredHeaders()) {
						newlyRenderedOrPromotedHeaders.add(h);
						canOmit = false; }
					for (TableCell h : newlyAppliedHeaders()) {
						if (canOmit
						    && h.headerPolicy != TableCell.HeaderPolicy.ALWAYS
						    && lastAppliedHeaders.hasNext() && lastAppliedHeaders.next().equals(h))
							continue;
						newlyRenderedOrPromotedHeaders.add(h);
						canOmit = false; }}
				return newlyRenderedOrPromotedHeaders;
			}

			private List<TableCell> newlyPromotedHeaders;
			public List<TableCell> newlyPromotedHeaders() {
				if (newlyPromotedHeaders == null) {
					newlyPromotedHeaders = new ArrayList<TableCell>();
					int i = newlyRenderedOrPromotedHeaders().size() - 1;
					while (i >= 0 && newlyRenderedOrPromotedHeaders().get(i).headerPolicy != TableCell.HeaderPolicy.FRONT)
						i--;
					while (i >= 0)
						newlyPromotedHeaders.add(0, newlyRenderedOrPromotedHeaders().get(i--)); }
				return newlyPromotedHeaders;
			}

			private List<TableCell> newlyRenderedHeaders;
			public  List<TableCell> newlyRenderedHeaders() {
				if (newlyRenderedHeaders == null) {
					newlyRenderedHeaders = new ArrayList<TableCell>();
					int i = newlyRenderedOrPromotedHeaders().size() - 1;
					while (i >= 0 && newlyRenderedOrPromotedHeaders().get(i).headerPolicy != TableCell.HeaderPolicy.FRONT)
						newlyRenderedHeaders.add(0, newlyRenderedOrPromotedHeaders().get(i--)); }
				return newlyRenderedHeaders;
			}

			public void write(XMLStreamWriter writer) throws XMLStreamException {
				cell.write(writer);
			}

			@Override
			public String toString() {
				ToStringWriter xml = new ToStringWriter();
				try {
					write(xml); }
				catch (Exception e) {
					throw new RuntimeException("coding error", e); }
				StringBuilder s = new StringBuilder();
				s.append("SingleTableCell[header: ").append(newlyRenderedHeaders());
				s.append(", cell: ").append(cell);
				s.append(", xml: ").append(xml).append("]");
				return s.toString();
			}
		}

		private class TableCellGroup extends TableCellCollection {

			private final TableCellGroup parent;
			private final TableCell groupingHeader;
			private final String groupingAxis;
			private final TableCellGroup precedingSibling;
			private final List<TableCellCollection> children;
			private final boolean rowApplied;
			private final boolean columnAppliedBeforeRow;

			private TableCellGroup(List<TableCell> cells, Iterator<String> nextAxes) {
				this(cells, nextAxes, null, null, null, null, false, false);
			}

			private TableCellGroup(List<TableCell> cells, Iterator<String> nextAxes,
			                       TableCellGroup parent, TableCell groupingHeader, String groupingAxis,
			                       TableCellGroup precedingSibling,
			                       boolean rowApplied, boolean columnAppliedBeforeRow) {
				this.parent = parent;
				this.groupingHeader = groupingHeader;
				this.groupingAxis = groupingAxis;
				this.precedingSibling = precedingSibling;
				this.rowApplied = rowApplied;
				this.columnAppliedBeforeRow = columnAppliedBeforeRow;
				children = groupCellsBy(cells, nextAxes);
			}

			private List<TableCellCollection> groupCellsBy(List<TableCell> cells, Iterator<String> axes) {
				String firstAxis = axes.hasNext() ? axes.next() : null;
				List<String> nextAxes = ImmutableList.copyOf(axes);
				if (firstAxis != null) {
					Map<TableCell,List<TableCell>> categories = new LinkedHashMap<TableCell,List<TableCell>>();
					List<TableCell> uncategorized = null;
					for (TableCell c : cells) {
						boolean categorized = false;
						for (TableCell h : findHeaders(c, !columnAppliedBeforeRow))
							if (h.axis != null && h.axis.contains(firstAxis)) {
								List<TableCell> category = categories.get(h);
								if (category == null) {
									category = new ArrayList<TableCell>();
									categories.put(h, category); }
								category.add(c);
								categorized = true; }
						if (!categorized) {
							if (uncategorized == null)
								uncategorized = new ArrayList<TableCell>();
							uncategorized.add(c); }}
					if (!categories.isEmpty()) {
						List<TableCellCollection> children = new ArrayList<TableCellCollection>();
						TableCellGroup child = null;
						for (TableCell h : categories.keySet()) {
							child = new TableCellGroup(categories.get(h), nextAxes.iterator(), this, h, firstAxis, child,
							                           rowApplied, columnAppliedBeforeRow);
							children.add(child); }
						if (uncategorized != null) {
							child = new TableCellGroup(uncategorized, nextAxes.iterator(), this, null, firstAxis, child,
							                           rowApplied, columnAppliedBeforeRow);
							children.add(child); }
						return children; }
					else if ("row".equals(firstAxis)) {
						List<TableCellCollection> children = new ArrayList<TableCellCollection>();
						TableCellGroup child = null;
						Map<Integer,List<TableCell>> rows = new LinkedHashMap<Integer,List<TableCell>>();
						for (TableCell c : cells) {
							List<TableCell> row = rows.get(c.row);
							if (row == null) {
								row = new ArrayList<TableCell>();
								rows.put(c.row, row); }
							row.add(c); }
						for (List<TableCell> row : rows.values()) {
							child = new TableCellGroup(row, nextAxes.iterator(), this, null, firstAxis, child, true, columnAppliedBeforeRow);
							children.add(child); }
						return children; }
					else if ("column".equals(firstAxis) || "col".equals(firstAxis)) {
						List<TableCellCollection> children = new ArrayList<TableCellCollection>();
						TableCellGroup child = null;
						Map<Integer,List<TableCell>> columns = new LinkedHashMap<Integer,List<TableCell>>();
						for (TableCell c : cells) {
							List<TableCell> column = columns.get(c.col);
							if (column == null) {
								column = new ArrayList<TableCell>();
								columns.put(c.col, column); }
							column.add(c); }
						for (List<TableCell> column : columns.values()) {
							child = new TableCellGroup(column, nextAxes.iterator(), this, null, firstAxis, child, rowApplied, !rowApplied);
							children.add(child); }
						return children; }
					else if ("row-group".equals(firstAxis)) {
						List<TableCellCollection> children = new ArrayList<TableCellCollection>();
						TableCellGroup child = null;
						Map<Integer,List<TableCell>> rowGroups = new LinkedHashMap<Integer,List<TableCell>>();
						for (TableCell c : cells) {
							List<TableCell> rowGroup = rowGroups.get(c.rowGroup);
							if (rowGroup == null) {
								rowGroup = new ArrayList<TableCell>();
								rowGroups.put(c.rowGroup, rowGroup); }
							rowGroup.add(c); }
						for (List<TableCell> rowGroup : rowGroups.values()) {
							child = new TableCellGroup(rowGroup, nextAxes.iterator(), this, null, firstAxis, child,
							                           rowApplied, columnAppliedBeforeRow);
							children.add(child); }
						return children; }
					else
						return groupCellsBy(cells, nextAxes.iterator()); }
				else {
					List<TableCellCollection> children = new ArrayList<TableCellCollection>();
					SingleTableCell child = null;
					for (TableCell c : cells) {
						child = new SingleTableCell(c, this, child, columnAppliedBeforeRow);
						children.add(child); }
					return children; }
			}

			private List<TableCell> newlyAppliedHeaders;
			public List<TableCell> newlyAppliedHeaders() {
				if (newlyAppliedHeaders == null) {
					newlyAppliedHeaders = new ArrayList<TableCell>();
					if (groupingHeader != null)
						for (TableCell h : findHeaders(groupingHeader, !columnAppliedBeforeRow))
							if (!previouslyAppliedHeaders().contains(h))
								newlyAppliedHeaders.add(h); }
				return newlyAppliedHeaders;
			}

			private List<TableCell> previouslyAppliedHeaders() {
				if (parent != null)
					return parent.appliedHeaders();
				else
					return emptyList;
			}

			private List<TableCell> appliedHeaders;
			public List<TableCell> appliedHeaders() {
				if (appliedHeaders == null) {
					appliedHeaders = new ArrayList<TableCell>();
					appliedHeaders.addAll(previouslyAppliedHeaders());
					appliedHeaders.addAll(newlyAppliedHeaders()); }
				return appliedHeaders;
			}

			private List<TableCell> newlyDeferredHeaders;
			private List<TableCell> newlyDeferredHeaders() {
				if (newlyDeferredHeaders == null) {
					newlyDeferredHeaders = new ArrayList<TableCell>();
					int i = newlyAppliedHeaders().size() - 1;
					while (i >= 0 && newlyAppliedHeaders().get(i).headerPolicy == TableCell.HeaderPolicy.ALWAYS)
						newlyDeferredHeaders.add(0, newlyAppliedHeaders().get(i--)); }
				return newlyDeferredHeaders;
			}

			private List<TableCell> deferredHeaders;
			private List<TableCell> deferredHeaders() {
				if (deferredHeaders == null) {
					deferredHeaders = new ArrayList<TableCell>();
					if (newlyRenderedOrPromotedHeaders().isEmpty())
						deferredHeaders.addAll(previouslyDeferredHeaders());
					deferredHeaders.addAll(newlyDeferredHeaders()); }
				return deferredHeaders;
			}

			private List<TableCell> previouslyDeferredHeaders() {
				if (parent != null)
					return parent.deferredHeaders();
				else
					return emptyList;
			}

			private List<TableCell> newlyRenderedOrPromotedHeaders;
			private List<TableCell> newlyRenderedOrPromotedHeaders() {
				if (newlyRenderedOrPromotedHeaders == null) {
					newlyRenderedOrPromotedHeaders = new ArrayList<TableCell>();
					int i = newlyAppliedHeaders().size() - 1;
					while (i >= 0 && newlyAppliedHeaders().get(i).headerPolicy == TableCell.HeaderPolicy.ALWAYS)
						i--;
					if (i >= 0) {
						Iterator<TableCell> lastAppliedHeaders = (
							precedingSibling != null ? precedingSibling.newlyAppliedHeaders() : emptyList
						).iterator();
						boolean canOmit = true;
						for (TableCell h : previouslyDeferredHeaders()) {
							newlyRenderedOrPromotedHeaders.add(h);
							canOmit = false; }
						for (int j = 0; j <= i; j++) {
							TableCell h = newlyAppliedHeaders().get(j);
							if (canOmit
							    && h.headerPolicy != TableCell.HeaderPolicy.ALWAYS
							    && lastAppliedHeaders.hasNext() && lastAppliedHeaders.next().equals(h))
								continue;
							newlyRenderedOrPromotedHeaders.add(h);
							canOmit = false; }}}
				return newlyRenderedOrPromotedHeaders;
			}

			private List<TableCell> newlyPromotedHeaders;
			public List<TableCell> newlyPromotedHeaders() {
				if (newlyPromotedHeaders == null) {
					newlyPromotedHeaders = new ArrayList<TableCell>();
					int i = newlyRenderedOrPromotedHeaders().size() - 1;
					while (i >= 0 && newlyRenderedOrPromotedHeaders().get(i).headerPolicy != TableCell.HeaderPolicy.FRONT)
						i--;
					while (i >= 0)
						newlyPromotedHeaders.add(0, newlyRenderedOrPromotedHeaders().get(i--)); }
				return newlyPromotedHeaders;
			}

			private List<TableCell> newlyRenderedHeaders;
			public List<TableCell> newlyRenderedHeaders() {
				if (newlyRenderedHeaders == null) {
					newlyRenderedHeaders = new ArrayList<TableCell>();
					int i = newlyRenderedOrPromotedHeaders().size() - 1;
					while (i >= 0 && newlyRenderedOrPromotedHeaders().get(i).headerPolicy != TableCell.HeaderPolicy.FRONT)
						newlyRenderedHeaders.add(0, newlyRenderedOrPromotedHeaders().get(i--)); }
				return newlyRenderedHeaders;
			}

			public void write(XMLStreamWriter writer) {
				try {
					List<List<TableCell>> promotedHeaders = null;
					int i = 0;
					for (TableCellCollection c : children) {
						if (c instanceof TableCellGroup) {
							TableCellGroup g = (TableCellGroup)c;
							int j = 0;
							for (TableCellCollection cc : g.children) {
								if (!cc.newlyPromotedHeaders().isEmpty()) {
									if (promotedHeaders == null) {
										if (i == 0 && j == 0) {
											writeStartElement(writer, new QName(ns, "_"));
											writeStyleAttribute(writer,
											                    groupingAxis != null ? getTableByStyle(groupingAxis).getListHeaderStyle()
											                                         : getListHeaderStyle());
											writeStartElement(writer, new QName(ns, "_"));
											writeStyleAttribute(writer, getTableByStyle(g.groupingAxis));
											promotedHeaders = new ArrayList<List<TableCell>>(); }
										else
											throw new RuntimeException("Some headers of children promoted but not all children have a promoted header."); }
									if (i == 0) {
										writeStartElement(writer, new QName(ns, "_"));
										Predicate<PseudoClass> matcher = matchesPosition(j + 1, g.children.size());
										writeStyleAttribute(writer, getTableByStyle(g.groupingAxis).getListItemStyle(matcher));
										for (TableCell h : cc.newlyPromotedHeaders())
											h.write(writer);
										writer.writeEndElement();
										promotedHeaders.add(cc.newlyPromotedHeaders()); }
									else if (!promotedHeaders.get(j).equals(cc.newlyPromotedHeaders()))
										throw new RuntimeException("Headers of children promoted but not the same as promoted headers of sibling groups."); }
								else if (promotedHeaders != null)
									throw new RuntimeException("Some headers of children promoted but not all children have a promoted header.");
								j++; }
							if (promotedHeaders != null && promotedHeaders.size() != j) {
								throw new RuntimeException("Headers of children promoted but not the same as promoted headers of sibling groups."); }}
						else if (promotedHeaders != null)
							throw new RuntimeException("Coding error");
						i++; }
					if (promotedHeaders != null) {
						writer.writeEndElement();
						writer.writeEndElement(); }
					i = 0;
					for (TableCellCollection c : children) {
						writeStartElement(writer, new QName(ns, "_"));
						Predicate<PseudoClass> matcher = matchesPosition(i + 1, children.size());
						writeStyleAttribute(writer,
						                    groupingAxis != null ? getTableByStyle(groupingAxis).getListItemStyle(matcher)
						                                         : getListItemStyle(matcher));
						for (TableCell h : c.newlyRenderedHeaders())
							h.write(writer);
						if (c instanceof TableCellGroup) {
							TableCellGroup g = (TableCellGroup)c;
							writeStartElement(writer, new QName(ns, "_"));
							writeStyleAttribute(writer, getTableByStyle(g.groupingAxis)); }
						c.write(writer);
						if (c instanceof TableCellGroup)
							writer.writeEndElement();
						writer.writeEndElement();
						i++; }}
				catch (XMLStreamException e) {
					throw new RuntimeException(e); }
			}

			@Override
			public String toString() {
				ToStringWriter xml = new ToStringWriter();
				write(xml);
				StringBuilder s = new StringBuilder();
				s.append("TableCellGroup[header: ").append(newlyRenderedHeaders());
				s.append(", children: ").append(children);
				s.append(", xml: ").append(xml).append("]");
				return s.toString();
			}
		}

		private static void writeStyleAttribute(XMLStreamWriter writer, PseudoElementStyle style) throws XMLStreamException {
			if (!style.isEmpty())
				writeAttribute(writer, _STYLE, style.toString());
		}

		final private Map<String,TableByStyle> tableByStyles = new HashMap<String,TableByStyle>();
		final private Map<List<PseudoClass>,ListItemStyle> listItemStyles = new LinkedHashMap<List<PseudoClass>,ListItemStyle>();
		private ListItemStyle listHeaderStyle = new ListItemStyle();

		public void addListItemStyle(List<PseudoClass> pseudo, ListItemStyle style) {
			if (!listItemStyles.containsKey(pseudo))
				listItemStyles.put(pseudo, style);
			else
				listItemStyles.put(pseudo, listItemStyles.get(pseudo).mergeWith(style));
		}

		public void addListHeaderStyle(ListItemStyle style) {
			listHeaderStyle = listHeaderStyle.mergeWith(style);
		}

		public TableByStyle getTableByStyle(String axis) {
			TableByStyle style = tableByStyles.get(axis);
			if (style == null) {
				style = new TableByStyle();
				tableByStyles.put(axis, style); }
			return style;
		}

		public ListItemStyle getListItemStyle(Predicate<PseudoClass> matcher) {
			ListItemStyle style = new ListItemStyle();
		  outer: for (List<PseudoClass> pseudoClasses : listItemStyles.keySet()) {
				for (PseudoClass pseudoClass : pseudoClasses)
					if (!matcher.apply(pseudoClass))
						continue outer;
				style = style.mergeWith(listItemStyles.get(pseudoClasses)); }
			return style;
		}

		public ListItemStyle getListHeaderStyle() {
			return listHeaderStyle;
		}

		private static class PseudoElementStyle {

			final protected Map<List<Selector>,RuleBlock<Rule<?>>> ruleBlocks = new HashMap<>();

			public void addRuleBlock(RuleBlock<Rule<?>> ruleblock) {
				if (!ruleblock.isEmpty()) {
					List<Selector> selector = null;
					if (ruleblock instanceof RuleRelativeBlock)
						selector = ((RuleRelativeBlock)ruleblock).getSelector();
					RuleBlock<Rule<?>> r;
					if (ruleBlocks.containsKey(selector))
						r = ruleBlocks.get(selector);
					else {
						// we make a copy so that we can modify the rule later without affecting the
						// original which might be used in other places (it should be considered
						// immutable)
						r = selector != null
							? new RuleRelativeBlock(selector)
							: new AbstractRuleBlock<Rule<?>>();
						r.unlock();
					}
					// we can modify the existing rule because it is mutable and dedicated to this class
					r.addAll(ruleblock);
					ruleBlocks.put(selector, r);
				}
			}

			public boolean isEmpty() {
				return ruleBlocks.isEmpty();
			}

			@Override
			public String toString() {
				return serializeRuleBlockList(ruleBlocks.values());
			}
		}

		private static class TableByStyle extends PseudoElementStyle {

			final private Map<List<PseudoClass>,ListItemStyle> listItemStyles = new LinkedHashMap<List<PseudoClass>,ListItemStyle>();
			private ListItemStyle listHeaderStyle = new ListItemStyle();

			public TableByStyle() {}

			public void addListItemStyle(List<PseudoClass> pseudo, ListItemStyle style) {
				if (!listItemStyles.containsKey(pseudo))
					listItemStyles.put(pseudo, style);
				else
					listItemStyles.put(pseudo, listItemStyles.get(pseudo).mergeWith(style));
			}

			public void addListHeaderStyle(ListItemStyle style) {
				listHeaderStyle = listHeaderStyle.mergeWith(style);
			}

			public ListItemStyle getListItemStyle(Predicate<PseudoClass> matcher) {
				ListItemStyle style = new ListItemStyle();
			  outer: for (List<PseudoClass> pseudoClasses : listItemStyles.keySet()) {
					for (PseudoClass pseudoClass : pseudoClasses)
						if (!matcher.apply(pseudoClass))
							continue outer;
					style = style.mergeWith(listItemStyles.get(pseudoClasses)); }
				return style;
			}

			public ListItemStyle getListHeaderStyle() {
				return listHeaderStyle;
			}
		}

		private static class ListItemStyle extends PseudoElementStyle {

			public ListItemStyle() {}

			public ListItemStyle(RuleBlock<Rule<?>> ruleblock) {
				addRuleBlock(ruleblock);
			}

			public ListItemStyle mergeWith(ListItemStyle style) {
				for (RuleBlock<Rule<?>> r: style.ruleBlocks.values())
					addRuleBlock(r);
				return this;
			}
		}

		private final static Predicate<PseudoClass> matchesPosition(final int position, final int elementCount) {
			return new Predicate<PseudoClass>() {
				public boolean apply(PseudoClass pseudo) {
					if (pseudo instanceof PseudoClassImpl)
						return ((PseudoClassImpl)pseudo).matchesPosition(position, elementCount);
					return false;
				}
			};
		}

		// see https://www.w3.org/TR/REC-html40/struct/tables.html#h-11.4.3
		private List<TableCell> findHeaders(TableCell cell, boolean firstLeftThenUpward) {
			List<TableCell> headers = new ArrayList<TableCell>();
			if (isHeader(cell))
				headers.add(cell);
			findHeaders(headers, 0, cell, firstLeftThenUpward);
			return headers;
		}

		private int findHeaders(List<TableCell> headers, int index, TableCell cell, boolean firstLeftThenUpward) {

			// headers attribute
			if (cell.headers != null) {
				for (String id : cell.headers)
					index = recurAddHeader(headers, index, getById(id), firstLeftThenUpward);
				return index; }

			// scope attribute can be used instead of headers (they should not be used in same table)
			List<TableCell> rowHeaders = new ArrayList<TableCell>();
			List<TableCell> colHeaders = new ArrayList<TableCell>();
			for (TableCell h : cells)
				if (h != cell && h.scope != null) {
					switch (h.scope) {
					case ROW:
						if (h.row <= (cell.row + cell.rowspan - 1) && cell.row <= (h.row + h.rowspan - 1))
							rowHeaders.add(h);
						break;
					case COL:
						if (h.col <= (cell.col + cell.colspan - 1) && cell.col <= (h.col + h.colspan - 1))
							colHeaders.add(h);
						break; }}
			Collections.sort(rowHeaders, sortByColumnAndThenRow);
			for (TableCell h : rowHeaders)
				index = recurAddHeader(headers, index, h, firstLeftThenUpward);
			Collections.sort(colHeaders, sortByRowAndThenColumn);
			for (TableCell h : colHeaders)
				index = recurAddHeader(headers, index, h, firstLeftThenUpward);

			if (!isHeader(cell)) {
				int direction = (firstLeftThenUpward ? 0 : 1);
			  outer: while (true) {
					switch (direction) {
					case 0: { // search left from the cell's position to find row header cells
						int k = 0;
						for (int i = 0; i < cell.rowspan; i++)
							for (int j = cell.col - 1; j > 0;) {
								boolean foundHeader = false;
								TableCell c = getByCoordinates(cell.row + i, j);
								if (c != null && isHeader(c)) {
									foundHeader = true;
									if (c.scope == null) {
										int l = recurAddHeader(headers, index, c, firstLeftThenUpward) - index;
										k += l;
										if (l > 1)
											break; }}
								else if (foundHeader)
									break;
								if (c == null)
									j--;
								else
									j = j - c.colspan; }
						index += k;
						if (!firstLeftThenUpward)
							break outer; }
					case 1: { // search upwards from the cell's position to find column header cells
						int k = 0;
						for (int i = 0; i < cell.colspan; i++)
							for (int j = cell.row - 1; j > 0;) {
								boolean foundHeader = false;
								TableCell c = getByCoordinates(j, cell.col + i);
								if (c != null && isHeader(c)) {
									foundHeader = true;
									if (c.scope == null) {
										int l = recurAddHeader(headers, index, c, firstLeftThenUpward) - index;
										k += l;
										if (l > 1)
											break; }}
								else if (foundHeader)
									break;
								if (c == null)
									j--;
								else
									j = j - c.rowspan; }
						index += k;
						if (!firstLeftThenUpward) {
							direction--;
							continue outer; }
						break outer; }}}}

			return index;
		}

		private int recurAddHeader(List<TableCell> headers, int index, TableCell header, boolean firstLeftThenUpward) {
			if (headers.contains(header))
				throw new RuntimeException();
			else {
				headers.add(index, header);
				index = findHeaders(headers, index, header, firstLeftThenUpward);
				index ++; }
			return index;
		}

		private TableCell getById(String id) {
			for (TableCell c : cells)
				if (id.equals(c.id))
					return c;
			throw new RuntimeException("No element found with id " + id);
		}

		private TableCell getByCoordinates(int row, int col) {
			for (TableCell c : cells)
				if (c.row <= row && (c.row + c.rowspan - 1) >= row &&
				    c.col <= col && (c.col + c.colspan - 1) >= col)
					return c;
			return null;
		}

		private static boolean isHeader(TableCell cell) {
			return (cell.type == TableCell.CellType.TH || (cell.axis != null) || (cell.scope != null));
		}

		@SafeVarargs
		private static final <T> Comparator<T> compose(final Comparator<T>... comparators) {
			return new Comparator<T>() {
				public int compare(T x1, T x2) {
					for (Comparator<T> comparator : comparators) {
						int result = comparator.compare(x1, x2);
						if (result != 0)
							return result; }
					return 0;
				}
			};
		}

		private static final Comparator<TableCell> sortByRow = new Comparator<TableCell>() {
			public int compare(TableCell c1, TableCell c2) {
				return new Integer(c1.row).compareTo(c2.row);
			}
		};

		private static final Comparator<TableCell> sortByColumn = new Comparator<TableCell>() {
			public int compare(TableCell c1, TableCell c2) {
				return new Integer(c1.col).compareTo(c2.col);
			}
		};

		private static final Comparator<TableCell> sortByRowType = new Comparator<TableCell>() {
			public int compare(TableCell c1, TableCell c2) {
				return c1.rowType.compareTo(c2.rowType);
			}
		};

		private static final Comparator<TableCell> sortByRowAndThenColumn = compose(sortByRow, sortByColumn);

		private static final Comparator<TableCell> sortByColumnAndThenRow = compose(sortByColumn, sortByRow);

		private static class TableCell {

			private enum CellType {
				TD,
				TH
			}

			private enum RowType {
				THEAD,
				TBODY,
				TFOOT
			}

			private enum HeaderPolicy {
				ALWAYS,
				ONCE,
				FRONT
			}

			// TODO: handle colgroup and rowgroup
			private enum Scope {
				COL,
				ROW
			}

			private int rowGroup;
			private int row;
			private int col;
			private CellType type = CellType.TD;
			private RowType rowType = RowType.TBODY;
			private HeaderPolicy headerPolicy = HeaderPolicy.ONCE;
			private String id;
			private List<String> headers;
			private Scope scope = null;
			private List<String> axis;
			private int rowspan = 1;
			private int colspan = 1;

			private List<WriterEvent> writeActions = new ArrayList<WriterEvent>();

			public void write(XMLStreamWriter writer) throws XMLStreamException {
				for (WriterEvent action : writeActions)
					action.writeTo(writer);
			}

			public TableCell clone() {
				TableCell clone = new TableCell();
				clone.rowGroup = this.rowGroup;
				clone.row = this.row;
				clone.col = this.col;
				clone.type = this.type;
				clone.rowType = this.rowType;
				clone.headerPolicy = this.headerPolicy;
				clone.id = this.id;
				clone.headers = this.headers;
				clone.scope = this.scope;
				clone.axis = this.axis;
				clone.rowspan = this.rowspan;
				clone.colspan = this.colspan;
				clone.writeActions.addAll(this.writeActions);
				return clone;
			}

			@Override
			public String toString() {
				ToStringWriter xml = new ToStringWriter();
				try {
					write(xml); }
				catch (Exception e) {
					throw new RuntimeException("coding error", e); }
				StringBuilder s = new StringBuilder();
				s.append("TableCell{" + row + "," + col + "}[").append(xml).append("]");
				return s.toString();
			}
		}

		private static class CellCoordinates {

			private final int row;
			private final int col;

			private CellCoordinates(int row, int col) {
				this.row = row;
				this.col = col;
			}

			public int hashCode() {
				final int prime = 31;
				int result = 1;
				result = prime * result + col;
				result = prime * result + row;
				return result;
			}

			public boolean equals(Object obj) {
				if (this == obj)
					return true;
				if (obj == null)
					return false;
				if (getClass() != obj.getClass())
					return false;
				CellCoordinates other = (CellCoordinates) obj;
				if (col != other.col)
					return false;
				if (row != other.row)
					return false;
				return true;
			}
		}

		private static int nonNegativeInteger(String s) {
			try {
				int i = Integer.parseInt(s);
				if (i >= 0)
					return i; }
			catch(NumberFormatException e) {}
			throw new RuntimeException("Expected positive integer but got "+ s);
		}
	}

	/* Remove the first part of the selector, or the whole selector if it exists of only one part */
	private static RuleBlock<Rule<?>> rest(RuleRelativeBlock rule) {
		List<Selector> combinedSelector = rule.getSelector();
		if (combinedSelector.size() == 0 || combinedSelector.get(0).size() == 0)
			throw new RuntimeException("coding error");
		SelectorPart first = combinedSelector.get(0).get(0);
		if (first instanceof PseudoElementImpl) {
			// combinedSelector.get(0).size() should normally always be 1
			List<Selector> rest = combinedSelector.subList(1, combinedSelector.size());
			RuleBlock<Rule<?>> newRule;
			PseudoElementImpl pseudo = (PseudoElementImpl)first;
			if (pseudo.hasStackedPseudoElement()) {
				combinedSelector = new ArrayList<>();
				Selector selector = (Selector)new SelectorImpl().unlock();
				selector.add(pseudo.getStackedPseudoElement());
				combinedSelector.add(selector);
				combinedSelector.addAll(rest);
				newRule = new RuleRelativeBlock(combinedSelector);
			} else {
				combinedSelector = pseudo.getCombinedSelectors();
				newRule = combinedSelector.isEmpty()
					? new AbstractRuleBlock<Rule<?>>()
					: new RuleRelativeBlock(combinedSelector);
			}
			newRule.replaceAll(rule); // we can do this because rule is considered immutable
			return newRule;
		} else {
			throw new RuntimeException("not implemented");
		}
	}

	private static String serializeRuleBlockList(Iterable<? extends RuleBlock<? extends Rule<?>>> ruleBlocks) {
		String b = null;
		for (RuleBlock<? extends Rule<?>> r : ruleBlocks) {
			String s;
			if (r instanceof RuleMainBlock)
				s = BrailleCssSerializer.toString((RuleMainBlock)r);
			else if (r instanceof RuleRelativeBlock)
				s = BrailleCssSerializer.toString((RuleRelativeBlock)r);
			else
				s = BrailleCssSerializer.toString(r);
			if (!s.isEmpty())
				if (b == null)
					b = s;
				else {
					if (!(b.endsWith("}") || b.endsWith(";")))
						b = b + ";";
					b += " ";
					b += s; }}
		if (b == null) b = "";
		return b;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

namespace SourceIndexingSharp.Git
{
    public class GitLibInitializer
    {
        static object _initLock = new object();
        static bool _isInitialized = false;

        public static void EnsureInitialized()
        {
            if(_isInitialized) return;

            lock (_initLock)
            {
                if(_isInitialized) return;

                LoadNativeGitDll();
            }
        }

        private static string GetNativeGitDllName()
        {
            var nativeDllNameType = Type.GetType("LibGit2Sharp.Core.NativeDllName, LibGit2Sharp");

            if(nativeDllNameType == null)
                throw new Exception("Couldn't reflect on the internal LibGit2Sharp class to get the name of the lib2git dll we need.");

            var nameField = nativeDllNameType.GetField("Name");

            if(nameField == null)
                throw new Exception("Couldn't get the reference to the constant 'Name' to get the name of the lib2git dll we need.");

            return (string)nameField.GetValue(null);
        }

        private static void LoadNativeGitDll()
        {
            var gitDllName = GetNativeGitDllName();

            var assemblyName = Assembly.GetExecutingAssembly().GetName();

            var dirName = Path.Combine(Path.GetTempPath(), assemblyName.Name + "." + Assembly.GetExecutingAssembly().GetName().Version);

            if (!Directory.Exists(dirName))
                Directory.CreateDirectory(dirName);

            var dllPath = Path.Combine(dirName, gitDllName + ".dll");

            var streamLocation = string.Format("SourceIndexingSharp.Git.Embedded.{0}.{1}.dll",
                IntPtr.Size == 4 ? "x86" : "x64", gitDllName);

            using (var stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(streamLocation))
            {
                if(stm == null)
                    throw new Exception("Couldn't find the embedded native dll at embedded location " + streamLocation);

                try
                {
                    using (Stream outFile = File.Create(dllPath))
                    {
                        const int sz = 4096;
                        var buf = new byte[sz];
                        while (true)
                        {
                            int nRead = stm.Read(buf, 0, sz);
                            if (nRead < 1)
                                break;
                            outFile.Write(buf, 0, nRead);
                        }
                    }
                }
                // ReSharper disable EmptyGeneralCatchClause
                catch
                // ReSharper restore EmptyGeneralCatchClause
                {
                    // This may happen if another process has already created and loaded the file.
                    // Since the directory includes the version number of this assembly we can
                    // assume that it's the same bits, so we just ignore the excecption here and
                    // load the DLL.
                }
            }

            var h = LoadLibrary(dllPath);

            if(h == IntPtr.Zero)
                throw new Exception("Unable to load library " + dllPath);
        }

        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr LoadLibrary(string lpFileName);
    }
}


text:
namespace engine {
namespace scene {

	DECLARE_CLASS(Entity, engine::component::ComponentHolder);

	void Entity::save(stream::OutputStream<stream::SerializationEndian> &strm) const
	{
		strm.write(name);
		strm.write(entityType);

		//Other data is inside the components, loop trough them and save them

		strm.write(components.size());
		for (unsigned i = 0; i < components.size(); ++i)
		{
			//Type to create
			strm.write(components[i]->getTypeInfo()->getTypeName());
			//What the component actually has in it
			components[i]->save(strm);
		}
	}

	void Entity::initComponents()
	{
		for (unsigned i = 0; i < components.size(); ++i)
			components[i]->init();
	}

	void Entity::load(stream::InputStream<stream::SerializationEndian> &strm)
	{
		if (!isContextValid())
		{
			LOG_ERROR("Trying to load entity! CONTEXT NOT SET! ABORTING!");
			return;
		}

		strm.read(name);
		strm.read(entityType);

		unsigned compCount;

		strm.read(compCount);

		for (unsigned i = 0; i < compCount; ++i)
		{
			String typeName;
			strm.read(typeName);

			component::Component *comp = engine::rtti::dynamicCast<component::Component>(rtti::RTTI::generateSerializable(typeName, getContextData()));

			comp->load(strm);

			this->addComponent(comp);
		}

		// call the init()'s on the components after the load
		for (unsigned i = 0; i < components.size(); ++i)
			components[i]->init();
	}

}
}


text:
require "spec_helper"

describe Salesforce::Field do

  describe '==' do
    before(:each) do
      @field = Salesforce::Field.new("the_name", "The Name", "string")
    end

    it 'should be false if other is nil' do
      (@field == nil).should be false
    end

    it "should be true if other is equal" do
      other_field = Salesforce::Field.new("the_name")
      (@field == other_field).should be true
    end

    it "should be false if other has a different name" do
      other_field = Salesforce::Field.new("other_name")
      (@field == other_field).should be false
    end
  end
end


text:
package org.apache.commons.jcs.jcache.extras.cdi;

import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessBean;
import java.util.Properties;

// add default CacheProvider and CacheManager
public class ExtraJCacheExtension implements Extension
{
    private static final boolean ACTIVATED = "true".equals(System.getProperty("org.apache.jcs.extra.cdi", "true"));

    private boolean cacheManagerFound = false;
    private boolean cacheProviderFound = false;
    private CacheManager cacheManager;
    private CachingProvider cachingProvider;

    public <A> void processBean(final @Observes ProcessBean<A> processBeanEvent)
    {
        if (!ACTIVATED)
        {
            return;
        }

        if (cacheManagerFound && cacheProviderFound)
        {
            return;
        }

        final Bean<A> bean = processBeanEvent.getBean();
        if (CacheManagerBean.class.isInstance(bean) || CacheProviderBean.class.isInstance(bean))
        {
            return;
        }

        if (!cacheManagerFound)
        {
            cacheManagerFound = bean.getTypes().contains(CacheManager.class);
        }
        if (!cacheProviderFound)
        {
            cacheProviderFound = bean.getTypes().contains(CachingProvider.class);
        }
    }

    public void addJCacheBeans(final @Observes AfterBeanDiscovery afterBeanDiscovery)
    {
        if (!ACTIVATED)
        {
            return;
        }

        if (cacheManagerFound && cacheProviderFound) {
            return;
        }

        cachingProvider = Caching.getCachingProvider();
        if (!cacheManagerFound)
        {
            cacheManager = cachingProvider.getCacheManager(
                    cachingProvider.getDefaultURI(),
                    cachingProvider.getDefaultClassLoader(),
                    new Properties());
            afterBeanDiscovery.addBean(new CacheManagerBean(cacheManager));
        }
        if (!cacheProviderFound)
        {
            afterBeanDiscovery.addBean(new CacheProviderBean(cachingProvider));
        }
    }

    public void destroyIfCreated(final @Observes BeforeShutdown beforeShutdown)
    {
        if (cacheManager != null)
        {
            cacheManager.close();
        }
        if (cachingProvider != null)
        {
            cachingProvider.close();
        }
    }
}


text:
Namespace('com.sjl.test');

com.sjl.test.simplejs2 = function()
{
	this.Speak = function()
	{
		alert('Hello World');
	};
};


text:
"use strict";

var Attempt = require( "attempt-js" );
var cashe = require( "cashe" );

var execInDir = cashe( function( dir ) {
	var exec = require( "child_process" ).exec;
	return function( command ) {
		return new Attempt( function( success, failure ) {
			exec( command, {
				cwd: dir,
				encoding: "utf8"
			}, function( error, stdout ) {
				if ( error ) {
					return failure( error );
				}
				success( stdout );
			} );
		} );
	};
} );

module.exports = function( commands, dir ) {
	var exec = execInDir(  dir || process.cwd() );
	return !Array.isArray( commands ) ? exec( commands ) : commands.reduce( function( attempt, command ) {
		return !attempt ? exec( command ) : attempt.chain( function() {
			return exec( command );
		} );
	}, false );
};


text:
{% load staticfiles %}
<link type="text/css" rel="stylesheet" href="{% static "css/navbar.css" %}" >

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Books & Beyond E-Magazine

Current Issue

Archive

Send a Letter to Book Bear

Contact

          Dropdown

Sign Up

Sign In

Profile

Sign Out


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
		  package="link.standen.michael.fatesheets">

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

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
		<activity
			android:name=".activity.CoreCharacterEditActivity"
			android:label="@string/title_activity_character_edit"
			android:parentActivityName=".activity.CharacterListActivity"
			android:theme="@style/AppTheme.NoActionBar">
			<meta-data
				android:name="android.support.PARENT_ACTIVITY"
				android:value="link.standen.michael.fatesheets.activity.CharacterListActivity"/>
		</activity>
		<activity
			android:name=".activity.FAECharacterEditActivity"
			android:label="@string/title_activity_character_edit"
			android:parentActivityName=".activity.CharacterListActivity"
			android:theme="@style/AppTheme.NoActionBar">
			<meta-data
				android:name="android.support.PARENT_ACTIVITY"
				android:value="link.standen.michael.fatesheets.activity.CharacterListActivity"/>
		</activity>
		<activity android:name=".activity.CreditsActivity"
			android:label="@string/title_activity_credits"
			android:theme="@style/AppTheme.NoActionBar">
		</activity>
		<activity android:name=".activity.EditSkillsActivity"
			android:label="@string/title_activity_edit_skills"
			android:theme="@style/AppTheme.NoActionBar"
			android:windowSoftInputMode="stateHidden">
		</activity>
		<provider
			android:name="android.support.v4.content.FileProvider"
			android:authorities="${applicationId}.provider"
			android:exported="false"
			android:grantUriPermissions="true">
			<meta-data
				android:name="android.support.FILE_PROVIDER_PATHS"
				android:resource="@xml/provider_paths"/>
		</provider>
	</application>

</manifest>


text:
require "spring/env"

module Spring
  module Test
    class Application
      DEFAULT_TIMEOUT = ENV['CI'] ? 30 : 10

      attr_reader :root, :spring_env

      def initialize(root)
        @root       = Pathname.new(root)
        @spring_env = Spring::Env.new(root: root)
        @times      = nil
      end

      def exists?
        root.exist?
      end

      def stdout
        @stdout ||= IO.pipe
      end

      def stderr
        @stderr ||= IO.pipe
      end

      def log_file
        @log_file ||= path("tmp/spring.log").open("w+")
      end

      def env
        @env ||= {
          "GEM_HOME"   => gem_home.to_s,
          "GEM_PATH"   => gem_home.to_s,
          "HOME"       => user_home.to_s,
          "RAILS_ENV"  => nil,
          "RACK_ENV"   => nil,
          "SPRING_LOG" => log_file.path
        }
      end

      def path(addition)
        root.join addition
      end

      def gemfile
        path "Gemfile"
      end

      def gem_home
        path "../gems/#{RUBY_VERSION}"
      end

      def user_home
        path "user_home"
      end

      def spring
        gem_home.join "bin/spring"
      end

      def rails_version
        @rails_version ||= RailsVersion.new(gemfile.read.match(/gem 'rails', '(.*)'/)[1])
      end

      def spring_test_command
        "bin/rake test #{test}"
      end

      def stop_spring
        run "#{spring} stop"
      rescue Errno::ENOENT
      end

      def test
        path "test/controllers/posts_controller_test.rb"
      end

      def controller
        path "app/controllers/posts_controller.rb"
      end

      def application_config
        path "config/application.rb"
      end

      def spring_config
        path "config/spring.rb"
      end

      def spring_client_config
        path "config/spring_client.rb"
      end

      def run(command, opts = {})
        start_time = Time.now

        Bundler.with_clean_env do
          Process.spawn(
            env,
            command.to_s,
            out:   stdout.last,
            err:   stderr.last,
            in:    :close,
            chdir: root.to_s,
          )
        end

        _, status = Timeout.timeout(opts.fetch(:timeout, DEFAULT_TIMEOUT)) { Process.wait2 }

        if pid = spring_env.pid
          @server_pid = pid
          lines = `ps -A -o ppid= -o pid= | egrep '^\\s*#{@server_pid}'`.lines
          @application_pids = lines.map { |l| l.split.last.to_i }
        end

        output = read_streams
        puts dump_streams(command, output) if ENV["SPRING_DEBUG"]

        @times << (Time.now - start_time) if @times

        output.merge(status: status, command: command)
      rescue Timeout::Error
        raise Timeout::Error, "While running command:\n\n#{dump_streams(command, read_streams)}"
      end

      def with_timing
        @times = []
        yield
      ensure
        @times = nil
      end

      def last_time
        @times.last
      end

      def first_time
        @times.first
      end

      def timing_ratio
        last_time / first_time
      end

      def read_streams
        {
          stdout: read_stream(stdout.first),
          stderr: read_stream(stderr.first),
          log:    read_stream(log_file)
        }
      end

      def read_stream(stream)
        output = ""
        while IO.select([stream], [], [], 0.5) && !stream.eof?
          output << stream.readpartial(10240)
        end
        output
      end

      def dump_streams(command, streams)
        output = "$ #{command}\n"

        streams.each do |name, stream|
          unless stream.chomp.empty?
            output << "--- #{name} ---\n"
            output << "#{stream.chomp}\n"
          end
        end

        output << "\n"
        output
      end

      def debug(artifacts)
        artifacts = artifacts.dup
        artifacts.delete :status
        dump_streams(artifacts.delete(:command), artifacts)
      end

      def await_reload
        raise "no pid" if @application_pids.nil? || @application_pids.empty?

        Timeout.timeout(DEFAULT_TIMEOUT) do
          sleep 0.1 while @application_pids.any? { |p| process_alive?(p) }
        end
      end

      def run!(command, options = {})
        attempts  = (options.delete(:retry) || 0) + 1
        artifacts = nil

        until attempts == 0 || artifacts && artifacts[:status].success?
          artifacts = run(command, options)
          attempts -= 1
        end

        if artifacts[:status].success?
          artifacts
        else
          raise "command failed\n\n#{debug(artifacts)}"
        end
      end

      def bundle
        # Version restriction is a workaround for https://github.com/bundler/bundler/pull/4981
        # The problem breaks our tests on Ruby 2.2
        # We can remove once it's fixed
        run! "(gem list bundler | grep bundler) || gem install bundler --version '~> 1.12.0'", timeout: nil, retry: 2
        run! "bundle check || bundle update --retry=2", timeout: nil
      end

      def insert_into_test(code)
        File.write(test, test.read.sub(/^\s*get .+$/, code))
      end

      private

      def process_alive?(pid)
        Process.kill 0, pid
        true
      rescue Errno::ESRCH
        false
      end
    end
  end
end


text:
package org.kuali.kra.iacuc.species;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.iacuc.IacucProtocolAction;
import org.kuali.kra.iacuc.IacucProtocolDocument;
import org.kuali.kra.iacuc.IacucProtocolForm;
import org.kuali.kra.iacuc.species.rule.AddProtocolSpeciesEvent;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class IacucProtocolSpeciesAction extends IacucProtocolAction{
    private static final String CONFIRM_DELETE_PROTOCOL_SPECIES_KEY = "confirmDeleteProtocolSpecies";
    private static final String DUPLICATE_SPECIES_ERROR_PATH = "iacucProtocolSpeciesHelper.newIacucProtocolSpecies";
    private static final String DUPLICATE_SPECIES_ERROR_KEY = "error.iacuc.validation.duplicate.group";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ActionForward forward = super.execute(mapping, form, request, response);

        IacucProtocolForm protocolForm = (IacucProtocolForm) form;

        protocolForm.getIacucProtocolSpeciesHelper().prepareView();

        return forward;
    }

    public ActionForward addProtocolSpecies(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        IacucProtocolForm protocolForm = (IacucProtocolForm) form;
        IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();
        List<IacucProtocolSpecies> iacucProtocolSpeciesList = document.getIacucProtocol().getIacucProtocolSpeciesList();
        IacucProtocolSpecies iacucProtocolSpecies = protocolForm.getIacucProtocolSpeciesHelper().getNewIacucProtocolSpecies();

        // look for duplicates
        boolean found = false;
        for (IacucProtocolSpecies oldSpecies: iacucProtocolSpeciesList) {
            if (iacucProtocolSpecies.isSameGroupAs(oldSpecies)) {
                GlobalVariables.getMessageMap().clearErrorPath();
                GlobalVariables.getMessageMap().addToErrorPath(DUPLICATE_SPECIES_ERROR_PATH);
                GlobalVariables.getMessageMap().putError("speciesGroup", DUPLICATE_SPECIES_ERROR_KEY);
               found = true;
            }
        }

        if (!found) {
            if (applyRules(new AddProtocolSpeciesEvent(Constants.EMPTY_STRING, document, iacucProtocolSpecies))) {
                getIacucProtocolSpeciesService().addProtocolSpecies(document.getIacucProtocol(), iacucProtocolSpecies);
                protocolForm.getIacucProtocolSpeciesHelper().setNewIacucProtocolSpecies(new IacucProtocolSpecies());
            }
        }

        return mapping.findForward(Constants.MAPPING_BASIC);
    }

    public ActionForward deleteProtocolSpecies(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception {
        return confirm(buildParameterizedConfirmationQuestion(mapping, form, request, response, CONFIRM_DELETE_PROTOCOL_SPECIES_KEY,
                KeyConstants.QUESTION_PROTOCOL_SPECIES_DELETE_CONFIRMATION), CONFIRM_DELETE_PROTOCOL_SPECIES_KEY, "");
    }

    @SuppressWarnings("deprecation")
    public ActionForward confirmDeleteProtocolSpecies(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception {
        Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
        if (CONFIRM_DELETE_PROTOCOL_SPECIES_KEY.equals(question)) {
            IacucProtocolForm protocolForm = (IacucProtocolForm) form;
            IacucProtocolDocument document = protocolForm.getIacucProtocolDocument();

            document.getIacucProtocol().getIacucProtocolSpeciesList().remove(getLineToDelete(request));
        }
        return mapping.findForward(Constants.MAPPING_BASIC);
    }

    protected IacucProtocolSpeciesService getIacucProtocolSpeciesService() {
        return (IacucProtocolSpeciesService) KcServiceLocator.getService("iacucProtocolSpeciesService");
    }

}


text:
class IndexAccountsOnUidAndProvider < ActiveRecord::Migration
  def change
    add_index :accounts, [:uid, :provider], unique: true
  end
end


text:
from django.core.urlresolvers import reverse

from zope.interface import implements

from vumi.tests.helpers import generate_proxies, IHelper

from go.base import utils as base_utils
from go.base.tests.helpers import DjangoVumiApiHelper
from .helpers import RouterHelper

class RouterViewsHelper(object):
    implements(IHelper)

    def __init__(self, router_type):
        self.router_type = router_type

        self.vumi_helper = DjangoVumiApiHelper()
        self._router_helper = RouterHelper(
            router_type, self.vumi_helper)

        # Proxy methods from our helpers.
        generate_proxies(self, self._router_helper)
        generate_proxies(self, self.vumi_helper)

    def setup(self):
        self.vumi_helper.setup()
        self.vumi_helper.make_django_user()

    def cleanup(self):
        return self.vumi_helper.cleanup()

    def get_new_view_url(self):
        return reverse('routers:new_router')

    def get_router_helper(self, router):
        return self.get_router_helper_by_key(router.key)

    def create_router_helper(self, *args, **kw):
        router = self.create_router(*args, **kw)
        return self.get_router_helper(router)

    def get_router_helper_by_key(self, router_key):
        return RouterViewHelper(self, router_key)

    def get_api_commands_sent(self):
        return base_utils.connection.get_commands()

class RouterViewHelper(object):
    def __init__(self, router_views_helper, router_key):
        self.router_key = router_key
        self.router_type = router_views_helper.router_type
        self.router_helper = router_views_helper

    def get_view_url(self, view):
        view_def = base_utils.get_router_view_definition(
            self.router_type)
        return view_def.get_view_url(
            view, router_key=self.router_key)

    def get_router(self):
        return self.router_helper.get_router(self.router_key)


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/web_package/web_bundle_parser_factory.h"

#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace web_package {

namespace {

base::FilePath GetTestFilePath(const base::FilePath& path) {
  base::FilePath test_path;
  base::PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
  test_path = test_path.Append(
      base::FilePath(FILE_PATH_LITERAL("components/test/data/web_package")));
  return test_path.Append(path);
}

}  // namespace

class WebBundleParserFactoryTest : public testing::Test {
 public:
  WebBundleParserFactoryTest()
      : factory_(std::make_unique<WebBundleParserFactory>()) {}

  std::unique_ptr<mojom::BundleDataSource> CreateFileDataSource(
      mojo::PendingReceiver<mojom::BundleDataSource> receiver,
      base::File file) {
    return factory_->CreateFileDataSourceForTesting(std::move(receiver),
                                                    std::move(file));
  }

  void GetParserForFile(mojo::PendingReceiver<mojom::WebBundleParser> receiver,
                        base::File file) {
    mojom::WebBundleParserFactory* factory = factory_.get();
    return factory->GetParserForFile(std::move(receiver), std::move(file));
  }

 private:
  std::unique_ptr<WebBundleParserFactory> factory_;
  base::test::TaskEnvironment task_environment_;
};

TEST_F(WebBundleParserFactoryTest, FileDataSource) {
  base::FilePath test_file =
      GetTestFilePath(base::FilePath(FILE_PATH_LITERAL("hello_b2.wbn")));

  base::File file(test_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(file.IsValid());
  int64_t file_length = file.GetLength();
  constexpr int64_t test_length = 16;
  ASSERT_LE(test_length, file_length);
  std::vector<uint8_t> first16b(test_length);
  ASSERT_EQ(test_length, file.Read(0, reinterpret_cast<char*>(first16b.data()),
                                   first16b.size()));
  std::vector<uint8_t> last16b(test_length);
  ASSERT_EQ(test_length,
            file.Read(file_length - test_length,
                      reinterpret_cast<char*>(last16b.data()), last16b.size()));

  mojo::PendingRemote<mojom::BundleDataSource> remote;
  auto data_source = CreateFileDataSource(
      remote.InitWithNewPipeAndPassReceiver(), std::move(file));

  absl::optional<std::vector<uint8_t>> result_data;
  {
    base::RunLoop run_loop;
    data_source->Read(
        /*offset=*/0, test_length,
        base::BindLambdaForTesting(
            [&result_data,
             &run_loop](const absl::optional<std::vector<uint8_t>>& data) {
              result_data = data;
              run_loop.QuitClosure().Run();
            }));
    run_loop.Run();
  }
  ASSERT_TRUE(result_data);
  EXPECT_EQ(first16b, *result_data);

  {
    base::RunLoop run_loop;
    data_source->Read(
        file_length - test_length, test_length,
        base::BindLambdaForTesting(
            [&result_data,
             &run_loop](const absl::optional<std::vector<uint8_t>>& data) {
              result_data = data;
              run_loop.QuitClosure().Run();
            }));
    run_loop.Run();
  }
  ASSERT_TRUE(result_data);
  EXPECT_EQ(last16b, *result_data);

  {
    base::RunLoop run_loop;
    data_source->Read(
        file_length - test_length, test_length + 1,
        base::BindLambdaForTesting(
            [&result_data,
             &run_loop](const absl::optional<std::vector<uint8_t>>& data) {
              result_data = data;
              run_loop.QuitClosure().Run();
            }));
    run_loop.Run();
  }
  ASSERT_TRUE(result_data);
  EXPECT_EQ(last16b, *result_data);

  {
    base::RunLoop run_loop;
    data_source->Read(
        file_length + 1, test_length,
        base::BindLambdaForTesting(
            [&result_data,
             &run_loop](const absl::optional<std::vector<uint8_t>>& data) {
              result_data = data;
              run_loop.QuitClosure().Run();
            }));
    run_loop.Run();
  }
  ASSERT_FALSE(result_data);
}

TEST_F(WebBundleParserFactoryTest, GetParserForFile) {
  base::File file(
      GetTestFilePath(base::FilePath(FILE_PATH_LITERAL("hello_b2.wbn"))),
      base::File::FLAG_OPEN | base::File::FLAG_READ);
  ASSERT_TRUE(file.IsValid());

  mojo::Remote<mojom::WebBundleParser> parser;
  GetParserForFile(parser.BindNewPipeAndPassReceiver(), std::move(file));

  mojom::BundleMetadataPtr metadata;
  {
    base::RunLoop run_loop;
    parser->ParseMetadata(base::BindLambdaForTesting(
        [&metadata, &run_loop](mojom::BundleMetadataPtr parsed_metadata,
                               mojom::BundleMetadataParseErrorPtr error) {
          metadata = std::move(parsed_metadata);
          run_loop.QuitClosure().Run();
        }));
    run_loop.Run();
  }
  ASSERT_TRUE(metadata);
  ASSERT_EQ(metadata->requests.size(), 4u);

  std::map<std::string, mojom::BundleResponsePtr> responses;
  for (const auto& item : metadata->requests) {
    ASSERT_TRUE(item.second->variants_value.empty());
    ASSERT_EQ(item.second->response_locations.size(), 1u);
    base::RunLoop run_loop;
    parser->ParseResponse(item.second->response_locations[0]->offset,
                          item.second->response_locations[0]->length,
                          base::BindLambdaForTesting(
                              [&item, &responses, &run_loop](
                                  mojom::BundleResponsePtr response,
                                  mojom::BundleResponseParseErrorPtr error) {
                                ASSERT_TRUE(response);
                                ASSERT_FALSE(error);
                                responses[item.first.spec()] =
                                    std::move(response);
                                run_loop.QuitClosure().Run();
                              }));
    run_loop.Run();
  }
  ASSERT_TRUE(responses["https://test.example.org/"]);
  EXPECT_EQ(responses["https://test.example.org/"]->response_code, 200);
  EXPECT_EQ(
      responses["https://test.example.org/"]->response_headers["content-type"],
      "text/html; charset=utf-8");
  EXPECT_TRUE(responses["https://test.example.org/index.html"]);
  EXPECT_TRUE(responses["https://test.example.org/manifest.webmanifest"]);
  EXPECT_TRUE(responses["https://test.example.org/script.js"]);
}

}  // namespace web_package


text:
layout:     post
title: "CS61A-Discussion 03"
subtitle:   "Data Abstraction"
author: "Tianxiang Gao"
date: "May 12, 2015"
header-img: "img/post-bg-02.jpg"
---
Discussion 03: Recursion and Tree Recusion
------------------------------------------
We don't have to worry about *how* code is implemented, but just have to know *what* it does.

* **Constructors** are functions that build the abstract data type
* **Selectors** are functions that retrieve information from the data type

## 1 Data Abstraction

### 1.1 Data Abstraction Practice

Hadley Cycle. Write a function near_thirty(city, diff) that checks whether an input city is within diff degrees of 30 degrees N or 30 degrees S.

def near_thirty(city, diff):
    city_lat = get_lat(city)
    return abs(city_lat - 30) <= 30 or abs(city_lat + 30) <= 30

Implement closer_city, a function that takes a latitude, longitude, and two cities, and returns the name of the city that is relatively closer to the provided latitude and
longitude.

def closer_city(lat, lon, city1, city2):
    target_city = make_city('new', lat, lon)
    dist1 = distance(target_city, city1)
    dist2 = distance(target_city, city2)
    return get_name(city1) if dist1 < dist2 else get_name(city2)

## 2 Let's be rational!

### 2.1 Rational Number Practice

Write a function that returns the given rational number x raised to positive power e.

from math import pow
def rational_pow(x,e):
    return 1 if e == 0 else mul_rational(x, rational_pow(x, e-1))

The irrational number $e ≈ 2.718$ can be generated from an infinite series. Write a function approx_e that returns a rational number approximation of e to iter amount of iterations. We've provided a factorial function.

def factorial(n):
    return 1 if n == 0 else n * factorial(n-1)

def approx_e(iter=100):
    e = rational(0, 1)
    for i in range(iter):
        e = add_rationals(e, rational(1, factorial(i)))
    return e

Implement inverse_rational and div_rationals

def inverse_rational(x):
    """Returns the inverse of the given non-zero rational
    number"""
    n = number(x)
    d = denom(x)
    return rational(d, n)

def div_rationals(x, y):
    """Returns x / y for given rational x and non-zero
    rational y"""
    return mul_rational(x, inverse_rational(y))

## My Life for Abstraction

### 3.1 Lists, or Zerg Rush!

Implement the constructors and selectors for the unit data abstraction using lists. Each unit will have a string catchphrase and an integer amount of damage.

def make_unit(catchphrase, damage):
    return [catchphrase, damage]

def get_catchphrase(unit):
    return unit[0]

def get_damage(unit):
    return unit[1]

### 3.2 Data Abstraction Violations, or, I Long For Combat!
Data abstraction violations happen when we assume we know something about how our data is represented. For example, if we use pairs and we forget to use a selector and instead use the index.

Let's simulate a battle between units!

def battle(first, second):
    """Simulates a battle between the first and second unit
    >>> zealot = make_unit('My life for Aiur!', 16)
    >>> zergling = make_unit('GRAAHHH!', 5)
    >>> winner = battle(zergling, zealot)
    GRAAHHH!
    My life for Aiur!
    >>> winner is zealot
    True
    """
    print(get_catchphrase(first))
    print(get_catchphrase(second))
    return first if get_damage(first) > get_damage(second) else second

### 3.3 Functional Pairs, or, We Require More Minerals

def pair(x, y):
    """Return a function that represents a pair."""
    def get(index):
        if index == 0:
            return x
        elif index == 1:
            return y
    return get

def select(p, i):
    """Return the element at index i of pair p"""
    return p(i)

Write constructors and selectors for a data abstraction that combines an integer amount
of minerals and gas together into a bundle. Use functional pair and select.

def make_resource_bundle(minerals, gas):
    return pair(minerals, gas)

def get_minerals(bundle):
    return select(bundle, 0)

def get_gas(bundle):
    return select(bundle, 1)

### 3.4 Putting It All Together

Let's make a building pair that is constructed with a unit data type and a resource bundle data type. This time take your choice of lists or functional pairs in representing a building. Make sure not to violate any data abstractions.

def make_building(unit, bundle):
    return pair(unit, bundle)

def get_unit(building):
    return select(building, 0)

def get_bundle(building):
    return select(building, 1)

Implement build_unit.

def build_unit(building, bundle):
    """Constructs a unit if given the minimum amount of
    resources. Otherwise, prints an error message.
    >>> barracks = make_building(make_unit('Go go go!', 6),
    ... make_resource_bundle(50, 0))
    >>> marine = build_unit(barracks, make_resource_bundle(20,
    20))
    We require more minerals!
    >>> marine = build_unit(barracks, make_resource_bundle(50,
    0))
    >>> print(get_catchphrase(marine))
    Go go go!
    """
    resource_minerals = get_minerals(bundle)
    resource_gas = get_gas(bundle)

    bundle_needed = get_bundle(building)
    minerals_needed = get_minerals(bundle_needed)
    gas_needed = get_gas(bundle_needed)

    if resource_minerals < minerals_needed:
        return print('We require more minerals!')

    if resource_gas < gas_needed:
        return print('We require more vespene gas!')

    return get_unit(building)

Reimplement the resource abstraction to use lists instead of functional pairs. Then verify that all the code that use the resource still works.

def make_resource_bundle(minerals, gas):
    return [minerals, gas]

def get_minerals(bundle):
    return bundle[0]

def get_gas(bundle):
    return bundle[1]


text:
package com.opengamma.financial.analytics.model.hullwhitediscounting;

import static com.opengamma.engine.value.ValueRequirementNames.BLOCK_CURVE_SENSITIVITIES;

import java.util.HashSet;
import java.util.Set;

import org.threeten.bp.Instant;

import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor;
import com.opengamma.analytics.financial.provider.calculator.generic.MarketQuoteSensitivityBlockCalculator;
import com.opengamma.analytics.financial.provider.calculator.hullwhite.PresentValueCurveSensitivityHullWhiteCalculator;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle;
import com.opengamma.analytics.financial.provider.description.interestrate.HullWhiteOneFactorProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.parameter.ParameterSensitivityParameterCalculator;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;

/**
 *
 */
public class HullWhiteDiscountingBCSFunction extends HullWhiteDiscountingFunction {
  /** The curve sensitivity calculator */
  private static final InstrumentDerivativeVisitor<HullWhiteOneFactorProviderInterface, MultipleCurrencyMulticurveSensitivity> PVCSDC =
      PresentValueCurveSensitivityHullWhiteCalculator.getInstance();
  /** The parameter sensitivity calculator */
  private static final ParameterSensitivityParameterCalculator<HullWhiteOneFactorProviderInterface> PSC =
      new ParameterSensitivityParameterCalculator<>(PVCSDC);
  /** The market quote sensitivity calculator */
  private static final MarketQuoteSensitivityBlockCalculator<HullWhiteOneFactorProviderInterface> CALCULATOR =
      new MarketQuoteSensitivityBlockCalculator<>(PSC);

  /**
   * Sets the value requirements to {@link ValueRequirementNames#BLOCK_CURVE_SENSITIVITIES}
   */
  public HullWhiteDiscountingBCSFunction() {
    super(BLOCK_CURVE_SENSITIVITIES);
  }

  @Override
  public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
    return new HullWhiteCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), false) {

      @Override
      protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs,
          final ComputationTarget target, final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative,
          final FXMatrix fxMatrix) {
        final Set<ComputedValue> result = new HashSet<>();
        final HullWhiteOneFactorProviderInterface curves = getMergedProviders(inputs, fxMatrix);
        final CurveBuildingBlockBundle blocks = getMergedCurveBuildingBlocks(inputs);
        final MultipleCurrencyParameterSensitivity sensitivities = CALCULATOR.fromInstrument(derivative, curves, blocks);
        for (final ValueRequirement desiredValue : desiredValues) {
          final ValueSpecification spec = new ValueSpecification(BLOCK_CURVE_SENSITIVITIES, target.toSpecification(), desiredValue.getConstraints().copy().get());
          result.add(new ComputedValue(spec, sensitivities));
        }
        return result;
      }

    };
  }

}


text:
package com.huahuacaocao.hhcc_common.base.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * 防止listview和gridview、ScrollView的冲突
 * @author zsl
 * @blog http://blog.csdn.net/yy1300326388
 *
 */
public class MyListView extends ListView {

	public MyListView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	//防止数据显示不全
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
				MeasureSpec.AT_MOST);
		super.onMeasure(widthMeasureSpec, expandSpec);
	}
}