/*
 * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sun.org.apache.xalan.internal.xsltc.dom;

import com.sun.org.apache.xalan.internal.xsltc.DOM;
import com.sun.org.apache.xalan.internal.xsltc.DOMEnhancedForDTM;
import com.sun.org.apache.xalan.internal.xsltc.StripFilter;
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
import com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary;
import com.sun.org.apache.xml.internal.dtm.Axis;
import com.sun.org.apache.xml.internal.dtm.DTM;
import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
import com.sun.org.apache.xml.internal.dtm.DTMManager;
import com.sun.org.apache.xml.internal.dtm.DTMWSFilter;
import com.sun.org.apache.xml.internal.dtm.ref.DTMAxisIterNodeList;
import com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBase;
import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeProxy;
import com.sun.org.apache.xml.internal.dtm.ref.EmptyIterator;
import com.sun.org.apache.xml.internal.dtm.ref.sax2dtm.SAX2DTM2;
import com.sun.org.apache.xml.internal.serializer.SerializationHandler;
import com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler;
import com.sun.org.apache.xml.internal.utils.SystemIDResolver;
import com.sun.org.apache.xml.internal.utils.XMLStringFactory;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Entity;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 * SAXImpl is the core model for SAX input source. SAXImpl objects are
 * usually created from an XSLTCDTMManager.
 *
 *
DOMSource inputs are handled using DOM2SAX + SAXImpl. SAXImpl has a
 * few specific fields (e.g. _node2Ids, _document) to keep DOM-related
 * information. They are used when the processing behavior between DOM and
 * SAX has to be different. Examples of these include id function and
 * unparsed entity.
 *
 *
SAXImpl extends SAX2DTM2 instead of SAX2DTM for better performance.
 * @author Jacek Ambroziak
 * @author Santiago Pericas-Geertsen
 * @author Morten Jorgensen
 * @author Douglas Sellers <douglasjsellers@hotmail.com>
 * @LastModified: Oct 2017
 */
