text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.25 at 10:03:57 PM CST
//

package ca.ieso.reports.schema.trapreauctionttcst;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence maxOccurs="unbounded">
 *         <element ref="{http://www.ieso.ca/schema}DocHeader"/>
 *         <element name="DocBody">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="AuctionStartDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
 *                   <element name="AuctionEndDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
 *                   <element name="AuctionRoundNumber" type="{http://www.w3.org/2001/XMLSchema}integer"/>
 *                   <element name="AuctionRoundStartTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *                   <element name="AuctionRoundEndTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *                   <element name="AuctionTimeStructure" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                   <element name="TransmissionRightsPercentage" type="{http://www.w3.org/2001/XMLSchema}integer"/>
 *                   <element name="InfoURL" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
 *                   <element name="ZonalTransferCapabilityTransmissionRightsSummary" maxOccurs="unbounded">
 *                     <complexType>
 *                       <complexContent>
 *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           <sequence>
 *                             <element name="InjectionZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                             <element name="TransferCapabilityTransmissionRightsSummary" maxOccurs="unbounded">
 *                               <complexType>
 *                                 <complexContent>
 *                                   <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                                     <sequence>
 *                                       <element name="PathName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                                       <element name="PathDescription" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                                       <element name="WithdrawalZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                                       <element name="TransferCapability" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
 *                                       <element name="TransmissionRights" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
 *                                       <element name="Notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *                                     </sequence>
 *                                   </restriction>
 *                                 </complexContent>
 *                               </complexType>
 *                             </element>
 *                           </sequence>
 *                         </restriction>
 *                       </complexContent>
 *                     </complexType>
 *                   </element>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="docID" type="{http://www.ieso.ca/schema}docID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "docHeaderAndDocBody"
})
@XmlRootElement(name = "Document")
public class Document {

    @XmlElements({
        @XmlElement(name = "DocHeader", required = true, type = DocHeader.class),
        @XmlElement(name = "DocBody", required = true, type = Document.DocBody.class)
    })
    protected List<Object> docHeaderAndDocBody;
    @XmlAttribute(name = "docID")
    protected String docID;

    /**
     * Gets the value of the docHeaderAndDocBody property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the docHeaderAndDocBody property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDocHeaderAndDocBody().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DocHeader }
     * {@link Document.DocBody }
     *
     *
     */
    public List<Object> getDocHeaderAndDocBody() {
        if (docHeaderAndDocBody == null) {
            docHeaderAndDocBody = new ArrayList<Object>();
        }
        return this.docHeaderAndDocBody;
    }

    /**
     * Gets the value of the docID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDocID() {
        return docID;
    }

    /**
     * Sets the value of the docID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDocID(String value) {
        this.docID = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="AuctionStartDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
     *         <element name="AuctionEndDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
     *         <element name="AuctionRoundNumber" type="{http://www.w3.org/2001/XMLSchema}integer"/>
     *         <element name="AuctionRoundStartTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
     *         <element name="AuctionRoundEndTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
     *         <element name="AuctionTimeStructure" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *         <element name="TransmissionRightsPercentage" type="{http://www.w3.org/2001/XMLSchema}integer"/>
     *         <element name="InfoURL" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
     *         <element name="ZonalTransferCapabilityTransmissionRightsSummary" maxOccurs="unbounded">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <sequence>
     *                   <element name="InjectionZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *                   <element name="TransferCapabilityTransmissionRightsSummary" maxOccurs="unbounded">
     *                     <complexType>
     *                       <complexContent>
     *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                           <sequence>
     *                             <element name="PathName" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *                             <element name="PathDescription" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *                             <element name="WithdrawalZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *                             <element name="TransferCapability" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
     *                             <element name="TransmissionRights" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
     *                             <element name="Notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
     *                           </sequence>
     *                         </restriction>
     *                       </complexContent>
     *                     </complexType>
     *                   </element>
     *                 </sequence>
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "auctionStartDate",
        "auctionEndDate",
        "auctionRoundNumber",
        "auctionRoundStartTime",
        "auctionRoundEndTime",
        "auctionTimeStructure",
        "transmissionRightsPercentage",
        "infoURL",
        "zonalTransferCapabilityTransmissionRightsSummary"
    })
    public static class DocBody {

        @XmlElement(name = "AuctionStartDate", required = true)
        @XmlSchemaType(name = "date")
        protected XMLGregorianCalendar auctionStartDate;
        @XmlElement(name = "AuctionEndDate", required = true)
        @XmlSchemaType(name = "date")
        protected XMLGregorianCalendar auctionEndDate;
        @XmlElement(name = "AuctionRoundNumber", required = true)
        protected BigInteger auctionRoundNumber;
        @XmlElement(name = "AuctionRoundStartTime", required = true)
        @XmlSchemaType(name = "dateTime")
        protected XMLGregorianCalendar auctionRoundStartTime;
        @XmlElement(name = "AuctionRoundEndTime", required = true)
        @XmlSchemaType(name = "dateTime")
        protected XMLGregorianCalendar auctionRoundEndTime;
        @XmlElement(name = "AuctionTimeStructure", required = true)
        protected String auctionTimeStructure;
        @XmlElement(name = "TransmissionRightsPercentage", required = true)
        protected BigInteger transmissionRightsPercentage;
        @XmlElement(name = "InfoURL", required = true)
        @XmlSchemaType(name = "anyURI")
        protected String infoURL;
        @XmlElement(name = "ZonalTransferCapabilityTransmissionRightsSummary", required = true)
        protected List<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary> zonalTransferCapabilityTransmissionRightsSummary;

        /**
         * Gets the value of the auctionStartDate property.
         *
         * @return
         *     possible object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public XMLGregorianCalendar getAuctionStartDate() {
            return auctionStartDate;
        }

        /**
         * Sets the value of the auctionStartDate property.
         *
         * @param value
         *     allowed object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public void setAuctionStartDate(XMLGregorianCalendar value) {
            this.auctionStartDate = value;
        }

        /**
         * Gets the value of the auctionEndDate property.
         *
         * @return
         *     possible object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public XMLGregorianCalendar getAuctionEndDate() {
            return auctionEndDate;
        }

        /**
         * Sets the value of the auctionEndDate property.
         *
         * @param value
         *     allowed object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public void setAuctionEndDate(XMLGregorianCalendar value) {
            this.auctionEndDate = value;
        }

        /**
         * Gets the value of the auctionRoundNumber property.
         *
         * @return
         *     possible object is
         *     {@link BigInteger }
         *
         */
        public BigInteger getAuctionRoundNumber() {
            return auctionRoundNumber;
        }

        /**
         * Sets the value of the auctionRoundNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link BigInteger }
         *
         */
        public void setAuctionRoundNumber(BigInteger value) {
            this.auctionRoundNumber = value;
        }

        /**
         * Gets the value of the auctionRoundStartTime property.
         *
         * @return
         *     possible object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public XMLGregorianCalendar getAuctionRoundStartTime() {
            return auctionRoundStartTime;
        }

        /**
         * Sets the value of the auctionRoundStartTime property.
         *
         * @param value
         *     allowed object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public void setAuctionRoundStartTime(XMLGregorianCalendar value) {
            this.auctionRoundStartTime = value;
        }

        /**
         * Gets the value of the auctionRoundEndTime property.
         *
         * @return
         *     possible object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public XMLGregorianCalendar getAuctionRoundEndTime() {
            return auctionRoundEndTime;
        }

        /**
         * Sets the value of the auctionRoundEndTime property.
         *
         * @param value
         *     allowed object is
         *     {@link XMLGregorianCalendar }
         *
         */
        public void setAuctionRoundEndTime(XMLGregorianCalendar value) {
            this.auctionRoundEndTime = value;
        }

        /**
         * Gets the value of the auctionTimeStructure property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getAuctionTimeStructure() {
            return auctionTimeStructure;
        }

        /**
         * Sets the value of the auctionTimeStructure property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setAuctionTimeStructure(String value) {
            this.auctionTimeStructure = value;
        }

        /**
         * Gets the value of the transmissionRightsPercentage property.
         *
         * @return
         *     possible object is
         *     {@link BigInteger }
         *
         */
        public BigInteger getTransmissionRightsPercentage() {
            return transmissionRightsPercentage;
        }

        /**
         * Sets the value of the transmissionRightsPercentage property.
         *
         * @param value
         *     allowed object is
         *     {@link BigInteger }
         *
         */
        public void setTransmissionRightsPercentage(BigInteger value) {
            this.transmissionRightsPercentage = value;
        }

        /**
         * Gets the value of the infoURL property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getInfoURL() {
            return infoURL;
        }

        /**
         * Sets the value of the infoURL property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setInfoURL(String value) {
            this.infoURL = value;
        }

        /**
         * Gets the value of the zonalTransferCapabilityTransmissionRightsSummary property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the zonalTransferCapabilityTransmissionRightsSummary property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getZonalTransferCapabilityTransmissionRightsSummary().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary }
         *
         *
         */
        public List<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary> getZonalTransferCapabilityTransmissionRightsSummary() {
            if (zonalTransferCapabilityTransmissionRightsSummary == null) {
                zonalTransferCapabilityTransmissionRightsSummary = new ArrayList<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary>();
            }
            return this.zonalTransferCapabilityTransmissionRightsSummary;
        }