public final class SAXImpl extends SAX2DTM2
                           implements DOMEnhancedForDTM, DOMBuilder
{

    /* ------------------------------------------------------------------- */
    /* DOMBuilder fields BEGIN                                             */
    /* ------------------------------------------------------------------- */

    // Namespace prefix-to-uri mapping stuff
    private int       _uriCount     = 0;
    // private int       _prefixCount  = 0;

    // Stack used to keep track of what whitespace text nodes are protected
    // by xml:space="preserve" attributes and which nodes that are not.
    private int[]   _xmlSpaceStack;
    private int     _idx = 1;
    private boolean _preserve = false;

    // private static final String XML_STRING = "xml:";
    private static final String XML_PREFIX   = "xml";
    private static final String XMLSPACE_STRING = "xml:space";
    private static final String PRESERVE_STRING = "preserve";
    // private static final String XMLNS_PREFIX = "xmlns";
    private static final String XML_URI = "http://www.w3.org/XML/1998/namespace";

    private boolean _escaping = true;
    private boolean _disableEscaping = false;
    private int _textNodeToProcess = DTM.NULL;

    /* ------------------------------------------------------------------- */
    /* DOMBuilder fields END                                               */
    /* ------------------------------------------------------------------- */

    // empty String for null attribute values
    private final static String EMPTYSTRING = "";

    // empty iterator to be returned when there are no children
    private final static DTMAxisIterator EMPTYITERATOR = EmptyIterator.getInstance();
    // The number of expanded names
    private int _namesSize = -1;

    // Namespace related stuff
    private Map<Integer, Integer> _nsIndex = new HashMap<>();

    // The initial size of the text buffer
    private int _size = 0;

    // Tracks which textnodes are not escaped
    private BitArray  _dontEscape = null;

    // The URI to this document
    // private String _documentURI = null;
    static private int _documentURIIndex = 0;

    // The owner Document when the input source is DOMSource.
    private Document _document;

    // The Map for org.w3c.dom.Node to node id mapping.
    // This is only used when the input is a DOMSource and the
    // buildIdIndex flag is true.
    private Map<Node, Integer> _node2Ids = null;

    // True if the input source is a DOMSource.
    private boolean _hasDOMSource = false;

    // The DTMManager
    private XSLTCDTMManager _dtmManager;

    // Support for access/navigation through org.w3c.dom API
    private Node[] _nodes;
    private NodeList[] _nodeLists;
    // private final static String XML_LANG_ATTRIBUTE = "http://www.w3.org/XML/1998/namespace:@lang";

    /**
     * Define the origin of the document from which the tree was built
     */
    public void setDocumentURI(String uri) {
        if (uri != null) {
            setDocumentBaseURI(SystemIDResolver.getAbsoluteURI(uri));
        }
    }

    /**
     * Returns the origin of the document from which the tree was built
     */
    public String getDocumentURI() {
        String baseURI = getDocumentBaseURI();
        return (baseURI != null) ? baseURI : "rtf" + _documentURIIndex++;
    }

    public String getDocumentURI(int node) {
        return getDocumentURI();
    }

    public void setupMapping(String[] names, String[] urisArray,
                             int[] typesArray, String[] namespaces) {
        // This method only has a function in DOM adapters
    }

    /**
     * Lookup a namespace URI from a prefix starting at node. This method
     * is used in the execution of xsl:element when the prefix is not known
     * at compile time.
     */
    public String lookupNamespace(int node, String prefix)
        throws TransletException
    {
        int anode, nsnode;
        final AncestorIterator ancestors = new AncestorIterator();

        if (isElement(node)) {
            ancestors.includeSelf();
        }

        ancestors.setStartNode(node);
        while ((anode = ancestors.next()) != DTM.NULL) {
            final NamespaceIterator namespaces = new NamespaceIterator();

            namespaces.setStartNode(anode);
            while ((nsnode = namespaces.next()) != DTM.NULL) {
                if (getLocalName(nsnode).equals(prefix)) {
                    return getNodeValue(nsnode);
                }
            }
        }

        BasisLibrary.runTimeError(BasisLibrary.NAMESPACE_PREFIX_ERR, prefix);
        return null;
    }

    /**
     * Returns 'true' if a specific node is an element (of any type)
     */
    public boolean isElement(final int node) {
        return getNodeType(node) == DTM.ELEMENT_NODE;
    }

    /**
     * Returns 'true' if a specific node is an attribute (of any type)
     */
    public boolean isAttribute(final int node) {
        return getNodeType(node) == DTM.ATTRIBUTE_NODE;
    }

    /**
     * Returns the number of nodes in the tree (used for indexing)
     */
    public int getSize() {
        return getNumberOfNodes();
    }

    /**
     * Part of the DOM interface - no function here.
     */
    public void setFilter(StripFilter filter) {
    }

    /**
     * Returns true if node1 comes before node2 in document order
     */
    public boolean lessThan(int node1, int node2) {
        if (node1 == DTM.NULL) {
            return false;
        }

        if (node2 == DTM.NULL) {
            return true;
        }

        return (node1 < node2);
    }

    /**
     * Create an org.w3c.dom.Node from a node in the tree
     */
    public Node makeNode(int index) {
        if (_nodes == null) {
            _nodes = new Node[_namesSize];
        }

        int nodeID = makeNodeIdentity(index);
        if (nodeID < 0) {
            return null;
        }
        else if (nodeID < _nodes.length) {
            return (_nodes[nodeID] != null) ? _nodes[nodeID]
                : (_nodes[nodeID] = new DTMNodeProxy((DTM)this, index));
        }
        else {
            return new DTMNodeProxy((DTM)this, index);
        }
    }

    /**
     * Create an org.w3c.dom.Node from a node in an iterator
     * The iterator most be started before this method is called
     */
    public Node makeNode(DTMAxisIterator iter) {
        return makeNode(iter.next());
    }

    /**
     * Create an org.w3c.dom.NodeList from a node in the tree
     */
    public NodeList makeNodeList(int index) {
        if (_nodeLists == null) {
            _nodeLists = new NodeList[_namesSize];
        }

        int nodeID = makeNodeIdentity(index);
        if (nodeID < 0) {
            return null;
        }
        else if (nodeID < _nodeLists.length) {
            return (_nodeLists[nodeID] != null) ? _nodeLists[nodeID]
                   : (_nodeLists[nodeID] = new DTMAxisIterNodeList(this,
                                                 new SingletonIterator(index)));
    }
        else {
            return new DTMAxisIterNodeList(this, new SingletonIterator(index));
        }
    }

    /**
     * Create an org.w3c.dom.NodeList from a node iterator
     * The iterator most be started before this method is called
     */
    public NodeList makeNodeList(DTMAxisIterator iter) {
        return new DTMAxisIterNodeList(this, iter);
    }

    /**
     * Iterator that returns the namespace nodes as defined by the XPath data
     * model for a given node, filtered by extended type ID.
     */
    public class TypedNamespaceIterator extends NamespaceIterator {

        private  String _nsPrefix;

        /**
         * Constructor TypedChildrenIterator
         *
         *
         * @param nodeType The extended type ID being requested.
         */
        public TypedNamespaceIterator(int nodeType) {
            super();
            if(m_expandedNameTable != null){
                _nsPrefix = m_expandedNameTable.getLocalName(nodeType);
            }
        }

       /**
        * Get the next node in the iteration.
        *
        * @return The next node handle in the iteration, or END.
        */
        public int next() {
            if ((_nsPrefix == null) ||(_nsPrefix.length() == 0) ){
                return (END);
            }
            int node = END;
            for (node = super.next(); node != END; node = super.next()) {
                if (_nsPrefix.compareTo(getLocalName(node))== 0) {
                    return returnNode(node);
                }
            }
            return (END);
        }
    }  // end of TypedNamespaceIterator

    /**************************************************************
     * This is a specialised iterator for predicates comparing node or
     * attribute values to variable or parameter values.
     */
    private final class NodeValueIterator extends InternalAxisIteratorBase
    {

        private DTMAxisIterator _source;
        private String _value;
        private boolean _op;
        private final boolean _isReverse;
        private int _returnType = RETURN_PARENT;

        public NodeValueIterator(DTMAxisIterator source, int returnType,
                                 String value, boolean op)
        {
            _source = source;
            _returnType = returnType;
            _value = value;
            _op = op;
            _isReverse = source.isReverse();
        }

        public boolean isReverse()
        {
            return _isReverse;
        }

        public DTMAxisIterator cloneIterator()
        {
            try {
                NodeValueIterator clone = (NodeValueIterator)super.clone();
                clone._isRestartable = false;
                clone._source = _source.cloneIterator();
                clone._value = _value;
                clone._op = _op;
                return clone.reset();
            }
            catch (CloneNotSupportedException e) {
                BasisLibrary.runTimeError(BasisLibrary.ITERATOR_CLONE_ERR,
                                          e.toString());
                return null;
            }
        }

        public void setRestartable(boolean isRestartable)
        {
            _isRestartable = isRestartable;
            _source.setRestartable(isRestartable);
        }

        public DTMAxisIterator reset()
        {
            _source.reset();
            return resetPosition();
        }

        public int next()
        {
            int node;
            while ((node = _source.next()) != END) {
                String val = getStringValueX(node);
                if (_value.equals(val) == _op) {
                    if (_returnType == RETURN_CURRENT) {
                        return returnNode(node);
                    }
                    else {
                        return returnNode(getParent(node));
                    }
                }
            }
            return END;
        }

        public DTMAxisIterator setStartNode(int node)
        {
            if (_isRestartable) {
                _source.setStartNode(_startNode = node);
                return resetPosition();
            }
            return this;
        }

        public void setMark()
        {
            _source.setMark();
        }

        public void gotoMark()
        {
            _source.gotoMark();
        }
    } // end NodeValueIterator

    public DTMAxisIterator getNodeValueIterator(DTMAxisIterator iterator, int type,
                                             String value, boolean op)
    {
        return(DTMAxisIterator)(new NodeValueIterator(iterator, type, value, op));
    }

    /**
     * Encapsulates an iterator in an OrderedIterator to ensure node order
     */
    public DTMAxisIterator orderNodes(DTMAxisIterator source, int node)
    {
        return new DupFilterIterator(source);
    }

    /**
     * Returns singleton iterator containg the document root
     * Works for them main document (mark == 0).  It cannot be made
     * to point to any other node through setStartNode().
     */
    public DTMAxisIterator getIterator()
    {
        return new SingletonIterator(getDocument(), true);
    }

     /**
     * Get mapping from DOM namespace types to external namespace types
     */
    public int getNSType(int node)
    {
        String s = getNamespaceURI(node);
        if (s == null) {
            return 0;
        }
        int eType = getIdForNamespace(s);
        return _nsIndex.get(eType);
    }

    /**
     * Returns the namespace type of a specific node
     */
    public int getNamespaceType(final int node)
    {
        return super.getNamespaceType(node);
    }

    /**
     * Sets up a translet-to-dom type mapping table
     */
    /*
    private int[] setupMapping(String[] names, String[] uris, int[] types, int nNames) {
        // Padding with number of names, because they
        // may need to be added, i.e for RTFs. See copy03
        final int[] result = new int[m_expandedNameTable.getSize()];
        for (int i = 0; i < nNames; i++)      {
            //int type = getGeneralizedType(namesArray[i]);
            int type = m_expandedNameTable.getExpandedTypeID(uris[i], names[i], types[i], false);
            result[type] = type;
        }
        return result;
    }
    */

    /**
     * Returns the internal type associated with an expanded QName
     */
    public int getGeneralizedType(final String name) {
        return getGeneralizedType(name, true);
    }

    /**
     * Returns the internal type associated with an expanded QName
     */
    public int getGeneralizedType(final String name, boolean searchOnly) {
        String lName, ns = null;
        int index = -1;
        int code;

        // Is there a prefix?
        if ((index = name.lastIndexOf(":"))> -1) {
            ns = name.substring(0, index);
        }

        // Local part of name is after colon.  lastIndexOf returns -1 if
        // there is no colon, so lNameStartIdx will be zero in that case.
        int lNameStartIdx = index+1;

        // Distinguish attribute and element names.  Attribute has @ before
        // local part of name.
        if (name.charAt(lNameStartIdx) == '@') {
            code = DTM.ATTRIBUTE_NODE;
            lNameStartIdx++;
        }
        else {
            code = DTM.ELEMENT_NODE;
        }

        // Extract local name
        lName = (lNameStartIdx == 0) ? name : name.substring(lNameStartIdx);

        return m_expandedNameTable.getExpandedTypeID(ns, lName, code, searchOnly);
    }

    /**
     * Get mapping from DOM element/attribute types to external types
     */
    public short[] getMapping(String[] names, String[] uris, int[] types)
    {
        // Delegate the work to getMapping2 if the document is not fully built.
        // Some of the processing has to be different in this case.
        if (_namesSize < 0) {
            return getMapping2(names, uris, types);
        }

        int i;
        final int namesLength = names.length;
        final int exLength = m_expandedNameTable.getSize();

        final short[] result = new short[exLength];

        // primitive types map to themselves
        for (i = 0; i < DTM.NTYPES; i++) {
            result[i] = (short)i;
        }

        for (i = NTYPES; i < exLength; i++) {
            result[i] = m_expandedNameTable.getType(i);
        }

        // actual mapping of caller requested names
        for (i = 0; i < namesLength; i++) {
            int genType = m_expandedNameTable.getExpandedTypeID(uris[i],
                                                                names[i],
                                                                types[i],
                                                                true);
            if (genType >= 0 && genType < exLength) {
                result[genType] = (short)(i + DTM.NTYPES);
            }
        }

        return result;
    }

    /**
     * Get mapping from external element/attribute types to DOM types
     */
    public int[] getReverseMapping(String[] names, String[] uris, int[] types)
    {
        int i;
        final int[] result = new int[names.length + DTM.NTYPES];

        // primitive types map to themselves
        for (i = 0; i < DTM.NTYPES; i++) {
            result[i] = i;
        }

        // caller's types map into appropriate dom types
        for (i = 0; i < names.length; i++) {
            int type = m_expandedNameTable.getExpandedTypeID(uris[i], names[i], types[i], true);
            result[i+DTM.NTYPES] = type;
        }
        return(result);
    }

    /**
     * Get mapping from DOM element/attribute types to external types.
     * This method is used when the document is not fully built.
     */
    private short[] getMapping2(String[] names, String[] uris, int[] types)
    {
        int i;
        final int namesLength = names.length;
        final int exLength = m_expandedNameTable.getSize();
        int[] generalizedTypes = null;
        if (namesLength > 0) {
            generalizedTypes = new int[namesLength];
        }

        int resultLength = exLength;

        for (i = 0; i < namesLength; i++) {
            // When the document is not fully built, the searchOnly
            // flag should be set to false. That means we should add
            // the type if it is not already in the expanded name table.
            //generalizedTypes[i] = getGeneralizedType(names[i], false);
            generalizedTypes[i] =
                m_expandedNameTable.getExpandedTypeID(uris[i],
                                                      names[i],
                                                      types[i],
                                                      false);
            if (_namesSize < 0 && generalizedTypes[i] >= resultLength) {
                resultLength = generalizedTypes[i] + 1;
            }
        }

        final short[] result = new short[resultLength];

        // primitive types map to themselves
        for (i = 0; i < DTM.NTYPES; i++) {
            result[i] = (short)i;
        }

        for (i = NTYPES; i < exLength; i++) {
            result[i] = m_expandedNameTable.getType(i);
        }

        // actual mapping of caller requested names
        for (i = 0; i < namesLength; i++) {
            int genType = generalizedTypes[i];
            if (genType >= 0 && genType < resultLength) {
                result[genType] = (short)(i + DTM.NTYPES);
            }
        }

        return(result);
    }
    /**
     * Get mapping from DOM namespace types to external namespace types
     */
    public short[] getNamespaceMapping(String[] namespaces)
    {
        int i;
        final int nsLength = namespaces.length;
        final int mappingLength = _uriCount;

        final short[] result = new short[mappingLength];

        // Initialize all entries to -1
        for (i=0; i<mappingLength; i++) {
            result[i] = (short)(-1);
        }

        for (i=0; i<nsLength; i++) {
            int eType = getIdForNamespace(namespaces[i]);
            Integer type = _nsIndex.get(eType);
            if (type != null) {
                result[type] = (short)i;
            }
        }

        return(result);
    }

    /**
     * Get mapping from external namespace types to DOM namespace types
     */
    public short[] getReverseNamespaceMapping(String[] namespaces)
    {
        int i;
        final int length = namespaces.length;
        final short[] result = new short[length];

        for (i = 0; i < length; i++) {
            int eType = getIdForNamespace(namespaces[i]);
            Integer type = _nsIndex.get(eType);
            result[i] = (type == null) ? -1 : type.shortValue();
        }

        return result;
    }

    /**
     * Construct a SAXImpl object using the default block size.
     */
    public SAXImpl(XSLTCDTMManager mgr, Source source,
                   int dtmIdentity, DTMWSFilter whiteSpaceFilter,
                   XMLStringFactory xstringfactory,
                   boolean doIndexing, boolean buildIdIndex)
    {
        this(mgr, source, dtmIdentity, whiteSpaceFilter, xstringfactory,
            doIndexing, DEFAULT_BLOCKSIZE, buildIdIndex, false);
    }

    /**
     * Construct a SAXImpl object using the given block size.
     */
    public SAXImpl(XSLTCDTMManager mgr, Source source,
                   int dtmIdentity, DTMWSFilter whiteSpaceFilter,
                   XMLStringFactory xstringfactory,
                   boolean doIndexing, int blocksize,
                   boolean buildIdIndex,
                   boolean newNameTable)
    {
        super(mgr, source, dtmIdentity, whiteSpaceFilter, xstringfactory,
            doIndexing, blocksize, false, buildIdIndex, newNameTable);

        _dtmManager = mgr;
        _size = blocksize;

        // Use a smaller size for the space stack if the blocksize is small
        _xmlSpaceStack = new int[blocksize <= 64 ? 4 : 64];

        /* From DOMBuilder */
        _xmlSpaceStack[0] = DTMDefaultBase.ROOTNODE;

        // If the input source is DOMSource, set the _document field and
        // create the node2Ids table.
        if (source instanceof DOMSource) {
            _hasDOMSource = true;
            DOMSource domsrc = (DOMSource)source;
            Node node = domsrc.getNode();
            if (node instanceof Document) {
                _document = (Document)node;
            }
            else {
                _document = node.getOwnerDocument();
            }
            _node2Ids = new HashMap<>();
        }
    }

    /**
    * Migrate a DTM built with an old DTMManager to a new DTMManager.
    * After the migration, the new DTMManager will treat the DTM as
    * one that is built by itself.
    * This is used to support DTM sharing between multiple transformations.
    * @param manager the DTMManager
    */
    public void migrateTo(DTMManager manager) {
        super.migrateTo(manager);
        if (manager instanceof XSLTCDTMManager) {
            _dtmManager = (XSLTCDTMManager)manager;
        }
    }

    /**
     * Return the node identity for a given id String
     *
     * @param idString The id String
     * @return The identity of the node whose id is the given String.
     */
    public int getElementById(String idString)
    {
        Node node = _document.getElementById(idString);
        if (node != null) {
            Integer id = _node2Ids.get(node);
            return (id != null) ? id : DTM.NULL;
        }
        else {
            return DTM.NULL;
        }
    }

    /**
     * Return true if the input source is DOMSource.
     */
    public boolean hasDOMSource()
    {
        return _hasDOMSource;
    }

    /*---------------------------------------------------------------------------*/
    /* DOMBuilder methods begin                                                  */
    /*---------------------------------------------------------------------------*/

    /**
     * Call this when an xml:space attribute is encountered to
     * define the whitespace strip/preserve settings.
     */
    private void xmlSpaceDefine(String val, final int node)
    {
        final boolean setting = val.equals(PRESERVE_STRING);
        if (setting != _preserve) {
            _xmlSpaceStack[_idx++] = node;
            _preserve = setting;
        }
    }

    /**
     * Call this from endElement() to revert strip/preserve setting
     * to whatever it was before the corresponding startElement().
     */
    private void xmlSpaceRevert(final int node)
    {
        if (node == _xmlSpaceStack[_idx - 1]) {
            _idx--;
            _preserve = !_preserve;
        }
    }

    /**
     * Find out whether or not to strip whitespace nodes.
     *
     *
     * @return whether or not to strip whitespace nodes.
     */
    protected boolean getShouldStripWhitespace()
    {
        return _preserve ? false : super.getShouldStripWhitespace();
    }

    /**
     * Creates a text-node and checks if it is a whitespace node.
     */
    private void handleTextEscaping() {
        if (_disableEscaping && _textNodeToProcess != DTM.NULL
            && _type(_textNodeToProcess) == DTM.TEXT_NODE) {
            if (_dontEscape == null) {
                _dontEscape = new BitArray(_size);
            }

            // Resize the _dontEscape BitArray if necessary.
            if (_textNodeToProcess >= _dontEscape.size()) {
                _dontEscape.resize(_dontEscape.size() * 2);
            }

            _dontEscape.setBit(_textNodeToProcess);
            _disableEscaping = false;
        }
        _textNodeToProcess = DTM.NULL;
    }

    /****************************************************************/
    /*               SAX Interface Starts Here                      */
    /****************************************************************/

    /**
     * SAX2: Receive notification of character data.
     */
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        super.characters(ch, start, length);

        _disableEscaping = !_escaping;
        _textNodeToProcess = getNumberOfNodes();
    }

    /**
     * SAX2: Receive notification of the beginning of a document.
     */
    public void startDocument() throws SAXException
    {
        super.startDocument();

        _nsIndex.put(0, _uriCount++);
        definePrefixAndUri(XML_PREFIX, XML_URI);
    }

    /**
     * SAX2: Receive notification of the end of a document.
     */
    public void endDocument() throws SAXException
    {
        super.endDocument();

        handleTextEscaping();
        _namesSize = m_expandedNameTable.getSize();
    }

    /**
     * Specialized interface used by DOM2SAX. This one has an extra Node
     * parameter to build the Node -> id map.
     */
    public void startElement(String uri, String localName,
                             String qname, Attributes attributes,
                             Node node)
        throws SAXException
    {
        this.startElement(uri, localName, qname, attributes);

        if (m_buildIdIndex) {
            _node2Ids.put(node, m_parents.peek());
        }
    }

    /**
     * SAX2: Receive notification of the beginning of an element.
     */
    public void startElement(String uri, String localName,
                 String qname, Attributes attributes)
        throws SAXException
    {
        super.startElement(uri, localName, qname, attributes);

        handleTextEscaping();

        if (m_wsfilter != null) {
            // Look for any xml:space attributes
            // Depending on the implementation of attributes, this
            // might be faster than looping through all attributes. ILENE
            final int index = attributes.getIndex(XMLSPACE_STRING);
            if (index >= 0) {
                xmlSpaceDefine(attributes.getValue(index), m_parents.peek());
            }
        }
    }

    /**
     * SAX2: Receive notification of the end of an element.
     */
    public void endElement(String namespaceURI, String localName, String qname)
        throws SAXException
    {
        super.endElement(namespaceURI, localName, qname);

        handleTextEscaping();

        // Revert to strip/preserve-space setting from before this element
        if (m_wsfilter != null) {
            xmlSpaceRevert(m_previous);
        }
    }

    /**
     * SAX2: Receive notification of a processing instruction.
     */
    public void processingInstruction(String target, String data)
        throws SAXException
    {
        super.processingInstruction(target, data);
        handleTextEscaping();
    }

    /**
     * SAX2: Receive notification of ignorable whitespace in element
     * content. Similar to characters(char[], int, int).
     */
    public void ignorableWhitespace(char[] ch, int start, int length)
        throws SAXException
    {
        super.ignorableWhitespace(ch, start, length);
        _textNodeToProcess = getNumberOfNodes();
    }

    /**
     * SAX2: Begin the scope of a prefix-URI Namespace mapping.
     */
    public void startPrefixMapping(String prefix, String uri)
        throws SAXException
    {
        super.startPrefixMapping(prefix, uri);
        handleTextEscaping();

        definePrefixAndUri(prefix, uri);
    }

    private void definePrefixAndUri(String prefix, String uri)
        throws SAXException
    {
        // Check if the URI already exists before pushing on stack
        Integer eType = getIdForNamespace(uri);
        if (_nsIndex.get(eType) == null) {
            _nsIndex.put(eType, _uriCount++);
        }
    }

    /**
     * SAX2: Report an XML comment anywhere in the document.
     */
    public void comment(char[] ch, int start, int length)
        throws SAXException
    {
        super.comment(ch, start, length);
        handleTextEscaping();
    }

    public boolean setEscaping(boolean value) {
        final boolean temp = _escaping;
        _escaping = value;
        return temp;
    }

   /*---------------------------------------------------------------------------*/
   /* DOMBuilder methods end                                                    */
   /*---------------------------------------------------------------------------*/

    /**
     * Prints the whole tree to standard output
     */
    public void print(int node, int level)
    {
        switch(getNodeType(node))
        {
            case DTM.ROOT_NODE:
            case DTM.DOCUMENT_NODE:
                print(getFirstChild(node), level);
                break;
            case DTM.TEXT_NODE:
            case DTM.COMMENT_NODE:
            case DTM.PROCESSING_INSTRUCTION_NODE:
                System.out.print(getStringValueX(node));
                break;
            default:
                final String name = getNodeName(node);
                System.out.print("<" + name);
                for (int a = getFirstAttribute(node); a != DTM.NULL; a = getNextAttribute(a))
                {
                    System.out.print("\n" + getNodeName(a) + "=\"" + getStringValueX(a) + "\"");
                }
                System.out.print('>');
                for (int child = getFirstChild(node); child != DTM.NULL;
                    child = getNextSibling(child)) {
                    print(child, level + 1);
                }
                System.out.println("</" + name + '>');
                break;
        }
    }

    /**
     * Returns the name of a node (attribute or element).
     */
    public String getNodeName(final int node)
    {
        // Get the node type and make sure that it is within limits
        int nodeh = node;
        final short type = getNodeType(nodeh);
        switch(type)
        {
            case DTM.ROOT_NODE:
            case DTM.DOCUMENT_NODE:
            case DTM.TEXT_NODE:
            case DTM.COMMENT_NODE:
                return EMPTYSTRING;
            case DTM.NAMESPACE_NODE:
                return this.getLocalName(nodeh);
            default:
                return super.getNodeName(nodeh);
        }
    }

    /**
     * Returns the namespace URI to which a node belongs
     */
    public String getNamespaceName(final int node)
    {
        if (node == DTM.NULL) {
            return "";
        }

        String s;
        return (s = getNamespaceURI(node)) == null ? EMPTYSTRING : s;
    }

    /**
     * Returns the attribute node of a given type (if any) for an element
     */
    public int getAttributeNode(final int type, final int element)
    {
        for (int attr = getFirstAttribute(element);
           attr != DTM.NULL;
           attr = getNextAttribute(attr))
        {
            if (getExpandedTypeID(attr) == type) return attr;
        }
        return DTM.NULL;
    }

    /**
     * Returns the value of a given attribute type of a given element
     */
    public String getAttributeValue(final int type, final int element)
    {
        final int attr = getAttributeNode(type, element);
        return (attr != DTM.NULL) ? getStringValueX(attr) : EMPTYSTRING;
    }

    /**
     * This method is for testing/debugging only
     */
    public String getAttributeValue(final String name, final int element)
    {
        return getAttributeValue(getGeneralizedType(name), element);
    }

    /**
     * Returns an iterator with all the children of a given node
     */
    public DTMAxisIterator getChildren(final int node)
    {
        return (new ChildrenIterator()).setStartNode(node);
    }

    /**
     * Returns an iterator with all children of a specific type
     * for a given node (element)
     */
    public DTMAxisIterator getTypedChildren(final int type)
    {
        return(new TypedChildrenIterator(type));
    }

    /**
     * This is a shortcut to the iterators that implement the
     * supported XPath axes (only namespace::) is not supported.
     * Returns a bare-bones iterator that must be initialized
     * with a start node (using iterator.setStartNode()).
     */
    public DTMAxisIterator getAxisIterator(final int axis)
    {
        switch (axis)
        {
            case Axis.SELF:
                return new SingletonIterator();
            case Axis.CHILD:
                return new ChildrenIterator();
            case Axis.PARENT:
                return new ParentIterator();
            case Axis.ANCESTOR:
                return new AncestorIterator();
            case Axis.ANCESTORORSELF:
                return (new AncestorIterator()).includeSelf();
            case Axis.ATTRIBUTE:
                return new AttributeIterator();
            case Axis.DESCENDANT:
                return new DescendantIterator();
            case Axis.DESCENDANTORSELF:
                return (new DescendantIterator()).includeSelf();
            case Axis.FOLLOWING:
                return new FollowingIterator();
            case Axis.PRECEDING:
                return new PrecedingIterator();
            case Axis.FOLLOWINGSIBLING:
                return new FollowingSiblingIterator();
            case Axis.PRECEDINGSIBLING:
                return new PrecedingSiblingIterator();
            case Axis.NAMESPACE:
                return new NamespaceIterator();
            case Axis.ROOT:
                return new RootIterator();
            default:
                BasisLibrary.runTimeError(BasisLibrary.AXIS_SUPPORT_ERR,
                        Axis.getNames(axis));
        }
        return null;
    }

    /**
     * Similar to getAxisIterator, but this one returns an iterator
     * containing nodes of a typed axis (ex.: child::foo)
     */
    public DTMAxisIterator getTypedAxisIterator(int axis, int type)
    {
        // Most common case handled first
        if (axis == Axis.CHILD) {
            return new TypedChildrenIterator(type);
        }

        if (type == NO_TYPE) {
            return(EMPTYITERATOR);
        }

        switch (axis)
        {
            case Axis.SELF:
                return new TypedSingletonIterator(type);
            case Axis.CHILD:
                return new TypedChildrenIterator(type);
            case Axis.PARENT:
                return new ParentIterator().setNodeType(type);
            case Axis.ANCESTOR:
                return new TypedAncestorIterator(type);
            case Axis.ANCESTORORSELF:
                return (new TypedAncestorIterator(type)).includeSelf();
            case Axis.ATTRIBUTE:
                return new TypedAttributeIterator(type);
            case Axis.DESCENDANT:
                return new TypedDescendantIterator(type);
            case Axis.DESCENDANTORSELF:
                return (new TypedDescendantIterator(type)).includeSelf();
            case Axis.FOLLOWING:
                return new TypedFollowingIterator(type);
            case Axis.PRECEDING:
                return new TypedPrecedingIterator(type);
            case Axis.FOLLOWINGSIBLING:
                return new TypedFollowingSiblingIterator(type);
            case Axis.PRECEDINGSIBLING:
                return new TypedPrecedingSiblingIterator(type);
            case Axis.NAMESPACE:
                return  new TypedNamespaceIterator(type);
            case Axis.ROOT:
                return new TypedRootIterator(type);
            default:
                BasisLibrary.runTimeError(BasisLibrary.TYPED_AXIS_SUPPORT_ERR,
                        Axis.getNames(axis));
        }
        return null;
    }

    /**
     * Do not think that this returns an iterator for the namespace axis.
     * It returns an iterator with nodes that belong in a certain namespace,
     * such as with <xsl:apply-templates select="blob/foo:*"/>
     * The 'axis' specifies the axis for the base iterator from which the
     * nodes are taken, while 'ns' specifies the namespace URI type.
     */
    public DTMAxisIterator getNamespaceAxisIterator(int axis, int ns)
    {
        if (ns == NO_TYPE) {
            return EMPTYITERATOR;
        }
        else {
            switch (axis) {
                case Axis.CHILD:
                    return new NamespaceChildrenIterator(ns);
                case Axis.ATTRIBUTE:
                    return new NamespaceAttributeIterator(ns);
                default:
                    return new NamespaceWildcardIterator(axis, ns);
            }
        }
    }

    /**
     * Iterator that handles node tests that test for a namespace, but have
     * a wild card for the local name of the node, i.e., node tests of the
     * form <axis>::<prefix>:*
     */
    public final class NamespaceWildcardIterator
        extends InternalAxisIteratorBase
    {
        /**
         * The namespace type index.
         */
        protected int m_nsType;

        /**
         * A nested typed axis iterator that retrieves nodes of the principal
         * node kind for that axis.
         */
        protected DTMAxisIterator m_baseIterator;

        /**
         * Constructor NamespaceWildcard
         *
         * @param axis The axis that this iterator will traverse
         * @param nsType The namespace type index
         */
        public NamespaceWildcardIterator(int axis, int nsType) {
            m_nsType = nsType;

            // Create a nested iterator that will select nodes of
            // the principal node kind for the selected axis.
            switch (axis) {
                case Axis.ATTRIBUTE: {
                    // For "attribute::p:*", the principal node kind is
                    // attribute
                    m_baseIterator = getAxisIterator(axis);
                    break;
                }
                case Axis.NAMESPACE: {
                    // This covers "namespace::p:*".  It is syntactically
                    // correct, though it doesn't make much sense.
                    m_baseIterator = getAxisIterator(axis);
                    break;
                }
                default: {
                    // In all other cases, the principal node kind is
                    // element
                    m_baseIterator = getTypedAxisIterator(axis,
                                                          DTM.ELEMENT_NODE);
                }
            }
        }

        /**
         * Set start to END should 'close' the iterator,
         * i.e. subsequent call to next() should return END.
         *
         * @param node Sets the root of the iteration.
         *
         * @return A DTMAxisIterator set to the start of the iteration.
         */
        public DTMAxisIterator setStartNode(int node) {
            if (_isRestartable) {
                _startNode = node;
                m_baseIterator.setStartNode(node);
                resetPosition();
            }
            return this;
        }

        /**
         * Get the next node in the iteration.
         *
         * @return The next node handle in the iteration, or END.
         */
        public int next() {
            int node;

            while ((node = m_baseIterator.next()) != END) {
                // Return only nodes that are in the selected namespace
                if (getNSType(node) == m_nsType) {
                    return returnNode(node);
                }
            }

            return END;
        }

        /**
         * Returns a deep copy of this iterator.  The cloned iterator is not
         * reset.
         *
         * @return a deep copy of this iterator.
         */
        public DTMAxisIterator cloneIterator() {
            try {
                DTMAxisIterator nestedClone = m_baseIterator.cloneIterator();
                NamespaceWildcardIterator clone =
                    (NamespaceWildcardIterator) super.clone();

                clone.m_baseIterator = nestedClone;
                clone.m_nsType = m_nsType;
                clone._isRestartable = false;

                return clone;
            } catch (CloneNotSupportedException e) {
                BasisLibrary.runTimeError(BasisLibrary.ITERATOR_CLONE_ERR,
                                          e.toString());
                return null;
            }
        }

        /**
         * True if this iterator has a reversed axis.
         *
         * @return true if this iterator is a reversed axis.
         */
        public boolean isReverse() {
            return m_baseIterator.isReverse();
        }

        public void setMark() {
            m_baseIterator.setMark();
        }

        public void gotoMark() {
            m_baseIterator.gotoMark();
        }
    }

    /**
     * Iterator that returns children within a given namespace for a
     * given node. The functionality chould be achieved by putting a
     * filter on top of a basic child iterator, but a specialised
     * iterator is used for efficiency (both speed and size of translet).
     */
    public final class NamespaceChildrenIterator
        extends InternalAxisIteratorBase
    {

        /** The extended type ID being requested. */
        private final int _nsType;

        /**
         * Constructor NamespaceChildrenIterator
         *
         *
         * @param type The extended type ID being requested.
         */
        public NamespaceChildrenIterator(final int type) {
            _nsType = type;
        }

        /**
         * Set start to END should 'close' the iterator,
         * i.e. subsequent call to next() should return END.
         *
         * @param node Sets the root of the iteration.
         *
         * @return A DTMAxisIterator set to the start of the iteration.
         */
        public DTMAxisIterator setStartNode(int node) {
            //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
            if (node == DTMDefaultBase.ROOTNODE) {
                node = getDocument();
            }

            if (_isRestartable) {
                _startNode = node;
                _currentNode = (node == DTM.NULL) ? DTM.NULL : NOTPROCESSED;

                return resetPosition();
            }

            return this;
        }

        /**
         * Get the next node in the iteration.
         *
         * @return The next node handle in the iteration, or END.
         */
        public int next() {
            if (_currentNode != DTM.NULL) {
                for (int node = (NOTPROCESSED == _currentNode)
                                     ? _firstch(makeNodeIdentity(_startNode))
                                     : _nextsib(_currentNode);
                     node != END;
                     node = _nextsib(node)) {
                    int nodeHandle = makeNodeHandle(node);

                    if (getNSType(nodeHandle) == _nsType) {
                        _currentNode = node;

                        return returnNode(nodeHandle);
                    }
                }
            }

            return END;
        }
    }  // end of NamespaceChildrenIterator

    /**
     * Iterator that returns attributes within a given namespace for a node.
     */
    public final class NamespaceAttributeIterator
            extends InternalAxisIteratorBase
    {

        /** The extended type ID being requested. */
        private final int _nsType;

        /**
         * Constructor NamespaceAttributeIterator
         *
         *
         * @param nsType The extended type ID being requested.
         */
        public NamespaceAttributeIterator(int nsType) {
            super();

            _nsType = nsType;
        }

        /**
         * Set start to END should 'close' the iterator,
         * i.e. subsequent call to next() should return END.
         *
         * @param node Sets the root of the iteration.
         *
         * @return A DTMAxisIterator set to the start of the iteration.
         */
        public DTMAxisIterator setStartNode(int node) {
            //%HZ%: Added reference to DTMDefaultBase.ROOTNODE back in, temporarily
            if (node == DTMDefaultBase.ROOTNODE) {
                node = getDocument();
            }

            if (_isRestartable) {
                int nsType = _nsType;

                _startNode = node;

                for (node = getFirstAttribute(node);
                     node != END;
                     node = getNextAttribute(node)) {
                    if (getNSType(node) == nsType) {
                        break;
                    }
                }

                _currentNode = node;
                return resetPosition();
            }

            return this;
        }

        /**
         * Get the next node in the iteration.
         *
         * @return The next node handle in the iteration, or END.
         */
        public int next() {
            int node = _currentNode;
            int nsType = _nsType;
            int nextNode;

            if (node == END) {
                return END;
            }

            for (nextNode = getNextAttribute(node);
                 nextNode != END;
                 nextNode = getNextAttribute(nextNode)) {
                if (getNSType(nextNode) == nsType) {
                    break;
                }
            }

            _currentNode = nextNode;

            return returnNode(node);
        }
    }  // end of NamespaceAttributeIterator

    /**
     * Returns an iterator with all descendants of a node that are of
     * a given type.
     */
    public DTMAxisIterator getTypedDescendantIterator(int type)
    {
        return new TypedDescendantIterator(type);
    }

    /**
     * Returns the nth descendant of a node
     */
    public DTMAxisIterator getNthDescendant(int type, int n, boolean includeself)
    {
        return new NthDescendantIterator(n);
    }

    /**
     * Copy the string value of a node directly to an output handler
     */
    public void characters(final int node, SerializationHandler handler)
        throws TransletException
    {
        if (node != DTM.NULL) {
            try {
                dispatchCharactersEvents(node, handler, false);
            } catch (SAXException e) {
                throw new TransletException(e);
            }
        }
    }

    /**
     * Copy a node-set to an output handler
     */
    public void copy(DTMAxisIterator nodes, SerializationHandler handler)
        throws TransletException
    {
        int node;
        while ((node = nodes.next()) != DTM.NULL) {
            copy(node, handler);
        }
    }

    /**
     * Copy the whole tree to an output handler
     */
    public void copy(SerializationHandler handler) throws TransletException
    {
        copy(getDocument(), handler);
    }

    /**
     * Performs a deep copy (ref. XSLs copy-of())
     *
     * TODO: Copy namespace declarations. Can't be done until we
     *       add namespace nodes and keep track of NS prefixes
     * TODO: Copy comment nodes
     */
    public void copy(final int node, SerializationHandler handler)
        throws TransletException
    {
        copy(node, handler, false );
    }

 private final void copy(final int node, SerializationHandler handler, boolean isChild)
        throws TransletException
    {
     int nodeID = makeNodeIdentity(node);
        int eType = _exptype2(nodeID);
        int type = _exptype2Type(eType);

        try {
            switch(type)
            {
                case DTM.ROOT_NODE:
                case DTM.DOCUMENT_NODE:
                    for(int c = _firstch2(nodeID); c != DTM.NULL; c = _nextsib2(c)) {
                        copy(makeNodeHandle(c), handler, true);
                    }
                    break;
                case DTM.PROCESSING_INSTRUCTION_NODE:
                    copyPI(node, handler);
                    break;
                case DTM.COMMENT_NODE:
                    handler.comment(getStringValueX(node));
                    break;
                case DTM.TEXT_NODE:
                    boolean oldEscapeSetting = false;
                    boolean escapeBit = false;

                    if (_dontEscape != null) {
                        escapeBit = _dontEscape.getBit(getNodeIdent(node));
                        if (escapeBit) {
                            oldEscapeSetting = handler.setEscaping(false);
                        }
                    }

                    copyTextNode(nodeID, handler);

                    if (escapeBit) {
                        handler.setEscaping(oldEscapeSetting);
                    }
                    break;
                case DTM.ATTRIBUTE_NODE:
                    copyAttribute(nodeID, eType, handler);
                    break;
                case DTM.NAMESPACE_NODE:
                    handler.namespaceAfterStartElement(getNodeNameX(node), getNodeValue(node));
                    break;
                default:
                    if (type == DTM.ELEMENT_NODE)
                    {
                        // Start element definition
                        final String name = copyElement(nodeID, eType, handler);
                        //if(isChild) => not to copy any namespaces  from parents
                        // else copy all namespaces in scope
                        copyNS(nodeID, handler,!isChild);
                        copyAttributes(nodeID, handler);
                        // Copy element children
                        for (int c = _firstch2(nodeID); c != DTM.NULL; c = _nextsib2(c)) {
                            copy(makeNodeHandle(c), handler, true);
                        }

                        // Close element definition
                        handler.endElement(name);
                    }
                    // Shallow copy of attribute to output handler
                    else {
                        final String uri = getNamespaceName(node);
                        if (uri.length() != 0) {
                            final String prefix = getPrefix(node);
                            handler.namespaceAfterStartElement(prefix, uri);
                        }
                        handler.addAttribute(getNodeName(node), getNodeValue(node));
                    }
                    break;
            }
        }
        catch (Exception e) {
            throw new TransletException(e);
        }

    }
    /**
     * Copies a processing instruction node to an output handler
     */
    private void copyPI(final int node, SerializationHandler handler)
        throws TransletException
    {
        final String target = getNodeName(node);
        final String value = getStringValueX(node);

        try {
            handler.processingInstruction(target, value);
        } catch (Exception e) {
            throw new TransletException(e);
        }
    }

    /**
     * Performs a shallow copy (ref. XSLs copy())
     */
    public String shallowCopy(final int node, SerializationHandler handler)
        throws TransletException
    {
        int nodeID = makeNodeIdentity(node);
        int exptype = _exptype2(nodeID);
        int type = _exptype2Type(exptype);

        try {
            switch(type)
            {
                case DTM.ELEMENT_NODE:
                    final String name = copyElement(nodeID, exptype, handler);
                    copyNS(nodeID, handler, true);
                    return name;
                case DTM.ROOT_NODE:
                case DTM.DOCUMENT_NODE:
                    return EMPTYSTRING;
                case DTM.TEXT_NODE:
                    copyTextNode(nodeID, handler);
                    return null;
                case DTM.PROCESSING_INSTRUCTION_NODE:
                    copyPI(node, handler);
                    return null;
                case DTM.COMMENT_NODE:
                    handler.comment(getStringValueX(node));
                    return null;
                case DTM.NAMESPACE_NODE:
                    handler.namespaceAfterStartElement(getNodeNameX(node), getNodeValue(node));
                    return null;
                case DTM.ATTRIBUTE_NODE:
                    copyAttribute(nodeID, exptype, handler);
                    return null;
                default:
                    final String uri1 = getNamespaceName(node);
                    if (uri1.length() != 0) {
                        final String prefix = getPrefix(node);
                        handler.namespaceAfterStartElement(prefix, uri1);
                    }
                    handler.addAttribute(getNodeName(node), getNodeValue(node));
                    return null;
            }
        } catch (Exception e) {
            throw new TransletException(e);
        }
    }

    /**
     * Returns a node' defined language for a node (if any)
     */
    public String getLanguage(int node)
    {
        int parent = node;
        while (DTM.NULL != parent) {
            if (DTM.ELEMENT_NODE == getNodeType(parent)) {
                int langAttr = getAttributeNode(parent, "http://www.w3.org/XML/1998/namespace", "lang");

                if (DTM.NULL != langAttr) {
                    return getNodeValue(langAttr);
                }
            }

            parent = getParent(parent);
        }
        return(null);
    }

    /**
     * Returns an instance of the DOMBuilder inner class
     * This class will consume the input document through a SAX2
     * interface and populate the tree.
     */
    public DOMBuilder getBuilder()
    {
        return this;
    }

    /**
     * Return a SerializationHandler for output handling.
     * This method is used by Result Tree Fragments.
     */
    public SerializationHandler getOutputDomBuilder()
    {
        return new ToXMLSAXHandler(this, "UTF-8");
    }

    /**
     * Return a instance of a DOM class to be used as an RTF
     */
    public DOM getResultTreeFrag(int initSize, int rtfType)
    {
        return getResultTreeFrag(initSize, rtfType, true);
    }

    /**
     * Return a instance of a DOM class to be used as an RTF
     *
     * @param initSize The initial size of the DOM.
     * @param rtfType The type of the RTF
     * @param addToManager true if the RTF should be registered with the DTMManager.
     * @return The DOM object which represents the RTF.
     */
    public DOM getResultTreeFrag(int initSize, int rtfType, boolean addToManager)
    {
        if (rtfType == DOM.SIMPLE_RTF) {
            if (addToManager) {
                int dtmPos = _dtmManager.getFirstFreeDTMID();
                SimpleResultTreeImpl rtf = new SimpleResultTreeImpl(_dtmManager,
                                           dtmPos << DTMManager.IDENT_DTM_NODE_BITS);
                _dtmManager.addDTM(rtf, dtmPos, 0);
                return rtf;
            }
            else {
                return new SimpleResultTreeImpl(_dtmManager, 0);
            }
        }
        else if (rtfType == DOM.ADAPTIVE_RTF) {
            if (addToManager) {
                int dtmPos = _dtmManager.getFirstFreeDTMID();
                AdaptiveResultTreeImpl rtf = new AdaptiveResultTreeImpl(_dtmManager,
                                       dtmPos << DTMManager.IDENT_DTM_NODE_BITS,
                                       m_wsfilter, initSize, m_buildIdIndex);
                _dtmManager.addDTM(rtf, dtmPos, 0);
                return rtf;

            }
            else {
                return new AdaptiveResultTreeImpl(_dtmManager, 0,
                                       m_wsfilter, initSize, m_buildIdIndex);
            }
        }
        else {
            return (DOM) _dtmManager.getDTM(null, true, m_wsfilter,
                                            true, false, false,
                                            initSize, m_buildIdIndex);
        }
    }

    /**
     * Return the attributes map.
     * @return the attributes map.
     */
    public Map<String, Integer> getElementsWithIDs() {
        return m_idAttributes;
    }

    /**
     * The getUnparsedEntityURI function returns the URI of the unparsed
     * entity with the specified name in the same document as the context
     * node (see [3.3 Unparsed Entities]). It returns the empty string if
     * there is no such entity.
     */
    public String getUnparsedEntityURI(String name)
    {
        // Special handling for DOM input
        if (_document != null) {
            String uri = "";
            DocumentType doctype = _document.getDoctype();
            if (doctype != null) {
                NamedNodeMap entities = doctype.getEntities();

                if (entities == null) {
                    return uri;
                }

                Entity entity = (Entity) entities.getNamedItem(name);

                if (entity == null) {
                    return uri;
                }

                String notationName = entity.getNotationName();
                if (notationName != null) {
                    uri = entity.getSystemId();
                    if (uri == null) {
                        uri = entity.getPublicId();
                    }
                }
            }
            return uri;
        }
        else {
            return super.getUnparsedEntityURI(name);
        }
    }

    public void release() {
        _dtmManager.release(this, true);
    }
}