        /**
         *
Java class for anonymous complex type.
         *
         *
The following schema fragment specifies the expected content contained within this class.
         *
         *

         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <sequence>
         *         <element name="InjectionZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
         *         <element name="TransferCapabilityTransmissionRightsSummary" maxOccurs="unbounded">
         *           <complexType>
         *             <complexContent>
         *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *                 <sequence>
         *                   <element name="PathName" type="{http://www.w3.org/2001/XMLSchema}string"/>
         *                   <element name="PathDescription" type="{http://www.w3.org/2001/XMLSchema}string"/>
         *                   <element name="WithdrawalZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
         *                   <element name="TransferCapability" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
         *                   <element name="TransmissionRights" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
         *                   <element name="Notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
         *                 </sequence>
         *               </restriction>
         *             </complexContent>
         *           </complexType>
         *         </element>
         *       </sequence>
         *     </restriction>
         *   </complexContent>
         * </complexType>
         *

         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {
            "injectionZone",
            "transferCapabilityTransmissionRightsSummary"
        })
        public static class ZonalTransferCapabilityTransmissionRightsSummary {

            @XmlElement(name = "InjectionZone", required = true)
            protected String injectionZone;
            @XmlElement(name = "TransferCapabilityTransmissionRightsSummary", required = true)
            protected List<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary.TransferCapabilityTransmissionRightsSummary> transferCapabilityTransmissionRightsSummary;

            /**
             * Gets the value of the injectionZone property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getInjectionZone() {
                return injectionZone;
            }

            /**
             * Sets the value of the injectionZone property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setInjectionZone(String value) {
                this.injectionZone = value;
            }

            /**
             * Gets the value of the transferCapabilityTransmissionRightsSummary property.
             *
             *

             * This accessor method returns a reference to the live list,
             * not a snapshot. Therefore any modification you make to the
             * returned list will be present inside the JAXB object.
             * This is why there is not a set method for the transferCapabilityTransmissionRightsSummary property.
             *
             *

             * For example, to add a new item, do as follows:
             *

             *    getTransferCapabilityTransmissionRightsSummary().add(newItem);
             *

             *
             *
             *

             * Objects of the following type(s) are allowed in the list
             * {@link Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary.TransferCapabilityTransmissionRightsSummary }
             *
             *
             */
            public List<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary.TransferCapabilityTransmissionRightsSummary> getTransferCapabilityTransmissionRightsSummary() {
                if (transferCapabilityTransmissionRightsSummary == null) {
                    transferCapabilityTransmissionRightsSummary = new ArrayList<Document.DocBody.ZonalTransferCapabilityTransmissionRightsSummary.TransferCapabilityTransmissionRightsSummary>();
                }
                return this.transferCapabilityTransmissionRightsSummary;
            }

            /**
             *
Java class for anonymous complex type.
             *
             *
The following schema fragment specifies the expected content contained within this class.
             *
             *

             * <complexType>
             *   <complexContent>
             *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
             *       <sequence>
             *         <element name="PathName" type="{http://www.w3.org/2001/XMLSchema}string"/>
             *         <element name="PathDescription" type="{http://www.w3.org/2001/XMLSchema}string"/>
             *         <element name="WithdrawalZone" type="{http://www.w3.org/2001/XMLSchema}string"/>
             *         <element name="TransferCapability" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
             *         <element name="TransmissionRights" type="{http://www.ieso.ca/schema}MW_decimal5.1"/>
             *         <element name="Notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
             *       </sequence>
             *     </restriction>
             *   </complexContent>
             * </complexType>
             *

             *
             *
             */
            @XmlAccessorType(XmlAccessType.FIELD)
            @XmlType(name = "", propOrder = {
                "pathName",
                "pathDescription",
                "withdrawalZone",
                "transferCapability",
                "transmissionRights",
                "notes"
            })
            public static class TransferCapabilityTransmissionRightsSummary {

                @XmlElement(name = "PathName", required = true)
                protected String pathName;
                @XmlElement(name = "PathDescription", required = true)
                protected String pathDescription;
                @XmlElement(name = "WithdrawalZone", required = true)
                protected String withdrawalZone;
                @XmlElement(name = "TransferCapability", required = true)
                protected BigDecimal transferCapability;
                @XmlElement(name = "TransmissionRights", required = true)
                protected BigDecimal transmissionRights;
                @XmlElement(name = "Notes")
                protected String notes;

                /**
                 * Gets the value of the pathName property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getPathName() {
                    return pathName;
                }

                /**
                 * Sets the value of the pathName property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setPathName(String value) {
                    this.pathName = value;
                }

                /**
                 * Gets the value of the pathDescription property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getPathDescription() {
                    return pathDescription;
                }

                /**
                 * Sets the value of the pathDescription property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setPathDescription(String value) {
                    this.pathDescription = value;
                }

                /**
                 * Gets the value of the withdrawalZone property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getWithdrawalZone() {
                    return withdrawalZone;
                }

                /**
                 * Sets the value of the withdrawalZone property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setWithdrawalZone(String value) {
                    this.withdrawalZone = value;
                }

                /**
                 * Gets the value of the transferCapability property.
                 *
                 * @return
                 *     possible object is
                 *     {@link BigDecimal }
                 *
                 */
                public BigDecimal getTransferCapability() {
                    return transferCapability;
                }

                /**
                 * Sets the value of the transferCapability property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link BigDecimal }
                 *
                 */
                public void setTransferCapability(BigDecimal value) {
                    this.transferCapability = value;
                }

                /**
                 * Gets the value of the transmissionRights property.
                 *
                 * @return
                 *     possible object is
                 *     {@link BigDecimal }
                 *
                 */
                public BigDecimal getTransmissionRights() {
                    return transmissionRights;
                }

                /**
                 * Sets the value of the transmissionRights property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link BigDecimal }
                 *
                 */
                public void setTransmissionRights(BigDecimal value) {
                    this.transmissionRights = value;
                }