One Big Secret.

Arile Fisher.
Let's describe her in Sim traits, shall we?
Grumpy, oh no doubt especially when she doesn't get her Ice-coffee from McDonald's.
Loner, while her two older siblings are party goers, she sits in her room, staring at her computer screen, which is almost always on Tumblr.
Clumsy, you know sponge bob's cousin? Yeah, thats her.
Loser, the only thing she can win is "how fast can you eat your dinner?"
which of course isn't a bad thing, to some people.
And finally, bookworm. You can always find her nose in a book, or on her phone reading a book.
Now, let's to the point.
Arile has a secret, a BIG secret.
I'm talking mumbo-jumbo drink size's at the State Fair.
Behind the bookshelf in her room, is a secret passage-way.
Oh yeah, the whole Nancy Drew package right here.
Now in that secret room is
a big machine.
Not what you were expecting right?
Well guess what?
That machine is a time machine.


Q:

How to print text from one client to all other clients using Sockets

Everytime I connect a client to the server, it adds a new socket to my ArrayList. When I send a message in my client to the server, it shows up in the server output window, but I am trying to push the message that it sent from one client thread into all of the client windows by somehow iterating through the ArrayList of Sockets.
How would I go about sending the input from one of the clients to all of the clients?
I have the program broken up into 3 classes, Client, Server, and Service.

A:

So basically just make the arraylist an arraylist of the Service class and add that object to the arraylist instead of the socket.
Then in the server class you iterate over the services and use the printstream (not the socket) to send data to all the logged in clients.


Amala Paul Hot Pics

Amala Paul Hot Pics

Amala was born on 26 october 1991 in Ernakulam, Kerala to Christian Malayali folks, Paul Varghese and Annice Paul. once completing her and 2 examinations at Nirmala Higher school, Aluva she took a sabbatical to start a career in films, however has since joined St. Teresa’s college in Kochi, to pursue a BA degree in English and is currently in her third year. Her father had been strictly against Amala following a acting career, but was forced to simply accept her call with her older brother, Abijith, strongly backing her ambition. Amala had modified her on-screen name to Anakha, on director Samy’s insistence, who cited that another role player, Amala had already created her name popular. However, once the failure of Sindhu Samaveli, she reverted to her birth name since she felt that the replacement had brought her dangerous luck.

Amala Paul, after finishing her and 2 education, took a year out before progressing to pursue engineering for any education. At the time, her modelling portfolio was noticed by noted malayalam director Lal Jose UN agency offered her a supporting role in his remake, Neelathamara (2009). Despite low-budget successful, the film did not attract any longer offers, as she had anticipated. She pursued roles in Tamil films and went on to sign the low-budget comedy film Vikadakavi that was delayed and ultimately became her sixth release, whereas conjointly language on to play the lead role in another tiny budget film Veerasekaran (2010). The film, that became her maiden Tamil release, was panned by critics and went completely malayalam, whereas Amala’s role was being labelled as ‘minimal’, release later cited that she regretted doing the film unnoticed of her scenes were edited out.