                /**
                 * Gets the value of the notes property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getNotes() {
                    return notes;
                }

                /**
                 * Sets the value of the notes property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setNotes(String value) {
                    this.notes = value;
                }

            }

        }

    }

}


text:
"""
Levels include (increasing severity): ``DEBUG``, ``INFO``, ``NOTICE``, ``WARNING``, ``ERROR``, ``CRITICAL``, ``DISABLED``
"""

class LogLevel(object):
    """A log level. Users should *not* create new instances.

    Levels are opaque; they may be compared to each other, but nothing else.
    """

    __slots__ = ['__name', '__value']
    _name2levels = {}

    def __init__(self, name, value):
        self.__name = name
        self.__value = value
        self._name2levels[name] = self

    def __str__(self):
        return self.__name

    def __repr__(self):
        return "<LogLevel %s>"%self.__name

    def __lt__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value < other.__value

    def __le__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value <= other.__value

    def __gt__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value > other.__value

    def __ge__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value >= other.__value

    def __eq__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value == other.__value

    def __ne__(self, other):
        if not isinstance(other, LogLevel):
            return NotImplemented
        else:
            return self.__value != other.__value

    def __hash__(self):
        return hash(self.__value)

def name2level(name):
    """return a `LogLevel` from a case-insensitve string"""
    return LogLevel._name2levels[name.upper()]

def get_level_names():
    return LogLevel._name2levels.keys()

DEBUG = LogLevel('DEBUG', 1)
INFO = LogLevel('INFO', 2)
NOTICE = LogLevel('NOTICE', 3)
WARNING = LogLevel('WARNING', 4)
ERROR = LogLevel('ERROR', 5)
CRITICAL = LogLevel('CRITICAL', 6)
DISABLED = LogLevel('DISABLED', 7)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection.Emit;

/// <summary>
/// Pushr8 [v-yishi]
/// </summary>
public class StackBehaviourPushr8
{
    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the value of Pushr8 is 24");

        try
        {
            int expected = 24;
            int actual = (int)StackBehaviour.Pushr8;

            if (expected != actual)
            {
                TestLibrary.TestFramework.LogError("001.1", "Pushr8's value is not 24");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] expected = " + expected + ", actual = " + actual);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    public static int Main()
    {
        StackBehaviourPushr8 test = new StackBehaviourPushr8();

        TestLibrary.TestFramework.BeginTestCase("StackBehaviourPushr8");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 24;
        }
    }
}


text:
namespace engine {

//=============================================================================
// FORWARD DECLARATIONS
//=============================================================================
class IGameObject;

class IGameEngine;
using GameEngineRef = std::shared_ptr<IGameEngine>;
using GameEngineWeakRef = std::weak_ptr<IGameEngine>;

//=============================================================================
// CLASS TimeManager
//=============================================================================
class TimeManager
	: public GameManager<TimeManager>
	, public ITimeManager
{
public:
	using time_point = GameClock::time_point;

public:
	static constexpr IdType TypeId = "TimeManager";
	static constexpr IdType Interfaces[] = {
		ITimeManager::TypeId
	};

public: // IComponent
	virtual void onAttached(const GameEngineRef &iGameEngine) override {}
	virtual void onDetached(const GameEngineRef &iGameEngine) override {}

public: // IPlayerManager
	virtual time_point currentTime() noexcept override;
	virtual time_point lastFrameTime() noexcept override;
	virtual void setGameRate(float iRate) override;

	virtual void startFrame() override;
	virtual void startSession() override;

	TimeManager();

private:
	time_point _lastFrameTime;
	time_point _currentTime;
	GameClock _sessionTimer;
};
} // namespace engine


text:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:elevation="2dp"
    app:cardCornerRadius="2dp">

    <RelativeLayout
        android:id="@+id/test"
        android:layout_width="310dp"
        android:layout_height="380dp">
            <TextView
                android:id="@+id/text"
                android:textSize="30sp"
                android:layout_centerInParent="true"
                android:text="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
      <!--  <ImageView
            android:id="@+id/iv_logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:src="@mipmap/ask_lcs_btn_default" />

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@id/iv_logo"
            android:ellipsize="end"
            android:maxLines="2"
            android:minHeight="46dp"
            android:text="200亿进行开矿处理200亿进行开矿处理200亿进行开矿处" />

        <ImageView
            android:id="@+id/v_div"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/tv_title"
            android:layout_marginTop="10dp"
            android:background="@android:color/holo_blue_dark" />

        <TextView

            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/v_div"
            android:ellipsize="end"
            android:maxLines="3"
            android:minHeight="70dp"
            android:padding="10dp"
            android:text="答:200亿进行开矿处理200亿进行开200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理200亿进行开矿处理"
            android:visibility="visible" />

        <TextView
            android:id="@+id/tv_lock"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/v_div"
            android:drawablePadding="24dp"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="3"
            android:padding="10dp"
            android:text="问答私密部分需要解锁以后查看"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/tv_look_more"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tv_content"
            android:layout_centerHorizontal="true"
            android:paddingRight="10dp"
            android:text="我被锁住了" />

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@id/tv_content"
            android:paddingRight="10dp"
            android:text="两分钟前" />

        <View
            android:id="@+id/bottom_line"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/tv_time"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:background="@android:color/holo_orange_light"></View>

        <ImageView
            android:id="@+id/img_avatar"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_below="@id/bottom_line"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:src="@mipmap/avatar_default" />

        <TextView

            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/img_avatar"
            android:layout_marginLeft="12dp"
            android:layout_toRightOf="@id/img_avatar"
            android:drawablePadding="4dp"
            android:text="张军" />

        <TextView
            android:id="@+id/tv_company"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/tv_name"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@id/tv_name"
            android:text="山西化什么什么公司" />

        <TextView
            android:id="@+id/tv_influence"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/tv_name"
            android:layout_below="@id/tv_name"
            android:layout_marginTop="6dp"
            android:text="影响力" />

        <TextView
            android:id="@+id/tv_liveness"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/tv_influence"
            android:layout_marginLeft="24dp"
            android:layout_toRightOf="@id/tv_influence"
            android:text="或阅历" />

        <TextView
            android:id="@+id/tv_ability"
            android:layout_width="190dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/tv_influence"
            android:layout_below="@id/tv_influence"
            android:layout_marginTop="6dp"
            android:text="按理说的就奥圣诞节啊送了接啊善良的爱上了就" />

        <LinearLayout
            android:id="@+id/linear_content"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@id/img_avatar"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="12dp"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_ask_num"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="回答数\n0" />

            <View
                android:layout_width="0.5dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:color/holo_blue_light"></View>

            <TextView
                android:id="@+id/tv_satisfied"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="满意度\n0%" />

            <View
                android:layout_width="0.5dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp"
                android:background="@android:color/holo_blue_light"></View>

            <TextView
                android:id="@+id/tv_average_response_time"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="平均响应时间\n--" />

        </LinearLayout>-->
    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
var searchData=
[
  ['unregisterallocator',['UnregisterAllocator',['../class_cpp_factory_1_1_object.html#ae7fd2e24446b4793d1ab4fdcccd27ec9',1,'CppFactory::Object::UnregisterAllocator()'],['../class_cpp_factory_1_1_object.html#ae6ca63d5828f51c3f74ec91339e3e7de',1,'CppFactory::Object::UnregisterAllocator()']]]
];


text:
package gw.plugin.ij.suite;

import gw.test.TestSpec;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IntelliJSuite extends TestSuite {
  public static final String GOSU_SUITE_INCLUDE_TYPES = "gs.suite.tests";

  public IntelliJSuite() throws Exception {
    super(new IntelliJTestScanner().findTests(createFilter(), findRootDir()));
  }

  @NotNull
  static private File findRootDir() throws Exception {
    URL location = IntelliJSuite.class.getProtectionDomain().getCodeSource().getLocation();
    return new File(location.toURI());
  }

  @NotNull
  public static Test suite() throws Exception {
    return new IntelliJSuite();
  }

  public static Set<String> createFilter() {
    Set<String> filter = new HashSet<>();

    String includedTests = System.getProperty(GOSU_SUITE_INCLUDE_TYPES);
    if (includedTests != null) {
      System.out.println("System property " + GOSU_SUITE_INCLUDE_TYPES + " used, so only running tests specified:");
      System.out.println(includedTests);
      String[] includedTestsArray = includedTests.replace(" ", "").split(",");
      filter.addAll(Arrays.asList(includedTestsArray));
    }
    return filter;
  }
}


text:
The sample can be run from the command line as follows:

Linux / macOS:
```bash
./gradlew clean bootRun
```

Windows:
```bash
gradlew.bat clean bootRun
```

The application will be served from `http://localhost:3010/`.

The sample includes a [Docker](https://www.docker.com) image ready to run with the following command:

```bash
# Linux / macOs
sh exec.sh
```

```bash
# Windows
./exec.ps1
```

The application will be served from `http://localhost:3010/`, just as if running with Gradle.


text:
<?xml version="1.0" encoding="UTF-8"?>
<tileset version="1.5" tiledversion="1.7.2" name="Paths" tilewidth="16" tileheight="16" tilecount="36" columns="4">
 <image source="paths.png" width="64" height="144"/>
 <tile id="0">
  <properties>
   <property name="PathType" value="NE"/>
  </properties>
 </tile>
 <tile id="1">
  <properties>
   <property name="PathType" value="SE"/>
  </properties>
 </tile>
 <tile id="2">
  <properties>
   <property name="PathType" value="WS"/>
  </properties>
 </tile>
 <tile id="3">
  <properties>
   <property name="PathType" value="WN"/>
  </properties>
 </tile>
 <tile id="4">
  <properties>
   <property name="PathType" value="Crossroad"/>
  </properties>
 </tile>
 <tile id="7">
  <properties>
   <property name="PathType" value="End"/>
  </properties>
 </tile>
</tileset>


text:
package spark.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.function.Predicate;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * GZIP utility class.
 *
 * @author Edward Raff
 * @author Per Wendel
 */
public class GzipUtils {

    private static final String ACCEPT_ENCODING = "Accept-Encoding";
    private static final String CONTENT_ENCODING = "Content-Encoding";

    private static final String GZIP = "gzip";

    private static final StringMatch STRING_MATCH = new StringMatch();

    // Hide constructor
    private GzipUtils() {

    }

    /**
     * Checks if the HTTP request/response accepts and wants GZIP and i that case wraps the response output stream in a
     * {@link java.util.zip.GZIPOutputStream}.
     *
     * @param httpRequest        the HTTP servlet request.
     * @param httpResponse       the HTTP servlet response.
     * @param requireWantsHeader if wants header is required
     * @return if accepted and wanted a {@link java.util.zip.GZIPOutputStream} otherwise the unchanged response
     * output stream.
     * @throws IOException in case of IO error.
     */
    public static OutputStream checkAndWrap(HttpServletRequest httpRequest,
                                            HttpServletResponse httpResponse,
                                            boolean requireWantsHeader) throws
                                                                        IOException {
        OutputStream responseStream = httpResponse.getOutputStream();

        // GZIP Support handled here. First we must ensure that we want to use gzip, and that the client supports gzip
        boolean acceptsGzip = Collections.list(httpRequest.getHeaders(ACCEPT_ENCODING)).stream().anyMatch(STRING_MATCH);
        boolean wantGzip = httpResponse.getHeaders(CONTENT_ENCODING).contains(GZIP);

        if (acceptsGzip) {
            if (!requireWantsHeader || wantGzip) {
                responseStream = new GZIPOutputStream(responseStream, true);
                addContentEncodingHeaderIfMissing(httpResponse, wantGzip);
            }
        }

        return responseStream;
    }

    private static void addContentEncodingHeaderIfMissing(HttpServletResponse response, boolean wantsGzip) {
        if (!wantsGzip) {
            response.setHeader(CONTENT_ENCODING, GZIP);
        }
    }

    /**
     * Used instead of lambdas due to risk for java.lang.IncompatibleClassChangeError.
     */
    private static class StringMatch implements Predicate<String> {
        @Override
        public boolean test(String s) {
            if (s == null) {
                return false;
            }

            return s.contains(GZIP);
        }
    }

}


text:
module Mongoid #:nodoc:
  module Finders #:nodoc:
    # Find +Documents+ given the conditions.
    #
    # Options:
    #
    # args: A +Hash+ with a conditions key and other options
    #
    # <tt>Person.all(:conditions => { :attribute => "value" })</tt>
    def all(*args)
      find(:all, *args)
    end

    # Returns a count of matching records in the database based on the
    # provided arguments.
    #
    # <tt>Person.count(:first, :conditions => { :attribute => "value" })</tt>
    def count(*args)
      Criteria.translate(self, *args).count
    end

    # Helper to initialize a new +Criteria+ object for this class.
    #
    # Example:
    #
    # <tt>Person.criteria</tt>
    def criteria
      Criteria.new(self)
    end

    # Find a +Document+ in several different ways.
    #
    # If a +String+ is provided, it will be assumed that it is a
    # representation of a Mongo::ObjectID and will attempt to find a single
    # +Document+ based on that id. If a +Symbol+ and +Hash+ is provided then
    # it will attempt to find either a single +Document+ or multiples based
    # on the conditions provided and the first parameter.
    #
    # <tt>Person.find(:first, :conditions => { :attribute => "value" })</tt>
    #
    # <tt>Person.find(:all, :conditions => { :attribute => "value" })</tt>
    #
    # <tt>Person.find(Mongo::ObjectID.new.to_s)</tt>
    def find(*args)
      raise Errors::InvalidOptions.new("Calling Document#find with nil is invalid") if args[0].nil?
      type = args.delete_at(0) if args[0].is_a?(Symbol)
      criteria = Criteria.translate(self, *args)
      case type
      when :first then return criteria.one
      when :last then return criteria.last
      else
        return criteria
      end
    end