By Thomas Adams, at Paykin Krieg and Adams, LLP, and a former managing director at Ambac and FGIC.

Readers may have noticed Janet Tavakoli’s recent article at Huffington Post on Goldman Sachs and AIG. While much of it covers territory that Yves and I already wrote about previously, Ms. Tavakoli stops short of telling the whole story. While she is very knowledgeable of this market, perhaps she is unaware of the full extent of the wrongdoings Goldman committed by getting themselves paid on the AIG bailout. The Federal Reserve and the Treasury aided and abetted Goldman Sachs in committing financial and ethical crimes at an astounding level.

She notes, accurately, that Goldman used AIG to hedge its bet on CDO’s, either for itself with the Abacus deals, or for its clients, with the Davis Square deal. Had AIG failed, Goldman would have been on the hook for the losses: to execute the CDO with synthetic mortgage bonds, Goldman went “long” the CDS and then turned around and went “short” with AIG, effectively taking the risk of the mortgage bonds defaulting and then transferring it to AIG.

But Ms. Tavakoli fails to note that the collapse of the CDO bonds and the collapse of AIG were a deliberate strategy by Goldman. To realize on their bet against the housing market, Goldman needed the CDO bonds to collapse in value, which would cause AIG to be downgraded and lead to AIG posting collateral and Goldman getting paid for their bet. I am confident that Goldman Sachs did not reveal to AIG that they were betting on the housing market collapse.

To help hasten the housing market collapse, Goldman ran a huge mortgage lending and issuance program with low quality loans virtually designed to fail, including dozens of deals backed by completely toxic non-prime second lien loans (these loans help pump up the housing bubble and let borrower’s suck the equity out of their homes). In soliciting AIG’s insurance for the CDOs, Goldman was not disclosing that the transaction was highly speculative. Goldman was offering AAA, or even super AAA bonds. Goldman designed and sold these bonds and purchased a rating from the rating agencies that represented the risk to be AAA. In fact, the bonds did not provide real protection, despite their AAA rating, and when the housing market turned down, the AAA CDO bonds collapsed in value exactly as they were designed to do.

Goldman never wanted these CDOs to succeed – their bet depended on them failing. This is why they used AIG as their insurer – AIG posted collateral, which enabled Goldman to still get paid even when AIG inevitably got downgraded for taking on such toxic deals.

Goldman needed AIG’s insurance to complete this bet and get them off risk for the CDO they created. Hedge fund manager John Paulson and others used the same strategy. Goldman’s bet was risky because they depended on AIG being solvent in order to get paid. Other parties who made similar betters, but relied on the other bond insurers to pay them off ended up getting hurt when the bond insurers got downgraded and the trade did not pay off, as well.

Months before AIG received its bailout, Goldman was well aware of the risk that insurers would pay less the full amount of the CDOs – Goldman was advising FGIC in its restructuring efforts and FGIC negotiated a CDO commutation for ten cents on the dollar. Goldman mitigated the risk of downgrade by dealing exclusively with AIG, which was required to post collateral in the event of a downgrade.

Goldman also misled shareholders and investors by proclaiming that they were not exposed to toxic CDOs because they were hedged with AIG, even as the bond insurers (AIG’s direct competitors in the CDO market), were getting downgraded.

It is bad enough that the creators and sellers of the CDOs, such as Goldman, BlackRock and TCW, have not been held to account for selling worthless bonds while representing them to be of AAA quality. Most of these influential power brokers have succeeded in blaming the victim (investors and insurers who believed their lies about the quality of the bonds) for the financial crisis to distract from their own questionable activities.

Goldman goes quite a few steps further into despicable territory with their other actions and the body count from Goldman’s actions is so enormous that it crosses over into criminal territory, morally and legally, by getting taxpayer money for their predation.

Goldman made a huge bet that the housing market would collapse. They profited, on paper, from the tremendous pain suffered by homeowners, investors and taxpayers across the country, they helped make it worse. Their bet only succeeded because they were able to force the government into bailing out AIG.

In addition, the Federal Reserve and the Treasury, by helping Goldman Sachs to profit from homeowner and investor losses, conceal their misrepresentations to shareholders, destroy insurers by stuffing them with toxic bonds that they marketed as AAA, and escape from the consequences of making a risky bet, committed a grave injustice and, very likely, financial crimes. Since the bailout, they have actively concealed their actions and mislead the public. Goldman, the Fed and the Treasury should be investigated for fraud, securities law violations and misappropriation of taxpayer funds. Based on what I have laid out here, I am confident that they will find ample evidence.

Update 12/23, 1:00 PM: Yves here. Some readers in comments are dismissing this post as mere Goldman bashing, when its behavior was far more pernicious. I was remiss in not adding a critical bit of Tom’s argument, which he provided in a separate post:

While the subprime deals and CDOs were obviously going bad, an argument was made by many people at the time that the aggressive mark downs by AIG acelerated the death spiral for the market. It is pretty clear, here and elsewhere, that Goldman was the one that initiated the mark downs of collateral value. it would be interesting to explore this all the way through. Though not discussed in this article, Goldman shorted subprime through the Abacus deals, and perhaps elsewhere. this gave them an incentive to force mark downs. the intermediation deals described in the article, combined with AIG’s collateral posting, gave them another incentive to be agressive with mark downs. they were acting like they wanted to grab the money before anyone else could get their hands on it. this would have raised some issues in an AIGFP bankruptcy. (note – Hank Greenberg suggested that this was going on in his october 2008 testimony but there was a chorus of attacks on him for being a crook and unreliable, thanks to his problems with Spitzer.)

So here we have the pattern:


Q:

A question about linearly lindelöf space

Suppose $X$ be a linearly lindelöf space, and $\mathcal{P}$ a family closed subsets of $X$, satisfying $\cap \mathcal{P}=\emptyset$. Let $\tau$ be the smallest cardinal number such that there is a subfamily $\gamma$ of $\mathcal{P}$ satisfying the conditions: $\cap \gamma=\emptyset$ and $|\gamma|=\tau$. Assume that $\tau$ is uncountable. How could I show the cofinality of $\tau$ is $\omega$? Thanks ahead:)

A:

Let $\gamma=\{F_\xi:\xi<\tau\}$. For $\eta<\tau$ let $H_\eta=\bigcap_{\xi\le\eta}F_\xi$, and let $U_\eta=X\setminus H_\eta$. Then $\mathscr{U}=\{U_\xi:\xi<\tau\}$ is a non-decreasing open cover of $X$, so it has a countable subcover $\{U_{\xi_n}:n\in\omega\}$, where $\xi_n<\xi_{n+1}$ for each $n\in\omega$. The sequence $\langle\xi_n:n\in\omega\rangle$ must be cofinal in $\tau$.


Factor and cluster analyses with the Rosenzweig Picture Frustration Study.
The Rosenzweig Picture Frustration (P-F) Study data of 104 psychiatric hospital patients, 56 males and 48 females, were subjected first to a Factor Analysis and then to a Cluster Analysis. In the former, five factors were extracted which showed some similarity to other Factor Analyses reported in the literature. The Cluster Analysis turned up one very large group (42% of the sample) characterized by depression and P-F profiles with elevated i and very low E scores. Seven other clusters are described in the article. The factors and clusters found are clinically meaningful and can provide assistance in interpreting P-F profiles. Recommendations for a revised P-F manual to enhance the usefulness of the test are made.