    # Find the first +Document+ given the conditions, or creates a new document
    # with the conditions that were supplied
    #
    # Options:
    #
    # args: A +Hash+ of attributes
    #
    # <tt>Person.find_or_create_by(:attribute => "value")</tt>
    def find_or_create_by(attrs = {})
      find_or(:create, attrs)
    end

    # Find the first +Document+ given the conditions, or instantiates a new document
    # with the conditions that were supplied
    #
    # Options:
    #
    # args: A +Hash+ of attributes
    #
    # <tt>Person.find_or_initialize_by(:attribute => "value")</tt>
    def find_or_initialize_by(attrs = {})
      find_or(:new, attrs)
    end

    # Find the first +Document+ given the conditions.
    #
    # Options:
    #
    # args: A +Hash+ with a conditions key and other options
    #
    # <tt>Person.first(:conditions => { :attribute => "value" })</tt>
    def first(*args)
      find(:first, *args)
    end

    # Find the last +Document+ given the conditions.
    #
    # Options:
    #
    # args: A +Hash+ with a conditions key and other options
    #
    # <tt>Person.last(:conditions => { :attribute => "value" })</tt>
    def last(*args)
      find(:last, *args)
    end

    # Convenience method for returning the max value of a field.
    #
    # Options:
    #
    # field: The field to use when calculating the max.
    #
    # Example:
    #
    # <tt>Person.max(:age)</tt>
    #
    # Returns: <tt>Float</tt> max value.
    def max(field)
      criteria.max(field)
    end

    # Convenience method for returning the min value of a field.
    #
    # Options:
    #
    # field: The field to use when calculating the min.
    #
    # Example:
    #
    # <tt>Person.min(:age)</tt>
    #
    # Returns: <tt>Float</tt> min value.
    def min(field)
      criteria.min(field)
    end

    # Find all documents in paginated fashion given the supplied arguments.
    # If no parameters are passed just default to offset 0 and limit 20.
    #
    # Options:
    #
    # params: A +Hash+ of params to pass to the Criteria API.
    #
    # Example:
    #
    # <tt>Person.paginate(:conditions => { :field => "Test" }, :page => 1,
    # :per_page => 20)</tt>
    #
    # Returns paginated array of docs.
    def paginate(params = {})
      Criteria.translate(self, params).paginate
    end

    # Entry point for creating a new criteria from a Document. This will
    # instantiate a new +Criteria+ object with the supplied select criterion
    # already added to it.
    #
    # Options:
    #
    # args: A list of field names to retrict the returned fields to.
    #
    # Example:
    #
    # <tt>Person.only(:field1, :field2, :field3)</tt>
    #
    # Returns: <tt>Criteria</tt>
    def only(*args)
      criteria.only(*args)
    end

    # Convenience method for returning the sum of a specified field for all
    # documents in the database.
    #
    # Options:
    #
    # field: The field to use when calculating the sum.
    #
    # Example:
    #
    # <tt>Person.sum(:age)</tt>
    #
    # Returns: <tt>Float</tt> of the sum.
    def sum(field)
      criteria.sum(field)
    end

    # Entry point for creating a new criteria from a Document. This will
    # instantiate a new +Criteria+ object with the supplied select criterion
    # already added to it.
    #
    # Options:
    #
    # selector: A where criteria to initialize.
    #
    # Example:
    #
    # <tt>Person.where(:field1 => "Value")</tt>
    #
    # Returns: <tt>Criteria</tt>
    def where(selector = nil)
      criteria.where(selector)
    end

    protected
    # Find the first object or create/initialize it.
    def find_or(method, attrs = {})
      first(:conditions => attrs) || send(method, attrs)
    end
  end
end


text:
<template name="listPrivateGroupsFlex">

{{_ "Private_Groups"}}

					<form class="search-form" role="form">

							<select class="c-select" id="sort">
								<option value="name" selected="{{sortSelected 'name'}}" class="primary-background-color">{{_ "Name"}}</option>
								<option value="ls" selected="{{sortSelected 'ls'}}" class="primary-background-color">{{_ "Last_seen"}}</option>
							</select>

							<input type="text" id="channel-search" class="search" placeholder="{{_ "Search_Private_Groups"}}" autocomplete="off" />

					</form>

{{_ "Private_Groups_list"}}