Induction of Mx-related protein in cat peripheral blood mononuclear cells after administration of recombinant human interferon hybrid.
A 78 kDa protein was induced in cat peripheral blood mononuclear cells after in vivo administration of recombinant human interferon-alpha hybrid (rHuIFN-alpha B/D). This protein was antigenically related to the IFN-induced human (78 kDa) and mouse Mx proteins. Quantitative immunoblot analysis indicated that the induction of the cat Mx protein was dose-dependent. There was a dissociation in time between plasma levels of IFN which were transient, and levels of cat Mx protein which remained elevated at least five days after dosing. Our results provide evidence that a human IFN-alpha hybrid may be active in cats. They also indicate that the Mx protein is a sensitive, quantitative, and stable marker to follow IFN activity in vivo in cats.


Abhishek Sudhesh Bhat had moved to San Bernandino in California State University around 2 years ago.

A 25-year-old student from Mysuru was shot dead in California on Thursday by an unidentified gunman. Abhishek Sudhesh Bhat who was studying Computer Science at the California State University in San Bernardino was killed inside a hotel where he was working part-time, family members said.

A resident of Kuvempunagar in Mysuru, Abhishek had moved to California for his post-graduation course around two years ago. He had four months left to complete his Master's Degree.

According to reports, Abhishek's family was stunned when they received a call at around 11:30 pm on Thursday informing about the incident.

The caller told them that Abhishek was shot dead inside the hotel but did not reveal any other information, family members told the newspaper Star of Mysore.

In a state a state of shock, the family say they are facing problems in bringing back Abhiskek's body because of a severe storm in San Bernandino, located about 100 km east from Los Angeles.

Thursday being a US holiday on account of Thanksgiving also impaired access to information and resources.

"We have contacted US Consulate and the Indian High Commission for more details and as of now there is no clear information about the incident and why Abhishek was shot dead. Modalities are being worked out for the parents and Abhishek's younger brother to travel to San Bernardino," a family member told the newspaper.


CONTRIBUTORS

The president’s friend should never run the Fed

The financial markets are delighted that Larry Summers has withdrawn from consideration as chair of the Federal Reserve. “Call it the Yellen rally,” Neil Irwin writes in Wonkblog, referring of course to Janet Yellen, the current vice chair of the Fed, whom President Obama “awkwardly” will probably choose, now that Summers has pulled out. Maybe the traders and their clients are pleased because there’s a real difference in monetary policy between Yellen and Summers, and she would keep interest rates lower for longer. Or maybe there’s not much disagreement between them, as Matt Yglesias argues, and the markets are up because Yellen will have a smoother ride to confirmation than Summers would have, avoiding a bout of uncertainty.

I haven’t been rallying for Yellen, but I’m glad Summers is out because I don’t see why closeness to Obama should determine who gets to be Fed chair. The most important reason Summers was the front-runner seems to have been his longtime working relationship with the president. But chair of the Fed is a lasting position in an institution outside the White House. Being Fed chair is more like being Supreme Court justice than being a White House adviser: You’re supposed to be independent. President Obama didn’t choose Sonia Sotomayor because they were pals, and he shouldn’t insist on personal affinity in making this choice either.

When the White House was pushing for Summers, they framed the president’s preference in terms of trust. Their “bond” was “forged in the crucible of the financial crisis,” Obama strategist David Axelrod said. An anonymous White House official told the New York Times, “It’s like the attachment you feel for your heart surgeon after he performs a quadruple bypass.” Another one turned to a mixed military metaphor. “We were sort of in a foxhole together, and he was a stand-up dude” (very dangerous in a foxhole!).

The “dude” word choice was unfortunate given the retro claims from the right that Yellen’s ascension threatened to impose an era of “The Female Dollar,” whatever that means. The objection from the New York Sun, bearer of that headline, and the Wall Street Journal editorial page was that Yellen was about to get the nod because she’s a woman, a triumph for the gender police. Gender didn’t come up when the names of any male candidates were floated, as Ezra Klein pointed out. It’s only accused of driving a president’s choice when he goes in the female direction.

More interesting than the knee-jerk sexism is the question whether it’s still easier to be the dude in the Obama foxhole if you’re actually a dude. There’s a list of administration names that serve as retorts: Valerie Jarrett, Susan Rice, Samantha Power, to pick three. But on the apparent short list for the Fed, along with Summers and Yellen, was former Treasury Secretary Timothy Geithner, who was told the job was his if he wanted it. (He doesn’t.) Geithner, of course, is another trusted insider, and of course another guy.

Story continues below advertisement.

My point isn’t that Obama should pick Yellen because he owes it to women. But I do think that for plenty of other male leaders, putting a high premium on personal comfort level and bonding tends to favor the male candidate over the equally qualified woman. If you think gender is irrelevant to the question of who would be the best next Fed chair, then Obama should look beyond his inner circle.

And he should do that anyway. The next Fed chair will outlast the president in office. Their working relationship isn’t what matters most. And he or she shouldn’t decide when to raise the interest rate out of loyalty to the White House.

The long-term nature of the Fed job, and critical distance from the president, are features of serving on the Supreme Court, too. It’s true that presidents have at times factored in personal ties. Obama had known Elena Kagan since the early 1990s when he picked her to be a justice in 2010, and she’d served as his solicitor general. But before Kagan, you have to go back to Lyndon Johnson’s (ill-fated) choice of Abe Fortas for another court pick rooted in friendship. (I’m not counting George W. Bush’s bumbling effort to nominate his White House counsel, Harriet Miers.) Presidents generally know to look past their noses for Supreme Court nominees. I’m sure this administration, after five grueling years, is reluctant to trust anyone who hasn’t been in its trenches with the keys to the Fed. But Obama should.


8.3 (sxml fold)

8.3.1 Overview

(sxml fold) defines a number of variants of the fold
algorithm for use in transforming SXML trees. Additionally it defines
the layout operator, fold-layout, which might be described as a
context-passing variant of SSAX's pre-post-order.

8.3.2 Usage

— Function: foldt fup fhere tree

The standard multithreaded tree fold.

fup is of type [a] -> a. fhere is of type object -> a.

— Function: foldts fdown fup fhere seed tree

The single-threaded tree fold originally defined in SSAX. See (sxml ssax), for more information.

— Function: foldts* fdown fup fhere seed tree

A variant of foldts that allows pre-order tree
rewrites. Originally defined in Andy Wingo's 2007 paper,
Applications of fold to XML transformation.

— Function: fold-values proc list . seeds

A variant of fold that allows multi-valued
seeds. Note that the order of the arguments differs from that of
fold.

— Function: foldts*-values fdown fup fhere tree . seeds

A variant of foldts* that allows multi-valued
seeds. Originally defined in Andy Wingo's 2007 paper, Applications
of fold to XML transformation.


Outback Power FX80. It is rated at 80 amps output. They also make an MX60,
60 amps out. they will take up to 140 volt open circuit string of like
sized panels and step it down to 12/24/48/60 volt standard dc voltages.
they are also programmable for odd output voltage as well.
These are the most expensive, I think I paid a little over 500 for my fx80
but it makes up for the difference in panel quantity plus a little.
There are a couple of other manufacturers that make lower power versions
of mppt controllers. Cant remember the power ratings, maybe 20-25 amps
that are $200 dollar range. THe lower priced units dont have as many
frills obviously.
bob
On Wed, 10 Sep 2008, Dave Baxter wrote:
> .
> .
> .
> Sorry probably way more than most on here wanted to know.
> .
> .
> .
>> Far from it! Who's MPPT box did you use?
>>> -----Original Message-----
>> From: bob evinger [mailto:wd9eka at evinger.com]
>> Sent: 09 September 2008 23:45
>> To: TAPR APRS Mailing List
>> Subject: Re: [aprssig] (Slightly OT) What is solar panel power output?
>>>> actually those numbers tell a lot. Solar panels are current
>> sources. That amp rating is short ciruit current, and the
>> current it will provide into a battery with proper sized wire
>> should be slightly less.
> This mail has been scanned by Palmer Cook Computer Services Limited. www.palmercook.co.uk
> _______________________________________________
> aprssig mailing list
>aprssig at lists.tapr.org>https://lists.tapr.org/cgi-bin/mailman/listinfo/aprssig>


Q:

ES6 and OO Desighn: It is good idea to use a class as "Interface"?

Usually on Php or in Java and in other single Inheritance Object Oriented Languages, when I am writing a software I use and Interface then and afterwards I implement the class that implements the business logic.
For example let us suppose we have a File Uploader that allow us to Upload into various ways in our case into an FtpServer or into an AmazonS3 Bucket.
Therefore I declare an interface FileUploaderInterface
interface FileUploaderInterface
{
   public function addFile(fromPath,toPath);
   public function removeFile(path);
}

And afterwards I Implement a seperate fileUploader for each seperate way we want to upload the data:
eg. for Ftp
class FtpFileUploader implements  FileUploaderInterface
{
   public function addFile(fromPath,toPath)
   {
     //Implement Method
   }
   public function removeFile(path)
   {
     //Implement Method
   }
}

eg. And for Amazon S3
class AmazonS3FileUploader implements FileUploaderInterface
{
   public function addFile(fromPath,toPath)
   {
     //Implement Method
   }
   public function removeFile(path)
   {
     //Implement Method
   }
}

With that I have the flexibility to have a Unique Handling for the file uploads regardless how the Upload Mechanism itself will work so if I want to upload using an X api I just have to implement the FileUploaderInterface Interface.
But on ES6 I find a it myself like a fish out of water int terms of software desighn so it it a good idea/practice to declare a class that has all the basic methods it want that plays the role of an interface
eg: A generic class for file Uploading in a file named 'FileUploader.js'
export default class FileManager {

  addFile(fromPath,toPath,callback){

  }

  deleteFile(path, callback){

  }
 }

And for each way for uploading I just develop a specific class:
eg. For Uploading via FTP
import FileManager from './FileUploader.js'

export default class FtpUploadManager extends FileManager {

  addFile(fromPath,toPath,callback){
    // Implement method
  }

  deleteFile(path, callback){
    // Implement method
  }
}

eg. For uploading via Amazon S3
import FileManager from './FileUploader.js'

export default class S3UploadManager extends FileManager {

  addFile(fromPath,toPath,callback){
    // Implement method
  }

  deleteFile(path, callback){
    // Implement method
  }
}

What are the pos and cons of using the following method?
The main difference I am asking of Are there any OO-principles that are practically applicable for Javascript? is if a specific way of using Js Classes is good or not and not a generic one.

A:

No, you should not do this. It makes no sense.
ECMAScript doesn't have a built-in notion of protocol (as it was originally called in Smalltalk) or interface, and a class with empty methods is not a good approximation of that.
The correct approximation of an interface in ECMAScript is documentation. You should document the protocols your objects need to conform to. After all, it is perfectly possible for an object to conform to the protocol even if it doesn't extend FileManager! That's what OO is all about: as long as an object conforms to a protocol, you can use it, without knowing its implementation (including its class / prototype).
Note: I am not familiar enough with ECMAScript documentation tools and how well they support protocol documentation. (In Ruby, with which I am more familiar, support is practically non-existent, which is a shame.)
A good example of the usage of interfaces in ECMAScript are the iteration interfaces defined in the specification: it first defines what an interface is (bold emphasis mine, italic emphasis from the spec):

An interface is a set of property keys whose associated values match a specific specification. Any object that provides all the properties as described by an interface's specification conforms to that interface. An interface is not represented by a distinct object. There may be many separately implemented objects that conform to any interface. An individual object may conform to multiple interfaces.

And then it describes the different interfaces, e.g. the Iterable interface:

Property: @@iterator
Value: A function that returns an Iterator object.
Requirements: The returned object must conform to the Iterator interface.

There are projects which add type annotations to ECMAScript, e.g. JSDoc supports type annotations for documentation purposes. (Note that there is a difference between type annotations and type checking! Annotations are useful for documentation and communication purposes, i.e. for humans even if not checked by a machine.)
There are also projects which can understand these JSDoc annotations and use them for actual static type checking, e.g. Google Closure Compiler.
Last but not least, there are some languages which are specifically designed to be familiar to ECMAScript developers, which have support for varying degrees of typing. For example, Facebook's Flow is a rather conservative superset of ECMAScript with support for type annotations and type checking, Microsoft's TypeScript is also a superset of ECMAScript that is a tad more ambitious than Flow (i.e. it supports Union and Intersection Types and Generics, and it doesn't just add typing, it also adds other features, for example, it supported classes and generators before ECMAScript did, and it already supports async/await). Basically, the difference between the two is: both are supersets of ECMAScript, but Flow is only a type system, whereas TypeScript adds a type system and additional features.
Moving further away from ECMAScript proper (starting with type annotations in doc comments, external type checkers, and ECMAScript superset languages), there are languages which are not intended to be supersets of ECMAScript and deliberately deviate from it, like Dart (which is still similar to ECMAScript and has optional typing) to languages like PureScript and Elm, which are much more in the strong, strict, statically typed functional language camp and closer to Haskell and ML than ECMAScript, yet still explicitly designed to be usable as ECMAScript replacements in the browser and server-side.


Related Tags:

INDIANA COUNTY (KDKA) – Indiana County District Attorney Patrick Dougherty says what he saw in social media clips from this weekend’s IUP student-organized off-campus St. Patrick’s Day party – called “IUPatty’s” – is shocking and disturbing.

He says even with a coordinated effort by borough and university police agencies, things got out of hand and now the big question is how to stop this from happening again.

“Obviously we didn’t want to go the route of State College,” Dougherty said. “They’ve been fighting this battle for a few years and they basically are at a point where there paying taverns and alcohol establishments to close.”

Today the university says it’s disappointed in the students that partook and frustrated that hundreds of young people who aren’t IUP students came to Indiana, causing so many problems.

“By no means is this the way our students behave and our expectations for students is much higher than this,” Michael Powers said.

Dougherty says police received 110 calls for service over the weekend. From assaults to underage drinking to a reported sexual assault that could be related to the IUPatty’s party.

Monday on campus, students were quick to defend the school’s reputation.

“Us being on local news, state news and getting the attention it has, I believe we should not be proud of that,” Scott Martz, a student, said.

Another student, Marcus Murray said, “I don’t think it’s like a big portrayal of our school in general. It’s just something that happened that day. This isn’t what happens here all the time.”

IUP Officials say they’re working with the Indiana Borough Police Department to determine which IUP students were arrested and charged. Those students will have to go through the university’s judicial system and could be suspended or even expelled.


Dying Light My Apocalypse Edition comes with a real house

A Collector’s Edition for Dying Light has been announced for the UK and it’s an expensive, one-off piece of merchandise. Well, and a house.

The collection is called My Apocalypse and is available for pre-order exclusively from GAME for £250,000.

It comes with four Steelbook copies of the game, professional parkour lessons, exclusive merchandise and a custom built, zombie apocalypse-proofed house.

The house is “fortified zombie apocalypse-proofed” and will be built to order by UK-based Tiger Log Cabins. The house comes fully equipped with all live-in amenities and also includes an upper deck, an escape hatch, arsenal storage for weaponry, and a living area with TV, Xbox One, and the latest sound system.

Subscribe to the VG247 newsletterGet all the best bits of VG247 delivered to your inbox every Friday!

Enable JavaScript to sign up to our newsletter

The survival-focused parkour lessons are from Ampisound, and it comes with custom merchandise and additional in-game perks.


This episode, Karan and Kushal talk about their experience with Star Wars Episode VII: The Force Awakens. Kushal talks a lot about the Star Wars canon and it's relationship between this new film and the canon. Be aware, THERE ARE **SPOILERS** IN THIS EPISODE.


13,000 refugees flee terrorist-controlled parts of Raqqa province

The committee chairperson of Raqqa civilian assembly said that about 13,000 refugees fled the territories of the northern Syrian province occupied by the ISIS terrorist group and came to the areas controlled by the Kurdish-led Syrian Democratic Forces.

"During the past two days, we have welcomed 13 thousand refugees from Meyselon and Celaa villages north of Raqqa and other villages near Raqqa," EbdulselamHemsorik told the Firat news agency on Saturday.

The official added that the majority of refugees were coming from the regions near Raqqa, but even three weeks ago the influx had been coming mostly from other parts of the crisis-torn state.

Syrian army as well as numerous armed groups, such as the SDF, have been fighting against ISIS, a terrorist organization that has occupied vast territories of the Middle Eastern country, including Raqqa.


If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Miami vs. Atlanta attn: Dolphans that live in Atlanta

Hello everyone, I live in Atlanta and my wife that is so great got me tickets to the game and I am on the 4th row seat 1 sect 120 or 5 yd line on the Falcons side..... I know, be careful right, lol. Anyway, i just wanted to see if anyone was going to be at the game and or have a tailgate before we start the season?
I am a little worried about our team in the secondary, Ryan and company have some talent and I cant take the thought that after waiting so long to see my boys in the Atl that the Falcons would have a team that could actually score with ease over the middle but it looks as such.

I live in TN and i am going to this game i cant wait. I am also worried about our secondary. But our defense has a chance against their offense where there d is pretty much bad all around but if our offense plays like they did against the Tampa they will have a chance.

Hello everyone, I live in Atlanta and my wife that is so great got me tickets to the game and I am on the 4th row seat 1 sect 120 or 5 yd line on the Falcons side..... I know, be careful right, lol. Anyway, i just wanted to see if anyone was going to be at the game and or have a tailgate before we start the season?
I am a little worried about our team in the secondary, Ryan and company have some talent and I cant take the thought that after waiting so long to see my boys in the Atl that the Falcons would have a team that could actually score with ease over the middle but it looks as such.

Hope to see you there!

There is a big group of Dolpfans meeting in Atlanta for the game. They are going to hit one of the Taco Mac's up there and "take it over". If you search through the threads I'm sure you can find more info including hotel. I'm sure that the guys/gals that are going up would be happy to have you join them.

"The object of life is not to be on the side of the majority, but to escape finding oneself in the ranks of the insane."

There is a big group of Dolpfans meeting in Atlanta for the game. They are going to hit one of the Taco Mac's up there and "take it over". If you search through the threads I'm sure you can find more info including hotel. I'm sure that the guys/gals that are going up would be happy to have you join them.

I think you are talking about the taco mac that is right next to the lindbergh marta station. If everyone is meeting up there you can count me in as well!!! Fin fans need to travel in packs!!!

The Falcons have issues so far covering screens! Happened all night to them vs. Chargers. They lost a lot of folks and young guys need to step up for them and early on. Ryan is great adn Turner is a sledgehammer at RB. Keep them in 3rd and long so they can't play ball control. With that D I love our chances with the WILDFIN making some special things happen. As an outside observer I like Ryan and admire his moxy for a young qb. Hopefull he gets a one game flu of the sophomore slump.

People don’t seem to have any problem having rookies in the secondary learning with live bullets in real games, but don’t want to see Henne go through the same process. I think both might cost us initially, but pay off in the long run and bigger picture. Go Miami. Hope you guys at the game have a great time!


[A French experience with methadone].
Methadone chlorhydrate has been administred to opiate addicts either for a short period with a decreasing dosage as a withdrawal cure, or for longterm treatments as a basis of a maintenance program. The analysis of precise clinical criteria regarding the socio-professional states, the family-life, the general health and the psychopathological diagnosis, allows an evaluation of the success of the cure and of its elective indications. The study of the personnality of the drug-addicts shows the importance of this factor in the potential success of a methadone cure. Urinary biological controls are regularly performed. This limitations and promises of this treatment discussed form a basis of a year's experience.


Quote of The Day With Seth and Amy

May 24, 2013 — Ron Chusid

“Really, Tea Party? Really? You’re surprised that you’re targeted by the IRS? You named yourself after a group of people who proudly and historically violated tax laws! Look, if I had a vanity license plate that said ‘Weed 420,’ I might expect to get pulled over now and then.” –Amy Poehler

“And really, politics aside, should we be surprised that the IRS takes special attention to the tax forms of the Tea Party? Judging from the terrible spelling on their protest signs, attention to detail isn’t really their thing.” –Seth Meyers