				{{#each groups}}

							{{name}}

								{{#if hidden}}

								{{/if}}

				{{/each}}

			{{#if hasMore}}

					{{> loading}}

			{{/if}}

</template>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CountryIterator</title>
<meta name="date" content="2015-03-20">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Index

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.sillysoft.lux.util

Class CountryIterator

java.lang.Object

com.sillysoft.lux.util.CountryIterator

Direct Known Subclasses:

ArmiesIterator, ClusterBorderIterator, ContinentIterator, NeighborIterator, OrderedNeighborIterator, PlayerIterator

public abstract class CountryIterator
extends java.lang.Object

An abstract class to serve as the superclass for a variety of different Country Iterators.

The real power of CountryIterators is that they can be chained together. For example

  CountryIterator foo = new PlayerIterator(0, new ContinentIterator(1, new NeighborIterator(5, countries)));

Will return an enumeration of all the countries owned by player 0 that are in continent 1 and border couuntry 5

The only difference among the subclasses provided is the constructor, which all take different parameters.

All subclasses must:

1. Have a constructor that sets the class variable countries to an array of Countries (usually it's all the countries in the game). The constructor must call getNextReady() as its last action.

2. implement the

      abstract protected boolean isAHit( int code );

    method, with code being the array index of the country to check to see if it should be returned.

Constructor Summary

Constructors

Constructor and Description

CountryIterator()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
hasNext()

Whether or not the Iterator contains more Countrys

Country
next()

Removes the next Country from the Iterator and returns it.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CountryIterator

public CountryIterator()

Method Detail

hasNext

public boolean hasNext()

Whether or not the Iterator contains more Countrys

next

public Country next()

Removes the next Country from the Iterator and returns it.

Skip navigation links

Overview

Package

Class

Tree

Index

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import DOMHelper from "../dom-helper";
import {
  equalHTML,
  isCheckedInputHTML
} from "../htmlbars-test-helpers";

var xhtmlNamespace = "http://www.w3.org/1999/xhtml",
    xlinkNamespace = "http://www.w3.org/1999/xlink",
    svgNamespace   = "http://www.w3.org/2000/svg";

var foreignNamespaces = ['foreignObject', 'desc', 'title'];

var dom, i, foreignNamespace;

// getAttributes may return null or "" for nonexistent attributes,
// depending on the browser.  So we find it out here and use it later.
var disabledAbsentValue = (function (){
  var div = document.createElement("input");
  return div.getAttribute("disabled");
})();

QUnit.module('DOM Helper', {
  beforeEach: function() {
    dom = new DOMHelper();
  },
  afterEach: function() {
    dom = null;
  }
});

test('#createElement', function(){
  var node = dom.createElement('div');
  equal(node.tagName, 'DIV');
  equalHTML(node, '

');
});

test('#childAtIndex', function() {
  var node = dom.createElement('div');

  var child1 = dom.createElement('p');
  var child2 = dom.createElement('img');

  strictEqual(dom.childAtIndex(node, 0), null);
  strictEqual(dom.childAtIndex(node, 1), null);
  strictEqual(dom.childAtIndex(node, 2), null);

  dom.appendChild(node, child1);
  strictEqual(dom.childAtIndex(node, 0).tagName, 'P');
  strictEqual(dom.childAtIndex(node, 1), null);
  strictEqual(dom.childAtIndex(node, 2), null);

  dom.insertBefore(node, child2, child1);
  strictEqual(dom.childAtIndex(node, 0).tagName, 'IMG');
  strictEqual(dom.childAtIndex(node, 1).tagName, 'P');
  strictEqual(dom.childAtIndex(node, 2), null);
});

test('#appendText adds text', function(){
  var node = dom.createElement('div');
  var text = dom.appendText(node, 'Howdy');
  ok(!!text, 'returns node');
  equalHTML(node, '
Howdy
');
});

test('#setAttribute', function(){
  var node = dom.createElement('div');
  dom.setAttribute(node, 'id', 'super-tag');
  equalHTML(node, '

');
  dom.setAttribute(node, 'id', null);
  equalHTML(node, '

');

  node = dom.createElement('input');
  ok(node.getAttribute('disabled') === disabledAbsentValue, 'precond: disabled is absent');
  dom.setAttribute(node, 'disabled', true);
  ok(node.getAttribute('disabled') !== disabledAbsentValue, 'disabled set to true is present');
  dom.setAttribute(node, 'disabled', false);
  ok(node.getAttribute('disabled') !== disabledAbsentValue, 'disabled set to false is present');
});

test('#setAttributeNS', function(){
  var node = dom.createElement('svg');
  dom.setAttributeNS(node, xlinkNamespace, 'xlink:href', 'super-fun');
  // chrome adds (xmlns:xlink="http://www.w3.org/1999/xlink") property while others don't
  // thus equalHTML is not useful
  var el = document.createElement('div');
  el.appendChild(node);
  // phantomjs omits the prefix, thus we can't find xlink:
  ok(el.innerHTML.indexOf('href="super-fun"') > 0);
  dom.setAttributeNS(node, xlinkNamespace, 'href', null);

  ok(el.innerHTML.indexOf('href="null"') > 0);

});

test('#getElementById', function() {
  var parentNode = dom.createElement('div'),
      childNode = dom.createElement('div');
  dom.setAttribute(parentNode, 'id', 'parent');
  dom.setAttribute(childNode, 'id', 'child');
  dom.appendChild(parentNode, childNode);
  dom.document.body.appendChild(parentNode);
  equalHTML(dom.getElementById('child'), '

');
  dom.document.body.removeChild(parentNode);
});

test('#setPropertyStrict', function(){
  var node = dom.createElement('div');
  dom.setPropertyStrict(node, 'id', 'super-tag');
  equalHTML(node, '

');

  node = dom.createElement('input');
  ok(node.getAttribute('disabled') === disabledAbsentValue, 'precond: disabled is absent');
  dom.setPropertyStrict(node, 'disabled', true);
  ok(node.getAttribute('disabled') !== disabledAbsentValue, 'disabled is present');
  dom.setPropertyStrict(node, 'disabled', false);
  ok(node.getAttribute('disabled') === disabledAbsentValue, 'disabled has been removed');
});

// IE dislikes undefined or null for value
test('#setPropertyStrict value', function(){
  var node = dom.createElement('input');
  dom.setPropertyStrict(node, 'value', undefined);
  equal(node.value, '', 'blank string is set for undefined');
  dom.setPropertyStrict(node, 'value', null);
  equal(node.value, '', 'blank string is set for undefined');
});

// IE dislikes undefined or null for type
test('#setPropertyStrict type', function(){
  var node = dom.createElement('input');
  dom.setPropertyStrict(node, 'type', undefined);
  equal(node.type, 'text', 'text default is set for undefined');
  dom.setPropertyStrict(node, 'type', null);
  equal(node.type, 'text', 'text default is set for undefined');
});

// setting undefined or null to src makes a network request
test('#setPropertyStrict src', function(){
  var node = dom.createElement('img');
  dom.setPropertyStrict(node, 'src', undefined);
  notEqual(node.src, undefined, 'blank string is set for undefined');
  dom.setPropertyStrict(node, 'src', null);
  notEqual(node.src, null, 'blank string is set for undefined');
});

test('#removeAttribute', function(){
  var node = dom.createElement('div');
  dom.setAttribute(node, 'id', 'super-tag');
  equalHTML(node, '

', 'precond - attribute exists');

  dom.removeAttribute(node, 'id');
  equalHTML(node, '

', 'attribute was removed');
});

test('#removeAttribute of SVG', function(){
  dom.setNamespace(svgNamespace);
  var node = dom.createElement('svg');
  dom.setAttribute(node, 'viewBox', '0 0 100 100');
  equalHTML(node, '<svg viewBox="0 0 100 100"></svg>', 'precond - attribute exists');

  dom.removeAttribute(node, 'viewBox');
  equalHTML(node, '<svg></svg>', 'attribute was removed');
});

test('#setProperty', function(){
  var node = dom.createElement('div');
  dom.setProperty(node, 'id', 'super-tag');
  equalHTML(node, '

');
  dom.setProperty(node, 'id', null);
  ok(node.getAttribute('id') !== 'super-tag', 'null property sets to the property');

  node = dom.createElement('div');
  dom.setProperty(node, 'data-fun', 'whoopie');
  equalHTML(node, '

');
  dom.setProperty(node, 'data-fun', null);
  equalHTML(node, '

', 'null attribute removes the attribute');

  node = dom.createElement('input');
  dom.setProperty(node, 'disabled', true);
  equal(node.disabled, true);
  dom.setProperty(node, 'disabled', false);
  equal(node.disabled, false);

  node = dom.createElement('div');
  dom.setProperty(node, 'style', 'color: red;');
  equalHTML(node, '

');
});

test('#setProperty removes attr with undefined', function(){
  var node = dom.createElement('div');
  dom.setProperty(node, 'data-fun', 'whoopie');
  equalHTML(node, '

');
  dom.setProperty(node, 'data-fun', undefined);
  equalHTML(node, '

', 'undefined attribute removes the attribute');
});

test('#addClasses', function(){
  var node = dom.createElement('div');
  dom.addClasses(node, ['super-fun']);
  equal(node.className, 'super-fun');
  dom.addClasses(node, ['super-fun']);
  equal(node.className, 'super-fun');
  dom.addClasses(node, ['super-blast']);
  equal(node.className, 'super-fun super-blast');
  dom.addClasses(node, ['bacon', 'ham']);
  equal(node.className, 'super-fun super-blast bacon ham');
});

test('#removeClasses', function(){
  var node = dom.createElement('div');
  node.setAttribute('class', 'this-class that-class');
  dom.removeClasses(node, ['this-class']);
  equal(node.className, 'that-class');
  dom.removeClasses(node, ['this-class']);
  equal(node.className, 'that-class');
  dom.removeClasses(node, ['that-class']);
  equal(node.className, '');
  node.setAttribute('class', 'woop moop jeep');
  dom.removeClasses(node, ['moop', 'jeep']);
  equal(node.className, 'woop');
});

test('#createElement of tr with contextual table element', function(){
  var tableElement = document.createElement('table'),
      node = dom.createElement('tr', tableElement);
  equal(node.tagName, 'TR');
  equalHTML(node, '

');
});

test('#createMorph has optional contextualElement', function(){
  var parent = document.createElement('div'),
      fragment = document.createDocumentFragment(),
      start = document.createTextNode(''),
      end = document.createTextNode(''),
      morph, thrown;

  try {
    morph = dom.createMorph(fragment, start, end, fragment);
  } catch(e) {
    thrown = true;
  }
  ok(thrown, 'Exception thrown when a fragment is provided for contextualElement');

  morph = dom.createMorph(fragment, start, end, parent);
  equal(morph.contextualElement, parent, "morph's contextualElement is parent");

  morph = dom.createMorph(parent, start, end);
  equal(morph.contextualElement, parent, "morph's contextualElement is parent");
});

test('#appendMorph', function(){
  var element = document.createElement('div');

  dom.appendText(element, 'a');
  var morph = dom.appendMorph(element);
  dom.appendText(element, 'c');

  morph.setContent('b');

  equal(element.innerHTML, 'abc');
});

test('#insertMorphBefore', function(){
  var element = document.createElement('div');

  dom.appendText(element, 'a');
  var c = dom.appendText(element, 'c');
  var morph = dom.insertMorphBefore(element, c);

  morph.setContent('b');

  equal(element.innerHTML, 'abc');
});

test('#parseHTML combinations', function(){
  var parsingCombinations = [
    // omitted start tags
    //
    ['table', '
Yo
', 'TR'],
    ['table', '

', 'TBODY'],
    ['table', '<col></col>', 'COL'],
    // elements with broken innerHTML in IE9 and down
    ['select', '<option></option>', 'OPTION'],
    ['colgroup', '<col></col>', 'COL'],
    ['tbody', '

', 'TR'],
    ['tfoot', '

', 'TR'],
    ['thead', '

', 'TR'],
    ['tr', '	', 'TD'],
    ['div', '', 'SCRIPT']
  ];

  var contextTag, content, expectedTagName, contextElement, nodes;
  for (var p=0;p<parsingCombinations.length;p++) {
    contextTag = parsingCombinations[p][0];
    content = parsingCombinations[p][1];
    expectedTagName = parsingCombinations[p][2];

    contextElement = document.createElement(contextTag);
    nodes = dom.parseHTML(content, contextElement).childNodes;
    equal(
      nodes[0].tagName, expectedTagName,
      '#parseHTML of '+content+' returns a '+expectedTagName+' inside a '+contextTag+' context' );
  }
});

test('#parseHTML of script then tr inside table context wraps the tr in a tbody', function(){
  var tableElement = document.createElement('table'),
      nodes = dom.parseHTML('
Yo
', tableElement).childNodes;
  // The HTML spec suggests the first item must be the child of
  // the omittable start tag. Here script is the first child, so no-go.
  equal(nodes.length, 2, 'Leading script tag corrupts');
  equal(nodes[0].tagName, 'SCRIPT');
  equal(nodes[1].tagName, 'TBODY');
});

test('#parseHTML of select allows the initial implicit option selection to remain', function(){
  var div = document.createElement('div');
  var select = dom.parseHTML('<select><option></option></select>', div).childNodes[0];

  ok(select.childNodes[0].selected, 'first element is selected');
});

test('#parseHTML of options removes an implicit selection', function(){
  var select = document.createElement('select');
  var options = dom.parseHTML(
    '<option value="1"></option><option value="2"></option>',
    select
  ).childNodes;

  ok(!options[0].selected, 'first element is not selected');
  ok(!options[1].selected, 'second element is not selected');
});

test('#parseHTML of options leaves an explicit first selection', function(){
  var select = document.createElement('select');
  var options = dom.parseHTML(
    '<option value="1" selected></option><option value="2"></option>',
    select
  ).childNodes;

  ok(options[0].selected, 'first element is selected');
  ok(!options[1].selected, 'second element is not selected');
});

test('#parseHTML of options leaves an explicit second selection', function(){
  var select = document.createElement('select');
  var options = dom.parseHTML(
    '<option value="1"></option><option value="2" selected="selected"></option>',
    select
  ).childNodes;

  ok(!options[0].selected, 'first element is not selected');
  ok(options[1].selected, 'second element is selected');
});

test('#parseHTML of script then tr inside tbody context', function(){
  var tbodyElement = document.createElement('tbody'),
      nodes = dom.parseHTML('
Yo
', tbodyElement).childNodes;
  equal(nodes.length, 2, 'Leading script tag corrupts');
  equal(nodes[0].tagName, 'SCRIPT');
  equal(nodes[1].tagName, 'TR');
});

test('#parseHTML with retains whitespace', function(){
  var div = document.createElement('div');
  var nodes = dom.parseHTML('leading
 , indeed.
', div).childNodes;
  equal(nodes[0].data, 'leading');
  equal(nodes[1].tagName, 'SCRIPT');
  equal(nodes[2].data, ' ');
  equal(nodes[3].tagName, 'SCRIPT');
  equal(nodes[4].tagName, 'DIV');
  equal(nodes[4].childNodes[0].tagName, 'SCRIPT');
  equal(nodes[4].childNodes[1].data, ' ');
  equal(nodes[4].childNodes[2].tagName, 'SCRIPT');
  equal(nodes[4].childNodes[3].data, ', indeed.');
});

test('#parseHTML with retains whitespace of top element', function(){
  var div = document.createElement('div');
  var nodes = dom.parseHTML('hello  yeah', div).childNodes;
  equal(nodes[0].tagName, 'SPAN');
  equalHTML(nodes, 'hello  yeah');
});

test('#parseHTML with retains whitespace after script', function(){
  var div = document.createElement('div');
  var nodes = dom.parseHTML('hello kwoop', div).childNodes;
  equal(nodes[0].tagName, 'SPAN');
  equal(nodes[1].tagName, 'SCRIPT');
  equal(nodes[2].tagName, 'SPAN');
  equalHTML(nodes, 'hello kwoop');
});

test('#parseHTML of number', function(){
  var div = document.createElement('div');
  var nodes = dom.parseHTML(5, div).childNodes;
  equal(nodes[0].data, '5');
  equalHTML(nodes, '5');
});

test('#protocolForURL', function() {
  var protocol = dom.protocolForURL("http://www.emberjs.com");
  equal(protocol, "http:");

  // Inherit protocol from document if unparseable
  protocol = dom.protocolForURL("   javascript:lulzhacked()");
  /*jshint scripturl:true*/
  equal(protocol, "javascript:");
});

test('#cloneNode shallow', function(){
  var divElement = document.createElement('div');

  divElement.appendChild( document.createElement('span') );

  var node = dom.cloneNode(divElement, false);

  equal(node.tagName, 'DIV');
  equalHTML(node, '

');
});

test('#cloneNode deep', function(){
  var divElement = document.createElement('div');

  divElement.appendChild( document.createElement('span') );

  var node = dom.cloneNode(divElement, true);

  equal(node.tagName, 'DIV');
  equalHTML(node, '

');
});

test('dom node has empty text after cloning and ensuringBlankTextNode', function(){
  var div = document.createElement('div');

  div.appendChild( document.createTextNode('') );

  var clonedDiv = dom.cloneNode(div, true);

  equal(clonedDiv.nodeType, 1);
  equalHTML(clonedDiv, '

');
  // IE's native cloneNode drops blank string text
  // nodes. Assert repairClonedNode brings back the blank
  // text node.
  dom.repairClonedNode(clonedDiv, [0]);
  equal(clonedDiv.childNodes.length, 1);
  equal(clonedDiv.childNodes[0].nodeType, 3);
});

test('dom node has empty start text after cloning and ensuringBlankTextNode', function(){
  var div = document.createElement('div');

  div.appendChild( document.createTextNode('') );
  div.appendChild( document.createElement('span') );

  var clonedDiv = dom.cloneNode(div, true);

  equal(clonedDiv.nodeType, 1);
  equalHTML(clonedDiv, '

');
  // IE's native cloneNode drops blank string text
  // nodes. Assert denormalizeText brings back the blank
  // text node.
  dom.repairClonedNode(clonedDiv, [0]);
  equal(clonedDiv.childNodes.length, 2);
  equal(clonedDiv.childNodes[0].nodeType, 3);
});

test('dom node checked after cloning and ensuringChecked', function(){
  var input = document.createElement('input');

  input.setAttribute('checked', 'checked');
  ok(input.checked, 'input is checked');

  var clone = dom.cloneNode(input, false);

  // IE's native cloneNode copies checked attributes but
  // not the checked property of the DOM node.
  dom.repairClonedNode(clone, [], true);

  isCheckedInputHTML(clone, '<input checked="checked">');
  ok(clone.checked, 'clone is checked');
});

if ('namespaceURI' in document.createElement('div')) {

QUnit.module('DOM Helper namespaces', {
  beforeEach: function() {
    dom = new DOMHelper();
  },
  afterEach: function() {
    dom = null;
  }
});

test('#createElement div is xhtml', function(){
  var node = dom.createElement('div');
  equal(node.namespaceURI, xhtmlNamespace);
});

test('#createElement of svg with svg namespace', function(){
  dom.setNamespace(svgNamespace);
  var node = dom.createElement('svg');
  equal(node.tagName, 'svg');
  equal(node.namespaceURI, svgNamespace);
});

test('#createElement of path with detected svg contextual element', function(){
  dom.setNamespace(svgNamespace);
  var node = dom.createElement('path');
  equal(node.tagName, 'path');
  equal(node.namespaceURI, svgNamespace);
});

test('#createElement of path with svg contextual element', function(){
  var node = dom.createElement('path', document.createElementNS(svgNamespace, 'svg'));
  equal(node.tagName, 'path');
  equal(node.namespaceURI, svgNamespace);
});

test('#createElement of svg with div namespace', function(){
  var node = dom.createElement('svg', document.createElement('div'));
  equal(node.tagName, 'svg');
  equal(node.namespaceURI, svgNamespace);
});

test('#getElementById with different root node', function() {
  var doc = document.implementation.createDocument(xhtmlNamespace, 'html', null),
      body = document.createElementNS(xhtmlNamespace, 'body'),
      parentNode = dom.createElement('div'),
      childNode = dom.createElement('div');

  doc.documentElement.appendChild(body);
  dom.setAttribute(parentNode, 'id', 'parent');
  dom.setAttribute(childNode, 'id', 'child');
  dom.appendChild(parentNode, childNode);
  dom.appendChild(body, parentNode);
  equalHTML(dom.getElementById('child', doc), '

');
});

test('#setProperty with namespaced attributes', function() {
  var node;

  dom.setNamespace(svgNamespace);
  node = dom.createElement('svg');
  dom.setProperty(node, 'viewBox', '0 0 0 0');
  equalHTML(node, '<svg viewBox="0 0 0 0"></svg>');

  dom.setProperty(node, 'xlink:title', 'super-blast', xlinkNamespace);
  // chrome adds (xmlns:xlink="http://www.w3.org/1999/xlink") property while others don't
  // thus equalHTML is not useful
  var el = document.createElement('div');
  el.appendChild(node);
  // phantom js omits the prefix so we can't look for xlink:
  ok(el.innerHTML.indexOf('title="super-blast"') > 0);

  dom.setProperty(node, 'xlink:title', null, xlinkNamespace);
  equal(node.getAttribute('xlink:title'), null, 'ns attr is removed');
});

test("#setProperty removes namespaced attr with undefined", function() {
  var node;

  node = dom.createElement('svg');
  dom.setProperty(node, 'xlink:title', 'Great Title', xlinkNamespace);
  dom.setProperty(node, 'xlink:title', undefined, xlinkNamespace);
  equal(node.getAttribute('xlink:title'), undefined, 'ns attr is removed');
});

for (i=0;i<foreignNamespaces.length;i++) {
  foreignNamespace = foreignNamespaces[i];

  test('#createElement of div with '+foreignNamespace+' contextual element', function(){
    var node = dom.createElement('div', document.createElementNS(svgNamespace, foreignNamespace));
    equal(node.tagName, 'DIV');
    equal(node.namespaceURI, xhtmlNamespace);
  }); // jshint ignore:line

  test('#parseHTML of div with '+foreignNamespace, function(){
    dom.setNamespace(xhtmlNamespace);
    var foreignObject = document.createElementNS(svgNamespace, foreignNamespace),
        nodes = dom.parseHTML('

', foreignObject).childNodes;
    equal(nodes[0].tagName, 'DIV');
    equal(nodes[0].namespaceURI, xhtmlNamespace);
  }); // jshint ignore:line
}

test('#parseHTML of path with svg contextual element', function(){
  dom.setNamespace(svgNamespace);
  var svgElement = document.createElementNS(svgNamespace, 'svg'),
      nodes = dom.parseHTML('<path></path>', svgElement).childNodes;
  equal(nodes[0].tagName, 'path');
  equal(nodes[0].namespaceURI, svgNamespace);
});

test('#parseHTML of stop with linearGradient contextual element', function(){
  dom.setNamespace(svgNamespace);
  var svgElement = document.createElementNS(svgNamespace, 'linearGradient'),
      nodes = dom.parseHTML('<stop />', svgElement).childNodes;
  equal(nodes[0].tagName, 'stop');
  equal(nodes[0].namespaceURI, svgNamespace);
});

test('#addClasses on SVG', function(){
  var node = document.createElementNS(svgNamespace, 'svg');
  dom.addClasses(node, ['super-fun']);
  equal(node.getAttribute('class'), 'super-fun');
  dom.addClasses(node, ['super-fun']);
  equal(node.getAttribute('class'), 'super-fun');
  dom.addClasses(node, ['super-blast']);
  equal(node.getAttribute('class'), 'super-fun super-blast');
});

test('#removeClasses on SVG', function(){
  var node = document.createElementNS(svgNamespace, 'svg');
  node.setAttribute('class', 'this-class that-class');
  dom.removeClasses(node, ['this-class']);
  equal(node.getAttribute('class'), 'that-class');
  dom.removeClasses(node, ['this-class']);
  equal(node.getAttribute('class'), 'that-class');
  dom.removeClasses(node, ['that-class']);
  equal(node.getAttribute('class'), '');
});

}


text:
package nsqd

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/bitly/go-simplejson"
	"github.com/bitly/nsq/util"
	"github.com/bitly/nsq/util/lookupd"
)

type NSQD struct {
	// 64bit atomic vars need to be first for proper alignment on 32bit platforms
	clientIDSequence int64

	sync.RWMutex

	options *nsqdOptions

	topicMap map[string]*Topic

	lookupPeers []*lookupPeer

	tcpAddr       *net.TCPAddr
	httpAddr      *net.TCPAddr
	httpsAddr     *net.TCPAddr
	tcpListener   net.Listener
	httpListener  net.Listener
	httpsListener net.Listener
	tlsConfig     *tls.Config

	idChan     chan MessageID
	notifyChan chan interface{}
	exitChan   chan int
	waitGroup  util.WaitGroupWrapper
}

func NewNSQD(options *nsqdOptions) *NSQD {
	var httpsAddr *net.TCPAddr

	if options.MaxDeflateLevel < 1 || options.MaxDeflateLevel > 9 {
		log.Fatalf("--max-deflate-level must be [1,9]")
	}

	tcpAddr, err := net.ResolveTCPAddr("tcp", options.TCPAddress)
	if err != nil {
		log.Fatal(err)
	}

	httpAddr, err := net.ResolveTCPAddr("tcp", options.HTTPAddress)
	if err != nil {
		log.Fatal(err)
	}

	if options.HTTPSAddress != "" {
		httpsAddr, err = net.ResolveTCPAddr("tcp", options.HTTPSAddress)
		if err != nil {
			log.Fatal(err)
		}
	}

	if options.StatsdPrefix != "" {
		statsdHostKey := util.StatsdHostKey(net.JoinHostPort(options.BroadcastAddress,
			strconv.Itoa(httpAddr.Port)))
		prefixWithHost := strings.Replace(options.StatsdPrefix, "%s", statsdHostKey, -1)
		if prefixWithHost[len(prefixWithHost)-1] != '.' {
			prefixWithHost += "."
		}
		options.StatsdPrefix = prefixWithHost
	}

	n := &NSQD{
		options:    options,
		tcpAddr:    tcpAddr,
		httpAddr:   httpAddr,
		httpsAddr:  httpsAddr,
		topicMap:   make(map[string]*Topic),
		idChan:     make(chan MessageID, 4096),
		exitChan:   make(chan int),
		notifyChan: make(chan interface{}),
		tlsConfig:  buildTLSConfig(options),
	}

	n.waitGroup.Wrap(func() { n.idPump() })

	return n
}

func (n *NSQD) Main() {
	var httpListener net.Listener
	var httpsListener net.Listener

	context := &context{n}

	if n.options.TLSClientAuthPolicy != "" {
		n.options.TLSRequired = true
	}

	if n.tlsConfig == nil && n.options.TLSRequired {
		log.Fatalf("FATAL: cannot require TLS client connections without TLS key and cert")
	}

	n.waitGroup.Wrap(func() { n.lookupLoop() })

	tcpListener, err := net.Listen("tcp", n.tcpAddr.String())
	if err != nil {
		log.Fatalf("FATAL: listen (%s) failed - %s", n.tcpAddr, err.Error())
	}
	n.tcpListener = tcpListener
	tcpServer := &tcpServer{context: context}
	n.waitGroup.Wrap(func() { util.TCPServer(n.tcpListener, tcpServer) })

	if n.tlsConfig != nil && n.httpsAddr != nil {
		httpsListener, err = tls.Listen("tcp", n.httpsAddr.String(), n.tlsConfig)
		if err != nil {
			log.Fatalf("FATAL: listen (%s) failed - %s", n.httpsAddr, err.Error())
		}
		n.httpsListener = httpsListener
		httpsServer := &httpServer{
			context:     context,
			tlsEnabled:  true,
			tlsRequired: true,
		}
		n.waitGroup.Wrap(func() { util.HTTPServer(n.httpsListener, httpsServer, "HTTPS") })
	}
	httpListener, err = net.Listen("tcp", n.httpAddr.String())
	if err != nil {
		log.Fatalf("FATAL: listen (%s) failed - %s", n.httpAddr, err.Error())
	}
	n.httpListener = httpListener
	httpServer := &httpServer{
		context:     context,
		tlsEnabled:  false,
		tlsRequired: n.options.TLSRequired,
	}
	n.waitGroup.Wrap(func() { util.HTTPServer(n.httpListener, httpServer, "HTTP") })

	if n.options.StatsdAddress != "" {
		n.waitGroup.Wrap(func() { n.statsdLoop() })
	}
}

func (n *NSQD) LoadMetadata() {
	fn := fmt.Sprintf(path.Join(n.options.DataPath, "nsqd.%d.dat"), n.options.ID)
	data, err := ioutil.ReadFile(fn)
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("ERROR: failed to read channel metadata from %s - %s", fn, err.Error())
		}
		return
	}

	js, err := simplejson.NewJson(data)
	if err != nil {
		log.Printf("ERROR: failed to parse metadata - %s", err.Error())
		return
	}

	topics, err := js.Get("topics").Array()
	if err != nil {
		log.Printf("ERROR: failed to parse metadata - %s", err.Error())
		return
	}

	for ti := range topics {
		topicJs := js.Get("topics").GetIndex(ti)

		topicName, err := topicJs.Get("name").String()
		if err != nil {
			log.Printf("ERROR: failed to parse metadata - %s", err.Error())
			return
		}
		if !util.IsValidTopicName(topicName) {
			log.Printf("WARNING: skipping creation of invalid topic %s", topicName)
			continue
		}
		topic := n.GetTopic(topicName)

		paused, _ := topicJs.Get("paused").Bool()
		if paused {
			topic.Pause()
		}

		channels, err := topicJs.Get("channels").Array()
		if err != nil {
			log.Printf("ERROR: failed to parse metadata - %s", err.Error())
			return
		}

		for ci := range channels {
			channelJs := topicJs.Get("channels").GetIndex(ci)

			channelName, err := channelJs.Get("name").String()
			if err != nil {
				log.Printf("ERROR: failed to parse metadata - %s", err.Error())
				return
			}
			if !util.IsValidChannelName(channelName) {
				log.Printf("WARNING: skipping creation of invalid channel %s", channelName)
				continue
			}
			channel := topic.GetChannel(channelName)

			paused, _ = channelJs.Get("paused").Bool()
			if paused {
				channel.Pause()
			}
		}
	}
}

func (n *NSQD) PersistMetadata() error {
	// persist metadata about what topics/channels we have
	// so that upon restart we can get back to the same state
	fileName := fmt.Sprintf(path.Join(n.options.DataPath, "nsqd.%d.dat"), n.options.ID)
	log.Printf("NSQ: persisting topic/channel metadata to %s", fileName)

	js := make(map[string]interface{})
	topics := make([]interface{}, 0)
	for _, topic := range n.topicMap {
		topicData := make(map[string]interface{})
		topicData["name"] = topic.name
		topicData["paused"] = topic.IsPaused()
		channels := make([]interface{}, 0)
		topic.Lock()
		for _, channel := range topic.channelMap {
			channel.Lock()
			if !channel.ephemeralChannel {
				channelData := make(map[string]interface{})
				channelData["name"] = channel.name
				channelData["paused"] = channel.IsPaused()
				channels = append(channels, channelData)
			}
			channel.Unlock()
		}
		topic.Unlock()
		topicData["channels"] = channels
		topics = append(topics, topicData)
	}
	js["version"] = util.BINARY_VERSION
	js["topics"] = topics

	data, err := json.Marshal(&js)
	if err != nil {
		return err
	}

	tmpFileName := fileName + ".tmp"
	f, err := os.OpenFile(tmpFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}

	_, err = f.Write(data)
	if err != nil {
		f.Close()
		return err
	}
	f.Sync()
	f.Close()

	err = atomic_rename(tmpFileName, fileName)
	if err != nil {
		return err
	}

	return nil
}

func (n *NSQD) Exit() {
	if n.tcpListener != nil {
		n.tcpListener.Close()
	}

	if n.httpListener != nil {
		n.httpListener.Close()
	}

	if n.httpsListener != nil {
		n.httpsListener.Close()
	}

	n.Lock()
	err := n.PersistMetadata()
	if err != nil {
		log.Printf("ERROR: failed to persist metadata - %s", err.Error())
	}
	log.Printf("NSQ: closing topics")
	for _, topic := range n.topicMap {
		topic.Close()
	}
	n.Unlock()

	// we want to do this last as it closes the idPump (if closed first it
	// could potentially starve items in process and deadlock)
	close(n.exitChan)
	n.waitGroup.Wait()
}

// GetTopic performs a thread safe operation
// to return a pointer to a Topic object (potentially new)
func (n *NSQD) GetTopic(topicName string) *Topic {
	n.Lock()
	t, ok := n.topicMap[topicName]
	if ok {
		n.Unlock()
		return t
	} else {
		t = NewTopic(topicName, &context{n})
		n.topicMap[topicName] = t

		log.Printf("TOPIC(%s): created", t.name)

		// release our global nsqd lock, and switch to a more granular topic lock while we init our
		// channels from lookupd. This blocks concurrent PutMessages to this topic.
		t.Lock()
		n.Unlock()
		// if using lookupd, make a blocking call to get the topics, and immediately create them.
		// this makes sure that any message received is buffered to the right channels
		if len(n.lookupPeers) > 0 {
			channelNames, _ := lookupd.GetLookupdTopicChannels(t.name, n.lookupHttpAddrs())
			for _, channelName := range channelNames {
				t.getOrCreateChannel(channelName)
			}
		}
		t.Unlock()

		// NOTE: I would prefer for this to only happen in topic.GetChannel() but we're special
		// casing the code above so that we can control the locks such that it is impossible
		// for a message to be written to a (new) topic while we're looking up channels
		// from lookupd...
		//
		// update messagePump state
		select {
		case t.channelUpdateChan <- 1:
		case <-t.exitChan:
		}
	}
	return t
}

// GetExistingTopic gets a topic only if it exists
func (n *NSQD) GetExistingTopic(topicName string) (*Topic, error) {
	n.RLock()
	defer n.RUnlock()
	topic, ok := n.topicMap[topicName]
	if !ok {
		return nil, errors.New("topic does not exist")
	}
	return topic, nil
}

// DeleteExistingTopic removes a topic only if it exists
func (n *NSQD) DeleteExistingTopic(topicName string) error {
	n.RLock()
	topic, ok := n.topicMap[topicName]
	if !ok {
		n.RUnlock()
		return errors.New("topic does not exist")
	}
	n.RUnlock()

	// delete empties all channels and the topic itself before closing
	// (so that we dont leave any messages around)
	//
	// we do this before removing the topic from map below (with no lock)
	// so that any incoming writes will error and not create a new topic
	// to enforce ordering
	topic.Delete()

	n.Lock()
	delete(n.topicMap, topicName)
	n.Unlock()

	return nil
}

func (n *NSQD) idPump() {
	factory := &guidFactory{}
	lastError := time.Now()
	for {
		id, err := factory.NewGUID(n.options.ID)
		if err != nil {
			now := time.Now()
			if now.Sub(lastError) > time.Second {
				// only print the error once/second
				log.Printf("ERROR: %s", err.Error())
				lastError = now
			}
			runtime.Gosched()
			continue
		}
		select {
		case n.idChan <- id.Hex():
		case <-n.exitChan:
			goto exit
		}
	}

exit:
	log.Printf("ID: closing")
}

func (n *NSQD) Notify(v interface{}) {
	// by selecting on exitChan we guarantee that
	// we do not block exit, see issue #123
	select {
	case <-n.exitChan:
	case n.notifyChan <- v:
		n.Lock()
		err := n.PersistMetadata()
		if err != nil {
			log.Printf("ERROR: failed to persist metadata - %s", err.Error())
		}
		n.Unlock()
	}
}

func buildTLSConfig(options *nsqdOptions) *tls.Config {
	var tlsConfig *tls.Config

	if options.TLSCert == "" && options.TLSKey == "" {
		return nil
	}

	tlsClientAuthPolicy := tls.VerifyClientCertIfGiven

	cert, err := tls.LoadX509KeyPair(options.TLSCert, options.TLSKey)
	if err != nil {
		log.Fatalf("ERROR: failed to LoadX509KeyPair %s", err.Error())
	}
	switch options.TLSClientAuthPolicy {
	case "require":
		tlsClientAuthPolicy = tls.RequireAnyClientCert
	case "require-verify":
		tlsClientAuthPolicy = tls.RequireAndVerifyClientCert
	default:
		tlsClientAuthPolicy = tls.NoClientCert
	}

	tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
		ClientAuth:   tlsClientAuthPolicy,
	}

	if options.TLSRootCAFile != "" {
		tlsCertPool := x509.NewCertPool()
		ca_cert_file, err := ioutil.ReadFile(options.TLSRootCAFile)
		if err != nil {
			log.Fatalf("ERROR: failed to read custom Certificate Authority file %s", err.Error())
		}
		if !tlsCertPool.AppendCertsFromPEM(ca_cert_file) {
			log.Fatalf("ERROR: failed to append certificates from Certificate Authority file")
		}
		tlsConfig.ClientCAs = tlsCertPool
	}

	tlsConfig.BuildNameToCertificate()

	return tlsConfig
}

func (n *NSQD) IsAuthEnabled() bool {
	return len(n.options.AuthHTTPAddresses) != 0
}


text:
@interface ZKPackageVersion()
@property (assign,nonatomic) NSInteger  majorNumber__v;
@property (assign,nonatomic) NSInteger  minorNumber__v;
@property (strong,nonatomic) NSString  *namespace__v;
@end

@implementation ZKPackageVersion

+(void)load {
    [self registerType:self xmlName:@"PackageVersion"];
}

+(ZKComplexTypeInfo *)wsdlSchema {
   static ZKComplexTypeInfo *wsdlSchema;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       wsdlSchema = [[ZKComplexTypeInfo alloc] initWithType:@"PackageVersion" parent:nil
                    fields:@[
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"majorNumber" propertyName:@"majorNumber" optional:NO nillable:NO],
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"minorNumber" propertyName:@"minorNumber" optional:NO nillable:NO],
                        [[ZKComplexTypeFieldInfo alloc] initWithElementName:@"namespace" propertyName:@"namespace" optional:NO nillable:NO],

                    ]];
   });
   return wsdlSchema;
}

-(NSInteger)majorNumber {
    if ((fields__set[0] & 0x1) == 0) {
        self.majorNumber__v = [self integer:@"majorNumber"];
        fields__set[0] |= 0x1;
    }
    return self.majorNumber__v;
}

-(void)setMajorNumber:(NSInteger)v {
    self.majorNumber__v = v;
    fields__set[0] |= 0x1;
}

-(NSInteger)minorNumber {
    if ((fields__set[0] & 0x2) == 0) {
        self.minorNumber__v = [self integer:@"minorNumber"];
        fields__set[0] |= 0x2;
    }
    return self.minorNumber__v;
}

-(void)setMinorNumber:(NSInteger)v {
    self.minorNumber__v = v;
    fields__set[0] |= 0x2;
}

-(NSString *)namespace {
    if ((fields__set[0] & 0x4) == 0) {
        self.namespace__v = [self string:@"namespace"];
        fields__set[0] |= 0x4;
    }
    return self.namespace__v;
}

-(void)setNamespace:(NSString *)v {
    self.namespace__v = v;
    fields__set[0] |= 0x4;
}

-(void)serializeTo:(ZKXmlWriter *)env elemName:(NSString *)elemName {
	[env startElement:elemName];
	[env addIntElement:@"majorNumber" elemValue:self.majorNumber];
	[env addIntElement:@"minorNumber" elemValue:self.minorNumber];
	[env addElement:@"namespace"      elemValue:self.namespace   nillable:NO  optional:NO];
	[env endElement:elemName];
}
@end


text:
package com.adben.testdatabuilder.entity.analyzers.introspectors.introspectorset;

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import com.adben.testdatabuilder.core.analyzers.generators.generatorset.DefaultGeneratorSet;
import com.adben.testdatabuilder.core.analyzers.introspectors.Introspector;
import com.adben.testdatabuilder.core.analyzers.introspectors.introspector.GeneratedIntrospector;
import com.adben.testdatabuilder.core.analyzers.introspectors.introspector.NoOpIntrospector;
import com.adben.testdatabuilder.core.analyzers.introspectors.introspectorset.AbstractIntrospectorSet;
import com.adben.testdatabuilder.entity.analyzers.introspectors.introspector.EmbeddableIntrospector;
import com.adben.testdatabuilder.entity.analyzers.introspectors.introspector.GeneratedValueIntrospector;
import com.adben.testdatabuilder.entity.analyzers.introspectors.introspector.IterableEntityIntrospector;
import com.adben.testdatabuilder.entity.analyzers.introspectors.introspector.NestedEntityIntrospector;
import com.adben.testdatabuilder.entity.analyzers.introspectors.introspector.StringColumnIntrospector;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;

/**
 * The entity {@link Introspector}Set. This is a specialism of an {@link Introspector}, that
 * contains an {@link Iterable} of other {@link Introspector}s, where given the field and object
 * loop over and return when one of the {@link Introspector}s applies a field generatedValue.
 *
 * <p>
 *
 * See {@link EntityIntrospectorSet#introspectors} for the default values.
 */
public class EntityIntrospectorSet extends AbstractIntrospectorSet {

  private static final Logger LOGGER = getLogger(lookup().lookupClass());

  public EntityIntrospectorSet() {
    super(ImmutableList.<Introspector>builder()
        .add(new NoOpIntrospector())
        .add(new GeneratedValueIntrospector())
        .add(new StringColumnIntrospector())
        .add(new IterableEntityIntrospector())
        .add(new NestedEntityIntrospector())
        .add(new EmbeddableIntrospector())
        .add(new GeneratedIntrospector(new DefaultGeneratorSet()))
        .build());
    LOGGER.debug("Default constructor");
  }

}


text:
module TwentyfourSevenOffice
  module DataTypes
    # http://help.24sevenoffice.com/index.php?title=API:ProductService_DataTypes#ProductSearchParameters
    class ProductSearchParameters < DataType
      attribute :id, Integer
      attribute :no, String
      attribute :ean1, String
      attribute :name, String
      attribute :price, Float
      attribute :date_changed, DateTime
    end
  end
end


text:
+++
Title = "Steve Persch"
Twitter = "stevector"
image = "steve-persch.png"
type = "speaker"
linktitle = "steve-persch"

+++

Steve Persch is the Lead Developer Advocate at Pantheon. Pantheon is a San Francisco based website management platform for Drupal and WordPress. Steve works out of Pantheon's downtown Minneapolis office. As a Developer Advocate, Steve draws on his experience developing WordPress and Drupal sites in order to advise Pantheon customers around workflow, CI, architecture, and performance best practices. You will find commits from Steve throughout Pantheon's GitHub repos along with many in Drupal core and contributed modules.