text:
/*
 */
package org.apache.tomcat.lite.http;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.tomcat.lite.http.HttpConnector.HttpConnection;
import org.apache.tomcat.lite.http.HttpMessage.HttpMessageBytes;
import org.apache.tomcat.lite.io.BBucket;
import org.apache.tomcat.lite.io.BBuffer;
import org.apache.tomcat.lite.io.CBuffer;
import org.apache.tomcat.lite.io.DumpChannel;
import org.apache.tomcat.lite.io.FastHttpDateFormat;
import org.apache.tomcat.lite.io.Hex;
import org.apache.tomcat.lite.io.IOBuffer;
import org.apache.tomcat.lite.io.IOChannel;
import org.apache.tomcat.lite.io.IOConnector;

public class Http11Connection extends HttpConnection
        implements IOConnector.ConnectedCallback {
    public static final String CHUNKED = "chunked";

    public static final String CLOSE = "close";

    public static final String KEEPALIVE_S = "keep-alive";

    public static final String CONNECTION = "connection";

    public static final String TRANSFERENCODING = "transfer-encoding";

    protected static Logger log = Logger.getLogger("Http11Connection");
    static final byte COLON = (byte) ':';

    // super.net is the socket

    boolean debug;
    BBuffer line = BBuffer.wrapper();
    boolean endSent = false;

    BodyState receiveBodyState = new BodyState();
    BodyState sendBodyState = new BodyState();

    BBuffer headW = BBuffer.wrapper();

    boolean headersReceived = false;
    boolean bodyReceived = false;

    /**
     * Close connection when done writting, no content-length/chunked,
     * or no keep-alive ( http/1.0 ) or error.
     *
     * ServerMode: set if HTTP/0.9 &1.0 || !keep-alive
     * ClientMode: not currently used
     */
    boolean keepAlive = true;

    protected boolean http11 = true;
    protected boolean http10 = false;
    protected boolean http09 = false;

    HttpConnection switchedProtocol = null;

    private int requestCount = 0;

    // dataReceived and endSendReceive
    private Object readLock = new Object();

    public Http11Connection(HttpConnector httpConnector) {
        this.httpConnector = httpConnector;
        if (httpConnector != null) {
            debug = httpConnector.debugHttp;
        }
    }

    public void beforeRequest() {
        nextRequest();
        headRecvBuf.recycle();
    }

    public void nextRequest() {
        endSent = false;
        keepAlive = true;
        receiveBodyState.recycle();
        sendBodyState.recycle();
        http11 = true;
        http09 = false;
        http10 = false;
        headersReceived = false;
        bodyReceived = false;
    }

    public Http11Connection serverMode() {
        serverMode = true;
        return this;
    }

    private boolean readHead() throws IOException {
        while (true) {
            int read;
            if (requestCount == 0 && headRecvBuf.remaining() < 4) {
                // requests have at least 4 bytes - detect protocol
                read = net.getIn().read(headRecvBuf, 4);
                if (read < 0) {
                    return closeInHead();
                }
                if (read < 4) {
                    return false; // need more
                }
                // we have at least 4 bytes
                if (headRecvBuf.get(0) == 0x80 &&
                        headRecvBuf.get(1) == 0x01) {
                    // SPDY signature ( experimental )
                    switchedProtocol = new SpdyConnection(httpConnector,
                            remoteHost);
                    if (serverMode) {
                        switchedProtocol.serverMode = true;
                    }
                    switchedProtocol.withExtraBuffer(headRecvBuf);
                    // Will also call handleReceived
                    switchedProtocol.setSink(net);
                    return false;
                }

            }

            // we know we have one
            read = net.getIn().readLine(headRecvBuf);
            // Remove starting empty lines.
            headRecvBuf.skipEmptyLines();

            // Do we have another full line in the input ?
            if (BBuffer.hasLFLF(headRecvBuf)) {
                break; // done
            }
            if (read == 0) { // no more data
                return false;
            }
            if (read < 0) {
                return closeInHead();
            }
        }

        return true;
    }

    private boolean closeInHead() throws IOException {
        if (debug) {
            trace("CLOSE while reading HEAD");
        }
        // too early - we don't have the head
        abort("Close in head");
        return false;
    }

    // Unit tests use this to access the HttpChannel
    protected HttpChannel checkHttpChannel() throws IOException {
        if (switchedProtocol != null) {
            return switchedProtocol.checkHttpChannel();
        }
        if (activeHttp == null) {
            if (serverMode) {
                activeHttp = httpConnector.getServer();
                activeHttp.setConnection(this);
                if (httpConnector.defaultService != null) {
                    activeHttp.setHttpService(httpConnector.defaultService);
                }
            } else {
            }
        }
        return activeHttp;
    }

    @Override
    public void dataReceived(IOBuffer netx) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.dataReceived(netx);
            return;
        }
        //trace("handleReceived " + headersReceived);
        if (!checkKeepAliveClient()) {
            return; // we were in client keep alive mode
        }
        // endSendReceived uses same lock - it will call this
        // to check outstanding bytes
        synchronized (readLock) {
            if (bodyReceived) {
                return; // leave data in net buffer, for next req
            }

            if (!headersReceived) {
                if (!readHead()) {
                    return;
                }
            }

            // We have a header
            if (activeHttp == null) {
                if (checkHttpChannel() == null) {
                    return;
                }
            }

            IOBuffer receiveBody = activeHttp.receiveBody;

            if (!headersReceived) {
                headRecvBuf.wrapTo(headW);
                parseMessage(activeHttp, headW);
                // Part of parseMessage we can switch the protocol
                if (switchedProtocol != null) {
                    return;
                }

                if (serverMode && activeHttp.httpReq.decodedUri.remaining() == 0) {
                    abort(activeHttp, "Invalid url");
                }

                headersReceived = true;
                // Send header callbacks - we process any incoming data
                // first, so callbacks have more info
                trace("Send headers received callback " + activeHttp.httpService);
                activeHttp.handleHeadersReceived(activeHttp.inMessage);
            }

            // any remaining data will be processed as part of the
            // body - or left in the channel until endSendReceive()

            if (!bodyReceived) {
                // Will close receiveBody when it consummed enough
                rawDataReceived(activeHttp, receiveBody, net.getIn());
                // Did we process anything ?
                if (receiveBody.getBufferCount() > 0) {
                    activeHttp.sendHandleReceivedCallback(); // callback
                }
            }
            // Receive has marked the body as closed
            if (receiveBody.isAppendClosed()) {
                bodyReceived = true;
                activeHttp.handleEndReceive();
            }

            if (net.getIn().isClosedAndEmpty()) {
                // If not already closed.
                closeStreamOnEnd("closed after body");
            }

        }
    }

    /**
     * We got data while in client keep alive ( no activeHttp )
     *
     * @return false if there is an error
     */
    private boolean checkKeepAliveClient() throws IOException {
        // Client, no active connection ( keep alive )
        if (!serverMode && activeHttp == null) {
            if (net.getIn().isClosedAndEmpty() || !net.isOpen()) {
                // server disconnected, fine
                httpConnector.cpool.stopKeepAlive(this);
                return false;
            }
            if (net.getIn().available() == 0) {
                return true;
            }
            log.warning("Unexpected message from server in client keep alive "
                    + net.getIn() + ": " + net.getIn().readAll(null));
            if (net.isOpen()) {
                net.close();
            }
            return false;
        }
        return true;
    }

    private void processProtocol(CBuffer protocolMB) throws IOException {
        http11 = false;
        http09 = false;
        http10 = false;

        if (protocolMB.equals(HttpChannel.HTTP_11)) {
            http11 = true;
        } else if (protocolMB.equals(HttpChannel.HTTP_10)) {
            http10 = true;
        } else if (protocolMB.equals("")) {
            http09 = true;
        } else {
            http11 = true; // hopefully will be backward compat
        }
    }

    void closeStreamOnEnd(String cause) {
        if (debug) {
            log.info("Not reusing connection because: " + cause);
        }
        keepAlive = false;
    }

    boolean keepAlive() {
        if (httpConnector != null) {
            if (serverMode && !httpConnector.serverKeepAlive) {
                keepAlive = false;
            }
            if (!serverMode && !httpConnector.clientKeepAlive) {
                keepAlive = false;
            }
        }
        if (http09) {
            keepAlive = false;
        }
        if (net != null && !net.isOpen()) {
            keepAlive = false;
        }
        return keepAlive;
    }

    @Override
    protected void endSendReceive(HttpChannel http) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.endSendReceive(http);
            return;
        }
        chunk.recycle();
        rchunk.recycle();
        boolean keepAlive = keepAlive();
        if (!keepAlive) {
            if (debug) {
                log.info("--- Close socket, no keepalive " + net);
            }
            if (net != null) {
                net.close();
                net.startSending();

            }
        }

        requestCount++;
        beforeRequest();
        httpConnector.cpool.afterRequest(http, this, true);

        if (serverMode && keepAlive) {
            handleReceived(net); // will attempt to read next req
        }
    }

    private void trace(String s) {
        if(debug) {
            log.info(this.toString() + " " + activeHttp + " " + s);
        }
    }

    private boolean isDone(BodyState bodys, IOBuffer body) {
        if (bodys.noBody) {
            return true;
        }
        if (bodys.isContentDelimited()) {
            if (!bodys.chunked && bodys.remaining == 0) {
                return true;
            } else if (bodys.chunked && body.isAppendClosed()) {
                return true;
            }
        }
        return false;
    }

    void parseMessage(HttpChannel http, BBuffer headB) throws IOException {
        //Parse the response
        line.recycle();
        headB.readLine(line);

        HttpMessageBytes msgBytes;

        if (serverMode) {
            msgBytes = http.httpReq.getMsgBytes();
            parseRequestLine(line, msgBytes.method(),
                    msgBytes.url(),
                    msgBytes.query(),
                    msgBytes.protocol());
        } else {
            msgBytes = http.httpRes.getMsgBytes();
            parseResponseLine(line, msgBytes.protocol(),
                    msgBytes.status(), msgBytes.message());
        }

        parseHeaders(http, msgBytes, headB);

        http.inMessage.state = HttpMessage.State.BODY_DATA;

        http.inMessage.processReceivedHeaders();

        // TODO: hook to allow specific charsets ( can be done later )
        processProtocol(http.inMessage.protocol());

        if (serverMode) {
            // requested connection:close/keepAlive and proto
            updateKeepAlive(http.getRequest().getMimeHeaders(), true);

            processExpectation(http);

            processContentDelimitation(receiveBodyState, http.getRequest());
            // Spec:
            // The presence of a message-body in a request is signaled by the
            // inclusion of a Content-Length or Transfer-Encoding header field in
            // the request's message-headers
            // Server should read - but ignore ..
            receiveBodyState.noBody = !receiveBodyState.isContentDelimited();

            updateCloseOnEnd(receiveBodyState, http, http.receiveBody);

            /*
             * The presence of a message-body in a request is signaled by the
             * inclusion of a Content-Length or Transfer-Encoding header field in
             * the request's message-headers. A message-body MUST NOT be included
             * in a request if the specification of the request method
             * (section 5.1.1) does not allow sending an entity-body in requests.
             * A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.
             */
            if (!receiveBodyState.isContentDelimited()) {
                // No body
                http.getIn().close();
            }

        } else {
            receiveBodyState.noBody = !http.getResponse().hasBody();

            updateKeepAlive(http.getResponse().getMimeHeaders(), false);

            if (statusDropsConnection(http.getResponse().getStatus())) {
                closeStreamOnEnd("response status drops connection");
            }
            IOBuffer body = http.receiveBody;
            processContentDelimitation(receiveBodyState, http.getResponse());

            if (isDone(receiveBodyState, body)) {
                body.close();
            }

            if (!receiveBodyState.isContentDelimited()) {
                closeStreamOnEnd("not content delimited");
            }
        }

    }

    private void processExpectation(HttpChannel http) throws IOException {
        http.expectation = false;
        MultiMap headers = http.getRequest().getMimeHeaders();

        CBuffer expect = headers.getHeader("expect");
        if ((expect != null)
                && (expect.indexOf("100-continue") != -1)) {
            http.expectation = true;

            // TODO: configure, use the callback or the servlet 'read'.
            net.getOut().append("HTTP/1.1 100 Continue\r\n\r\n");
            net.startSending();
        }
    }

    /**
     * Updates chunked, contentLength, remaining - based
     * on headers
     */
    private void processContentDelimitation(BodyState bodys,
            HttpMessage httpMsg) {

        bodys.contentLength = httpMsg.getContentLength();
        if (bodys.contentLength >= 0) {
            bodys.remaining = bodys.contentLength;
        }

        // TODO: multiple transfer encoding headers, only process the last
        String transferEncodingValue = httpMsg.getHeader(TRANSFERENCODING);
        if (transferEncodingValue != null) {
            int startPos = 0;
            int commaPos = transferEncodingValue.indexOf(',');
            String encodingName = null;
            while (commaPos != -1) {
                encodingName = transferEncodingValue.substring
                (startPos, commaPos).toLowerCase().trim();
                if ("chunked".equalsIgnoreCase(encodingName)) {
                    bodys.chunked = true;
                }
                startPos = commaPos + 1;
                commaPos = transferEncodingValue.indexOf(',', startPos);
            }
            encodingName = transferEncodingValue.substring(startPos)
                .toLowerCase().trim();
            if ("chunked".equals(encodingName)) {
                bodys.chunked = true;
                httpMsg.chunked = true;
            } else {
                System.err.println("TODO: ABORT 501");
                //return 501; // Currently only chunked is supported for
                // transfer encoding.
            }
        }

        if (bodys.chunked) {
            bodys.remaining = 0;
        }
    }

    /**
     * Read the request line. This function is meant to be used during the
     * HTTP request header parsing. Do NOT attempt to read the request body
     * using it.
     *
     * @throws IOException If an exception occurs during the underlying socket
     * read operations, or if the given buffer is not big enough to accomodate
     * the whole line.
     */
    boolean parseRequestLine(BBuffer line,
            BBuffer methodMB, BBuffer requestURIMB,
            BBuffer queryMB,
            BBuffer protoMB)
        throws IOException {

        line.readToSpace(methodMB);
        line.skipSpace();

        line.readToDelimOrSpace(HttpChannel.QUESTION, requestURIMB);
        if (line.remaining() > 0 && line.get(0) == HttpChannel.QUESTION) {
            // Has query
            line.readToSpace(queryMB);
            // don't include '?'
            queryMB.position(queryMB.position() + 1);
        } else {
            queryMB.setBytes(line.array(), line.position(), 0);
        }
        line.skipSpace();

        line.readToSpace(protoMB);

        // proto is optional ( for 0.9 )
        return requestURIMB.remaining() > 0;
    }

    boolean parseResponseLine(BBuffer line,
            BBuffer protoMB, BBuffer statusCode, BBuffer status)
            throws IOException {
        line.skipEmptyLines();

        line.readToSpace(protoMB);
        line.skipSpace();
        line.readToSpace(statusCode);
        line.skipSpace();
        line.wrapTo(status);

        // message may be empty
        return statusCode.remaining() > 0;
    }

    List<String> connectionHeaders = new ArrayList<String>();

    private void parseHeaders(HttpChannel http, HttpMessageBytes msgBytes,
            BBuffer head)
                throws IOException {

        head.readLine(line);

        int idx = 0;

        BBuffer upgrade = null;

        while(line.remaining() > 0) {
            // not empty..
            idx = msgBytes.addHeader();
            BBuffer nameBuf = msgBytes.getHeaderName(idx);
            BBuffer valBuf = msgBytes.getHeaderValue(idx);
            parseHeader(http, head, line, nameBuf, valBuf);

            // TODO: process 'interesting' headers here.
            if (nameBuf.equalsIgnoreCase("connection")) {
                // TODO: save and remove if not recognized
            }
            if (nameBuf.equalsIgnoreCase("upgrade")) {
                upgrade = valBuf;
            }
        }

        if (upgrade != null) {
            if (upgrade.equalsIgnoreCase("WebSocket")) {

            } else if (upgrade.equalsIgnoreCase("SPDY/1.0")) {

            }
        }

        // TODO: process connection headers
    }

    /**
     * Parse one header.
     * Line must be populated. On return line will be populated
     * with the next header:
     *
     * @param line current header line, not empty.
     */
    int parseHeader(HttpChannel http, BBuffer head,
            BBuffer line, BBuffer name, BBuffer value)
          throws IOException {

        int newPos = line.readToDelimOrSpace(COLON, name);
        line.skipSpace();
        if (line.readByte() != COLON) {
            throw new IOException("Missing ':' in header name " + line);
        }
        line.skipSpace();
        line.read(value); // remaining of the line

        while (true) {
            head.readLine(line);
            if (line.remaining() == 0) {
                break;
            }
            int first = line.get(0);
            if (first != BBuffer.SP && first != BBuffer.HT) {
                break;
            }
            // continuation line - append it to value
            value.setEnd(line.getEnd());
            line.position(line.limit());
        }

        // We may want to keep the original and use separate buffer ?
        http.normalizeHeader(value);
        return 1;
    }

    private int receiveDone(HttpChannel http, IOBuffer body, boolean frameError) throws IOException {
        // Content-length case, we're done reading
        body.close();

        http.error = frameError;
        if (frameError) {
            closeStreamOnEnd("frame error");
        }

        return DONE;
    }

    /**
     * Called when raw body data is received.
     * Callback should not consume past the end of the body.
     * @param rawReceiveBuffers
     *
     */
    private void rawDataReceived(HttpChannel http, IOBuffer body,
            IOBuffer rawReceiveBuffers) throws IOException {
        // TODO: Make sure we don't process more than we need ( eat next req ).
        // If we read too much: leave it in readBuf, the finalzation code
        // should skip KeepAlive and start processing it.
        // we need to read at least something - to detect -1 ( we could
        // suspend right away, but seems safer
        BodyState bodys = receiveBodyState;

        while (http.inMessage.state == HttpMessage.State.BODY_DATA) {
            if (receiveBodyState.noBody) {
                receiveDone(http, body, false);
                return;
            }
            if (rawReceiveBuffers.isClosedAndEmpty()) {
                if (receiveBodyState.isContentDelimited()) {
                    if (receiveBodyState.contentLength >= 0 && receiveBodyState.remaining == 0) {
                        receiveDone(http, body, false);
                    } else {
                        // End of input - other side closed, no more data
                        //log.info("CLOSE while reading " + this);
                        // they're not supposed to close !
                        receiveDone(http, body, true);
                    }
                } else {
                    receiveDone(http, body, false); // ok
                }
                // input connection closed ?
                closeStreamOnEnd("Closed input");
                return;
            }
            BBucket rawBuf = rawReceiveBuffers.peekFirst();
            if (rawBuf == null) {
                return;  // need more data
            }

            if (!bodys.isContentDelimited()) {
                while (true) {
                    BBucket first = rawReceiveBuffers.popFirst();
                    if (first == null) {
                        break; // will go back to check if done.
                    } else {
                        received(body, first);
                    }
                }
            } else {

                if (bodys.contentLength >= 0 && bodys.remaining == 0) {
                    receiveDone(http, body, false);
                    return;
                }

                if (bodys.chunked && bodys.remaining == 0) {
                    int rc = NEED_MORE;
                    // TODO: simplify, use readLine()
                    while (rc == NEED_MORE) {
                        rc = rchunk.parseChunkHeader(rawReceiveBuffers);
                        if (rc == ERROR) {
                            http.abort("Chunk error");
                            receiveDone(http, body, true);
                            return;
                        } else if (rc == NEED_MORE) {
                            return;
                        }
                    }
                    if (rc == 0) { // last chunk
                        receiveDone(http, body, false);
                        return;
                    } else {
                        bodys.remaining = rc;
                    }
                }

                rawBuf = (BBucket) rawReceiveBuffers.peekFirst();
                if (rawBuf == null) {
                    return;  // need more data
                }

                if (bodys.remaining < rawBuf.remaining()) {
                    // To buffer has more data than we need.
                    int lenToConsume = (int) bodys.remaining;
                    BBucket sb = rawReceiveBuffers.popLen(lenToConsume);
                    received(body, sb);
                    //log.info("Queue received buffer " + this + " " + lenToConsume);
                    bodys.remaining = 0;
                } else {
                    BBucket first = rawReceiveBuffers.popFirst();
                    bodys.remaining -= first.remaining();
                    received(body, first);
                    //log.info("Queue full received buffer " + this + " RAW: " + rawReceiveBuffers);
                }
                if (bodys.contentLength >= 0 && bodys.remaining == 0) {
                    // Content-Length, all done
                    body.close();
                    receiveDone(http, body, false);
                }
            }
        }
    }

    private void received(IOBuffer body, BBucket bb) throws IOException {
        body.queue(bb);
    }

    protected void sendRequest(HttpChannel http)
            throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.sendRequest(http);
            return;
        }

        // Update transfer fields based on headers.
        processProtocol(http.getRequest().protocol());
        updateKeepAlive(http.getRequest().getMimeHeaders(), true);

        // Update Host header
        if (http.getRequest().getMimeHeaders().getHeader("Host") == null) {
            String target = http.getTarget();
            if (target == null) {
                throw new IOException("Missing host header");
            }
            CBuffer hostH = http.getRequest().getMimeHeaders().addValue("Host");
            if (target.endsWith(":80")) {
                hostH.set(target.substring(0, target.length() - 3));
            } else {
                hostH.set(target);
            }
        }

        processContentDelimitation(sendBodyState,
                http.getRequest());

        CBuffer method = http.getRequest().method();
        if (method.equals("GET") || method.equals("HEAD")) {
            // TODO: add the others
            sendBodyState.noBody = true;
        }

        // 1.0: The presence of an entity body in a request is signaled by
        // the inclusion of a Content-Length header field in the request
        // message headers. HTTP/1.0 requests containing an entity body
        // must include a valid Content-Length header field.
        if (http10 && !sendBodyState.isContentDelimited()) {
            // Will not close connection - just flush and mark the body
            // as sent
            sendBodyState.noBody = true;
        }

        if (sendBodyState.noBody) {
            http.getRequest().getMimeHeaders().remove(HttpChannel.CONTENT_LENGTH);
            http.getRequest().getMimeHeaders().remove(TRANSFERENCODING);
            http.getOut().close();
        } else {
            long contentLength =
                http.getRequest().getContentLength();
            if (contentLength < 0) {
                http.getRequest().getMimeHeaders().addValue("Transfer-Encoding").
                    set(CHUNKED);
            }
        }

        updateCloseOnEnd(sendBodyState, http, http.sendBody);

        try {
            serialize(http.getRequest(), net.getOut());
            if (http.debug) {
                http.trace("S: \n" + net.getOut());
            }

            if (http.outMessage.state == HttpMessage.State.HEAD) {
                http.outMessage.state = HttpMessage.State.BODY_DATA;
            }

            // TODO: add any body and flush. More body can be added later -
            // including 'end'.

            http.startSending();
        } catch (Throwable t) {
            log.log(Level.SEVERE, "Error sending request", t);
            abort(t.getMessage());
        }

    }

    /**
     * Determine if we must drop the connection because of the HTTP status
     * code.  Use the same list of codes as Apache/httpd.
     */
    private boolean statusDropsConnection(int status) {
        return status == 400 /* SC_BAD_REQUEST */ ||
        status == 408 /* SC_REQUEST_TIMEOUT */ ||
        status == 411 /* SC_LENGTH_REQUIRED */ ||
        status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ ||
        status == 414 /* SC_REQUEST_URI_TOO_LARGE */ ||
        status == 500 /* SC_INTERNAL_SERVER_ERROR */ ||
        status == 503 /* SC_SERVICE_UNAVAILABLE */ ||
        status == 501 /* SC_NOT_IMPLEMENTED */;
    }

    protected void sendResponseHeaders(HttpChannel http)
            throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.sendResponseHeaders(http);
            return;
        }

        if (!serverMode) {
            throw new IOException("Only in server mode");
        }
        endSent = false;
        IOBuffer sendBody = http.sendBody;
        HttpResponse res = http.getResponse();
        if (res.isCommitted()) {
            return;
        }
        res.setCommitted(true);

        sendBodyState.noBody = !res.hasBody();

        if (statusDropsConnection(res.getStatus())) {
            closeStreamOnEnd("status drops connection");
        }
        if (http.error) {
            closeStreamOnEnd("error");
        }

        MultiMap headers = res.getMimeHeaders();

        // Add date header
        if (headers.getHeader("Date") == null) {
            headers.setValue("Date").set(FastHttpDateFormat.getCurrentDate());
        }

        // Add server header
        if (http.serverHeader.length() > 0) {
            headers.setValue("Server").set(http.serverHeader);
        }

        // Decide on a transfer encoding for out.
        if (keepAlive()) { // request and user allows keep alive
            int cl = res.getContentLength();

            if (http10) {
                if (cl < 0 && !sendBodyState.noBody &&
                        sendBody.isAppendClosed()) {
                    // We can generate content-lenght
                    cl = sendBody.available();
                    res.setContentLength(cl);
                }
                if (cl < 0 && !sendBodyState.noBody) {
                    closeStreamOnEnd("HTTP/1.0 without content length");
                } else {
                    headers.setValue(CONNECTION).set(KEEPALIVE_S);
                }
            } else { // http11
                if (!sendBodyState.noBody) {
                    if (cl < 0) {
                        res.getMimeHeaders().setValue(TRANSFERENCODING).set(CHUNKED);
                    }
                }
            }
        } else {
            headers.setValue(CONNECTION).set(CLOSE);
            // since we close the connection - don't bother with
            // transfer encoding
            headers.remove(TRANSFERENCODING);
        }

        // Update our internal state based on headers we just set.
        processContentDelimitation(sendBodyState, res);
        updateCloseOnEnd(sendBodyState, http, sendBody);

        if (http.debug) {
            http.trace("Send response headers " + net);
        }
        if (net != null) {
            serialize(res, net.getOut());
        }

        if (http.outMessage.state == HttpMessage.State.HEAD) {
            http.outMessage.state = HttpMessage.State.BODY_DATA;
        }

        if (isDone(sendBodyState, sendBody)) {
            http.getOut().close();
        }

        if (net != null) {
            net.startSending();
        }
    }

    private void abort(String t) throws IOException {
        abort(activeHttp, t);
    }

    private void updateCloseOnEnd(BodyState bodys, HttpChannel http, IOBuffer body) {
        if (!bodys.isContentDelimited() && !bodys.noBody) {
            closeStreamOnEnd("not content delimited");
        }
    }

    /**
     * Disconnect abruptly - client closed, frame errors, etc
     * @param t
     * @throws IOException
     */
    public void abort(HttpChannel http, String t) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.abort(http, t);
            return;
        }
        keepAlive = false;
        if (net != null ) {
            if (net.isOpen()) {
                net.close();
                net.startSending();
            }
        }
        if (http != null) {
            http.abort(t);
        }
    }

    /**
     * Update keepAlive based on Connection header and protocol.
     */
    private void updateKeepAlive(MultiMap headers, boolean request) {
        if (http09) {
            closeStreamOnEnd("http 0.9");
            return;
        }

        // TODO: also need to remove headers matching connection
        // ( like 'upgrade')

        CBuffer value = headers.getHeader(CONNECTION);
        // TODO: split it by space
        if (value != null) {
            value.toLower();
            if (value.indexOf(CLOSE) >= 0) {
                // 1.1 ( but we accept it for 1.0 too )
                closeStreamOnEnd("connection close");
            }
            if (http10 && value.indexOf(KEEPALIVE_S) < 0) {
                // Keep-Alive required for http/1.0
                closeStreamOnEnd("connection != keep alive");
            }
            // we have connection: keepalive, good
        } else {
            // no connection header - for 1.1 default is keepAlive,
            // for 10 it's close
            if (http10) {
                closeStreamOnEnd("http1.0 no connection header");
            }
        }
    }

    @Override
    public void startSending() throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.startSending();
            return;
        }

    }

    @Override
    public void startSending(HttpChannel http) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.startSending(http);
            return;
        }
        http.send(); // if needed

        if (net == null) {
            return; // not connected yet.
        }

        if (net.getOut().isAppendClosed()) {
            abort("Net closed");
        } else {
            flushToNext(http.sendBody, net.getOut());
            net.startSending();
        }

    }

    protected void outClosed(HttpChannel http) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.outClosed(http);
            return;
        }
        // TODO: move it ?
        if (sendBodyState.isContentDelimited() && !http.error) {
            if (!sendBodyState.chunked &&
                    sendBodyState.remaining - http.getOut().available() > 0) {
                http.abort("CLOSE CALLED WITHOUT FULL LEN");
            }
        }

    }

    @Override
    public void handleFlushed(IOChannel net) throws IOException {
        if (switchedProtocol != null) {
            switchedProtocol.handleFlushed(net);
            return;
        }
        if (activeHttp != null) {
            activeHttp.flushLock.signal(this);
            activeHttp.handleFlushed(this);
            if (activeHttp.sendBody.isClosedAndEmpty()) {
                activeHttp.handleEndSent();
            }
        }
    }

    private void flushToNext(IOBuffer body, IOBuffer out) throws IOException {

        synchronized (this) {
            // TODO: better head support
            if (sendBodyState.noBody) {
                for (int i = 0; i < body.getBufferCount(); i++) {
                    Object bc = body.peekBucket(i);
                    if (bc instanceof BBucket) {
                        ((BBucket) bc).release();
                    }
                }
                body.clear();
                return;
            }

            // TODO: only send < remainingWrite, if buffer
            // keeps changing after startWrite() is called (shouldn't)

            if (sendBodyState.chunked) {
                sendChunked(sendBodyState, body, out);
            } else if (sendBodyState.contentLength >= 0) {
                // content-length based
                sendContentLen(sendBodyState, body, out);
            } else {
                sendCloseDelimited(body, out);
            }
        }
    }

    private void sendCloseDelimited(IOBuffer body, IOBuffer out) throws IOException {
        // Close delimitation
        while (true) {
            Object bc = body.popFirst();
            if (bc == null) {
                break;
            }
            out.queue(bc);
        }
        if (body.isClosedAndEmpty()) {
            out.close(); // no content-delimitation
        }
    }

    /**
     * Convert the request to bytes, ready to send.
     */
    public static void serialize(HttpRequest req, IOBuffer rawSendBuffers2) throws IOException {
        rawSendBuffers2.append(req.method());
        rawSendBuffers2.append(BBuffer.SP);

        // TODO: encode or use decoded
        rawSendBuffers2.append(req.requestURI());
        if (req.queryString().length() > 0) {
            rawSendBuffers2.append("?");
            rawSendBuffers2.append(req.queryString());
        }

        rawSendBuffers2.append(BBuffer.SP);
        rawSendBuffers2.append(req.protocol());
        rawSendBuffers2.append(BBuffer.CRLF_BYTES);

        serializeHeaders(req.getMimeHeaders(), rawSendBuffers2);
    }

    /**
     * Convert the response to bytes, ready to send.
     */
    public static void serialize(HttpResponse res, IOBuffer rawSendBuffers2) throws IOException {

        rawSendBuffers2.append(res.protocol()).append(' ');
        String status = Integer.toString(res.getStatus());
        rawSendBuffers2.append(status).append(' ');
        if (res.getMessageBuffer().length() > 0) {
            rawSendBuffers2.append(res.getMessage());
        } else {
            rawSendBuffers2
                .append(res.getMessage(res.getStatus()));
        }
        rawSendBuffers2.append(BBuffer.CRLF_BYTES);
        // Headers
        serializeHeaders(res.getMimeHeaders(), rawSendBuffers2);
    }

    public static void serializeHeaders(MultiMap mimeHeaders, IOBuffer rawSendBuffers2) throws IOException {
        for (int i = 0; i < mimeHeaders.size(); i++) {
            CBuffer name = mimeHeaders.getName(i);
            CBuffer value = mimeHeaders.getValue(i);
            if (name.length() == 0 || value.length() == 0) {
                continue;
            }
            rawSendBuffers2.append(name);
            rawSendBuffers2.append(Http11Connection.COLON);
            rawSendBuffers2.append(value);
            rawSendBuffers2.append(BBuffer.CRLF_BYTES);
        }
        rawSendBuffers2.append(BBuffer.CRLF_BYTES);
    }

    private boolean sendContentLen(BodyState bodys, IOBuffer body, IOBuffer out) throws IOException {
        while (true) {
            BBucket bucket = body.peekFirst();
            if (bucket == null) {
                break;
            }
            int len = bucket.remaining();
            if (len <= bodys.remaining) {
                bodys.remaining -= len;
                bucket = body.popFirst();
                out.queue(bucket);
            } else {
                // Write over the end of the buffer !
                log.severe("write more than Content-Length");
                len = (int) bodys.remaining;
                // data between position and limit
                bucket = body.popLen((int) bodys.remaining);
                out.queue(bucket);
                while (bucket != null) {
                    bucket = body.popFirst();
                    if (bucket != null) {
                        bucket.release();
                    }
                }

                // forced close
                //close();
                bodys.remaining = 0;
                return true;
            }
        }
        if (body.isClosedAndEmpty()) {
            //http.rawSendBuffers.queue(IOBrigade.MARK);
            if (bodys.remaining > 0) {
                closeStreamOnEnd("sent more than content-length");
                log.severe("Content-Length > body");
            }
            return true;
        }
        return false;
    }

    private boolean sendChunked(BodyState bodys, IOBuffer body, IOBuffer out) throws IOException {
        int len = body.available();

        if (len > 0) {
            ByteBuffer sendChunkBuffer = chunk.prepareChunkHeader(len);
            bodys.remaining = len;
            out.queue(sendChunkBuffer);
            while (bodys.remaining > 0) {
                BBucket bc = body.popFirst();
                bodys.remaining -= bc.remaining();
                out.queue(bc);
            }
        }

        if (body.isClosedAndEmpty()) {
            synchronized(this) {
                if (!endSent) {
                    out.append(chunk.endChunk());
                    endSent = true;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    // used for chunk parsing/end
    ChunkState chunk = new ChunkState();
    ChunkState rchunk = new ChunkState();
    static final int NEED_MORE = -1;
    static final int ERROR = -4;
    static final int DONE = -5;

    static class ChunkState {
        static byte[] END_CHUNK_BYTES = {
            (byte) '\r', (byte) '\n',
            (byte) '0',
            (byte) '\r', (byte) '\n',
            (byte) '\r', (byte) '\n'};

        int partialChunkLen;
        boolean readDigit = false;
        boolean trailer = false;
        protected boolean needChunkCrlf = false;

        // Buffer used for chunk length conversion.
        protected byte[] sendChunkLength = new byte[10];

        /** End chunk marker - will include chunked end or empty */
        protected BBuffer endSendBuffer = BBuffer.wrapper();

        public ChunkState() {
            sendChunkLength[8] = (byte) '\r';
            sendChunkLength[9] = (byte) '\n';
        }

        void recycle() {
            partialChunkLen = 0;
            readDigit = false;
            trailer = false;
            needChunkCrlf = false;
            endSendBuffer.recycle();
        }

        /**
         * Parse the header of a chunk.
         * A chunk header can look like
         * A10CRLF
         * F23;chunk-extension to be ignoredCRLF
         * The letters before CRLF but after the trailer mark, must be valid hex digits,
         * we should not parse F23IAMGONNAMESSTHISUP34CRLF as a valid header
         * according to spec
         */
        int parseChunkHeader(IOBuffer buffer) throws IOException {
            if (buffer.peekFirst() == null) {
                return NEED_MORE;
            }
            if (needChunkCrlf) {
                // TODO: Trailing headers
                int c = buffer.read();
                if (c == BBuffer.CR) {
                    if (buffer.peekFirst() == null) {
                        return NEED_MORE;
                    }
                    c = buffer.read();
                }
                if (c == BBuffer.LF) {
                    needChunkCrlf = false;
                } else {
                    System.err.println("Bad CRLF " + c);
                    return ERROR;
                }
            }

            while (true) {
                if (buffer.peekFirst() == null) {
                    return NEED_MORE;
                }
                int c = buffer.read();

                if (c == BBuffer.CR) {
                    continue;
                } else if (c == BBuffer.LF) {
                    break;
                } else if (c == HttpChannel.SEMI_COLON) {
                    trailer = true;
                } else if (c == BBuffer.SP) {
                    // ignore
                } else if (trailer) {
                    // ignore
                } else {
                    //don't read data after the trailer
                    if (Hex.DEC[c] != -1) {
                        readDigit = true;
                        partialChunkLen *= 16;
                        partialChunkLen += Hex.DEC[c];
                    } else {
                        //we shouldn't allow invalid, non hex characters
                        //in the chunked header
                        log.info("Chunk parsing error1 " + c + " " + buffer);
                        //http.abort("Chunk error");
                        return ERROR;
                    }
                }
            }

            if (!readDigit) {
                log.info("Chunk parsing error2 " + buffer);
                return ERROR;
            }

            needChunkCrlf = true;  // next time I need to parse CRLF
            int result = partialChunkLen;
            partialChunkLen = 0;
            trailer = false;
            readDigit = false;
            return result;
        }

        ByteBuffer prepareChunkHeader(int current) {
            int pos = 7; // 8, 9 are CRLF
            while (current > 0) {
                int digit = current % 16;
                current = current / 16;
                sendChunkLength[pos--] = Hex.HEX[digit];
            }
            if (needChunkCrlf) {
                sendChunkLength[pos--] = (byte) '\n';
                sendChunkLength[pos--] = (byte) '\r';
            } else {
                needChunkCrlf = true;
            }
            // TODO: pool - this may stay in the queue while we flush more
            ByteBuffer chunkBB = ByteBuffer.allocate(16);
            chunkBB.put(sendChunkLength, pos + 1, 9 - pos);
            chunkBB.flip();
            return chunkBB;
        }

        public BBuffer endChunk() {
            if (! needChunkCrlf) {
                endSendBuffer.setBytes(END_CHUNK_BYTES, 2,
                        END_CHUNK_BYTES.length - 2); // CRLF
            } else { // 0
                endSendBuffer.setBytes(END_CHUNK_BYTES, 0,
                        END_CHUNK_BYTES.length);
            }
            return endSendBuffer;
        }
    }

    static class BodyState {
        /** response: HEAD or  1xx, 204, 304 status
         *  req: missing content-length or transfer-encoding
         */
        protected boolean noBody = false;
        protected boolean chunked = false;
        protected long contentLength = -1; // C-L header
        /** Bytes remaining in the current chunk or body ( if CL ) */
        protected long remaining = 0; // both chunked and C-L

        public void recycle() {
            chunked = false;
            remaining = 0;
            contentLength = -1;
            noBody = false;
        }
        public boolean isContentDelimited() {
            return chunked || contentLength >= 0;
        }

    }

    public String toString() {
        if (switchedProtocol != null) {
            return switchedProtocol.toString();
        }

        return (serverMode ? "SR " : "CL ") +
        (keepAlive() ? " KA " : "") +
        (headersReceived ? " HEAD " : "") +
        (bodyReceived ? " BODY " : "")
        ;
    }

    @Override
    public void handleConnected(IOChannel net) throws IOException {
        HttpChannel httpCh = activeHttp;

        if (!net.isOpen()) {
            httpCh.abort(net.lastException());
            return;
        }

        boolean ssl = httpCh.getRequest().isSecure();
        if (ssl) {
            String[] hostPort = httpCh.getTarget().split(":");

            IOChannel ch1 = httpConnector.sslProvider.channel(net,
                    hostPort[0], Integer.parseInt(hostPort[1]));
            //net.setHead(ch1);
            net = ch1;
        }
        if (httpConnector.debugHttp) {
            net = DumpChannel.wrap("Http-Client-", net);
        }

        setSink(net);

        sendRequest(httpCh);
    }

}


text:
internal static partial class Interop
{
    internal static partial class Http
    {
        // Enum for constants defined for the enum CURLcode in curl.h
        internal enum CURLcode
        {
            CURLE_OK = 0,
            CURLE_UNSUPPORTED_PROTOCOL  =  1,
            CURLE_FAILED_INIT = 2,
            CURLE_NOT_BUILT_IN = 4,
            CURLE_COULDNT_RESOLVE_HOST  =  6,
            CURLE_OUT_OF_MEMORY = 27,
            CURLE_ABORTED_BY_CALLBACK = 42,
            CURLE_UNKNOWN_OPTION = 48,
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { FragmentOpcodeCompiler } from './fragment_opcode';
import { FragmentCompiler } from './fragment';
import { HydrationOpcodeCompiler } from './hydration_opcode';
import { HydrationCompiler } from './hydration';
import { ASTWalker } from './ast_walker';

export function TemplateCompiler() {
  this.fragmentOpcodeCompiler = new FragmentOpcodeCompiler();
  this.fragmentCompiler = new FragmentCompiler();
  this.hydrationOpcodeCompiler = new HydrationOpcodeCompiler();
  this.hydrationCompiler = new HydrationCompiler();
  this.templates = [];
  this.childTemplates = [];
}

TemplateCompiler.prototype.compile = function(ast) {
  var astWalker = new ASTWalker(this);
  astWalker.visit(ast);
  return this.templates.pop();
};

TemplateCompiler.prototype.startTemplate = function(program, childTemplateCount) {
  this.fragmentOpcodeCompiler.startTemplate(program, childTemplateCount);
  this.hydrationOpcodeCompiler.startTemplate(program, childTemplateCount);

  this.childTemplates.length = 0;
  while(childTemplateCount--) {
    this.childTemplates.push(this.templates.pop());
  }
};

TemplateCompiler.prototype.endTemplate = function(program) {
  this.fragmentOpcodeCompiler.endTemplate(program);
  this.hydrationOpcodeCompiler.endTemplate(program);

  // function build(dom) { return fragment; }
  var fragmentProgram = this.fragmentCompiler.compile(
    this.fragmentOpcodeCompiler.opcodes
  );

  // function hydrate(fragment) { return mustaches; }
  var hydrationProgram = this.hydrationCompiler.compile(
    this.hydrationOpcodeCompiler.opcodes
  );

  var childTemplateVars = "";
  for (var i=0, l=this.childTemplates.length; i<l; i++) {
    childTemplateVars +=   '  var child' + i + '=' + this.childTemplates[i] + ';\n';
  }

  var template =
    '(function (){\n' +
      childTemplateVars +
      fragmentProgram +
    'var cachedFragment = null;\n' +
    'return function template(context, options) {\n' +
    '  if (cachedFragment === null) {\n' +
    '    cachedFragment = build(dom);\n' +
    '  }\n' +
    '  var fragment = cachedFragment.cloneNode(true);\n' +
    '  var helpers = options && options.helpers || {};\n' +
       hydrationProgram +
    '  return fragment;\n' +
    '};\n' +
    '}())';

  this.templates.push(template);
};

TemplateCompiler.prototype.openElement = function(element, i, l, c) {
  this.fragmentOpcodeCompiler.openElement(element, i, l, c);
  this.hydrationOpcodeCompiler.openElement(element, i, l, c);
};

TemplateCompiler.prototype.closeElement = function(element, i, l) {
  this.fragmentOpcodeCompiler.closeElement(element, i, l);
  this.hydrationOpcodeCompiler.closeElement(element, i, l);
};

TemplateCompiler.prototype.component = function(component, i, l) {
  this.fragmentOpcodeCompiler.component(component, i, l);
  this.hydrationOpcodeCompiler.component(component, i, l);
};

TemplateCompiler.prototype.block = function(block, i, l) {
  this.fragmentOpcodeCompiler.block(block, i, l);
  this.hydrationOpcodeCompiler.block(block, i, l);
};

TemplateCompiler.prototype.text = function(string, i, l) {
  this.fragmentOpcodeCompiler.text(string, i, l);
  this.hydrationOpcodeCompiler.text(string, i, l);
};

TemplateCompiler.prototype.node = function (node, i, l) {
  this.fragmentOpcodeCompiler.node(node, i, l);
  this.hydrationOpcodeCompiler.node(node, i, l);
};


text:
@interface PodsDummy_Pods_CNMLib_Example : NSObject
@end
@implementation PodsDummy_Pods_CNMLib_Example
@end


text:
from tornado.escape import url_escape, json_encode

from qiita_pet.handlers.base_handlers import BaseHandler
from qiita_core.qiita_settings import qiita_config, r_client
from qiita_core.util import execute_as_transaction
from qiita_core.exceptions import (IncorrectPasswordError, IncorrectEmailError,
                                   UnverifiedEmailError)
from qiita_db.util import send_email
from qiita_db.user import User
from qiita_db.exceptions import (QiitaDBUnknownIDError, QiitaDBDuplicateError,
                                 QiitaDBError)
# login code modified from https://gist.github.com/guillaumevincent/4771570

class AuthCreateHandler(BaseHandler):
    """User Creation"""
    def get(self):
        try:
            error_message = self.get_argument("error")
        # Tornado can raise an Exception directly, not a defined type
        except Exception:
            error_message = ""
        self.render("create_user.html", error=error_message)

    @execute_as_transaction
    def post(self):
        username = self.get_argument("email", "").strip().lower()
        password = self.get_argument("newpass", "")
        info = {}
        for info_column in ("name", "affiliation", "address", "phone"):
            hold = self.get_argument(info_column, None)
            if hold:
                info[info_column] = hold

        created = False
        try:
            created = User.create(username, password, info)
        except QiitaDBDuplicateError:
            msg = "Email already registered as a user"

        if created:
            info = created.info
            try:
                # qiita_config.base_url doesn't have a / at the end, but the
                # qiita_config.portal_dir has it at the beginning but not at
                # the end. This constructs the correct URL
                url = qiita_config.base_url + qiita_config.portal_dir
                send_email(username, "QIITA: Verify Email Address", "Please "
                           "click the following link to verify email address: "
                           "%s/auth/verify/%s?email=%s\n\nBy clicking you are "
                           "accepting our term and conditions: "
                           "%s/iframe/?iframe=qiita-terms"
                           % (url, info['user_verify_code'],
                              url_escape(username), url))
            except Exception:
                msg = ("Unable to send verification email. Please contact the "
                       "qiita developers at qiita-help@gmail.com")
                self.redirect(u"%s/?level=danger&message=%s"
                              % (qiita_config.portal_dir, url_escape(msg)))
                return

            msg = ("
User Successfully Created

Your Qiita account "
                   "has been successfully created. An email has been sent to "
                   "the email address you provided. This email contains "
                   "instructions on how to activate your account.
"
                   "
If you don't receive your activation email within a "
                   "couple of minutes, check your spam folder. If you still "
                   "don't see it, send us an email at qiita.help@gmail.com"
                   ".
")
            self.redirect(u"%s/?level=success&message=%s" %
                          (qiita_config.portal_dir, url_escape(msg)))
        else:
            error_msg = u"?error=" + url_escape(msg)
            self.redirect(u"%s/auth/create/%s"
                          % (qiita_config.portal_dir, error_msg))

class AuthVerifyHandler(BaseHandler):
    def get(self, code):
        email = self.get_argument("email").strip().lower()

        code_is_valid = False
        msg = "This code is not valid."

        # an exception is raised if the 'code type' is not available, otherwise
        # the method determines the validity of the code
        try:
            code_is_valid = User.verify_code(email, code, "create")
        except QiitaDBError:
            msg = "This user has already created an account."

        if code_is_valid:
            msg = "Successfully verified user. You are now free to log in."
            color = "black"
            r_client.zadd('qiita-usernames', {email: 0})
        else:
            color = "red"

        self.render("user_verified.html", msg=msg, color=color,
                    email=self.get_argument("email").strip())

class AuthLoginHandler(BaseHandler):
    """user login, no page necessary"""
    def get(self):
        self.redirect("%s/" % qiita_config.portal_dir)

    @execute_as_transaction
    def post(self):
        username = self.get_argument("username", "").strip().lower()
        passwd = self.get_argument("password", "")
        nextpage = self.get_argument("next", None)
        if nextpage is None:
            if "auth/" not in self.request.headers['Referer']:
                nextpage = self.request.headers['Referer']
            else:
                nextpage = "%s/" % qiita_config.portal_dir

        msg = ""
        # check the user level
        try:
            if User(username).level == "unverified":
                # email not verified so dont log in
                msg = ("Email not verified. Please check your email and click "
                       "the verify link. You may need to check your spam "
                       "folder to find the email.
If a verification email"
                       " has not arrived in 15 minutes, please email qiita.help@gmail.com")
        except QiitaDBUnknownIDError:
            msg = "Unknown user"
        except RuntimeError:
            # means DB not available, so set maintenance mode and failover
            r_client.set("maintenance", "Database connection unavailable, "
                         "please try again later.")
            self.redirect("%s/" % qiita_config.portal_dir)
            return

        # Check the login information
        login = None
        try:
            login = User.login(username, passwd)
        except IncorrectEmailError:
            msg = "Unknown user"
        except IncorrectPasswordError:
            msg = "Incorrect password"
        except UnverifiedEmailError:
            msg = "You have not verified your email address"

        if login:
            # everything good so log in
            self.set_current_user(username)
            self.redirect(nextpage)
        else:
            self.render("index.html", message=msg, level='danger')

    def set_current_user(self, user):
        if user:
            self.set_secure_cookie("user", json_encode(user))
        else:
            self.clear_cookie("user")

class AuthLogoutHandler(BaseHandler):
    """Logout handler, no page necessary"""
    def get(self):
        self.clear_cookie("user")
        self.redirect("%s/" % qiita_config.portal_dir)


text:
(function() {
  var AbstractParser, ParsePHP, util, which, _,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  _ = require("lodash");

  util = require("util");

  which = require("which");

  AbstractParser = require("./abstract");

  require('shelljs/global');

  module.exports.PHP = ParsePHP = (function(_super) {
    __extends(ParsePHP, _super);

    ParsePHP.prototype.varToken = null;

    ParsePHP.prototype.ignoreTokens = [];

    function ParsePHP() {
      var getIgnore, ignore;
      this.weigth = 1;
      this.varToken = parseInt(exec("php -r \"echo T_VARIABLE;\"", {
        silent: true
      }).output);
      ignore = "T_INLINE_HTML,T_COMMENT,T_DOC_COMMENT,T_OPEN_TAG,T_OPEN_TAG_WITH_ECHO,T_CLOSE_TAG,T_WHITESPACE,T_USE,T_NS_SEPARATOR";
      getIgnore = util.format("php -r \"echo json_encode([%s]);\"", ignore);
      this.ignoreTokens = JSON.parse(exec(getIgnore, {
        silent: true
      }).output);
    }

    ParsePHP.prototype.parse = function(file, content, fuzzy) {
      var s, stack, tokens;
      stack = [];
      s = util.format("php -r \"echo json_encode(token_get_all(file_get_contents('%s')));\"", file);
      tokens = JSON.parse(exec(s, {
        silent: true
      }).output);
      _.forEach(tokens, (function(_this) {
        return function(token) {
          if (_.isArray(token)) {
            if (fuzzy && token[0] === _this.varToken) {
              token[1] = "__variable__";
            }
            if (!_this.ignores(token[0])) {
              return stack.push({
                type: token[0],
                value: token[1],
                line: token[2]
              });
            }
          }
        };
      })(this));
      return stack;
    };

    ParsePHP.prototype.ignores = function(token) {
      return __indexOf.call(this.ignoreTokens, token) >= 0;
    };

    ParsePHP.prototype.registers = function(mime, extension) {
      return !!which.sync('php') && (extension === 'php' || extension === 'php3' || extension === 'php4' || extension === 'php5');
    };

    return ParsePHP;

  })(AbstractParser);

}).call(this);


text:
class PIXINeutrinoContext {

	constructor(renderer) {
		var gl = renderer.gl;

		this.renderer = renderer;
		this.neutrino = new NeutrinoParticles();
		this.effectsBasePath = "";
		this.texturesBasePath = "";
		this.trimmedExtensionLookupFirst = true;

		if (!(renderer instanceof PIXI.CanvasRenderer)) {
			this.materials = new PIXINeutrinoMaterials(this);
		}
	}

	initializeNoise(path, success, fail) {
		this.neutrino.initializeNoise(path, success, fail);
	}

	loadEffect(path, success, fail) {
		this.neutrino.loadEffect(path, success, fail);
	}
}


text:
package id3v1

const (
	// TagSize is the size in bytes of an id3v1 tag
	TagSize = 128
)

var (
	//TagCode is the byte representation of "TAG"
	TagCode = []byte{84, 65, 71}
)

// Tag contains the various information stored in a id3 v1 tag.
// Strings are either space or zero-padded.
// Unset string entries are filled using an empty string. ID3v1 is 128 bytes long
type Tag struct {
	Title  [30]byte
	Artist [30]byte
	Album  [30]byte
	Year   [4]byte
	// The track number is stored in the last two bytes of the comment field.
	// If the comment is 29 or 30 characters long, no track number can be stored.
	Comment  [30]byte
	ZeroByte byte
	Track    byte
	Genre    byte
}


text:
package tests

// +stateify savable
type benchStruct struct {
	B *benchStruct // Must be exported for gob.
}

func (b *benchStruct) afterLoad() {
	// Do nothing, just force scheduling.
}


text:
namespace aura {
class Env;
}
#endif

#if defined(USE_OZONE)
#include "ui/ozone/buildflags.h"  // nogncheck
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif

namespace base {
class CommandLine;
class HighResolutionTimerManager;
class MemoryPressureMonitor;
class SingleThreadTaskRunner;
class SystemMonitor;
}  // namespace base

namespace data_decoder {
class ServiceProvider;
}

namespace gpu {
class GpuChannelEstablishFactory;
}

namespace media {
class AudioManager;
class AudioSystem;
#if BUILDFLAG(IS_WIN)
class SystemMessageWindowWin;
#elif (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_UDEV)
class DeviceMonitorLinux;
#endif
class UserInputMonitor;
#if BUILDFLAG(IS_MAC)
class DeviceMonitorMac;
#endif
}  // namespace media

namespace midi {
class MidiService;
}  // namespace midi

namespace mojo {
namespace core {
class ScopedIPCSupport;
}  // namespace core
}  // namespace mojo

namespace net {
class NetworkChangeNotifier;
}  // namespace net

namespace viz {
class CompositingModeReporterImpl;
class HostFrameSinkManager;
}  // namespace viz

namespace content {
class BrowserMainParts;
class BrowserOnlineStateObserver;
class BrowserThreadImpl;
class MediaKeysListenerManagerImpl;
class MediaStreamManager;
class SaveFileManager;
class ScreenlockMonitor;
class SmsProvider;
class SpeechRecognitionManagerImpl;
class StartupTaskRunner;
class TracingControllerImpl;
struct MainFunctionParams;

namespace responsiveness {
class Watcher;
}  // namespace responsiveness

#if BUILDFLAG(IS_ANDROID)
class ScreenOrientationDelegate;
#endif

// Implements the main browser loop stages called from BrowserMainRunner.
// See comments in browser_main_parts.h for additional info.
class CONTENT_EXPORT BrowserMainLoop {
 public:
  // Returns the current instance. This is used to get access to the getters
  // that return objects which are owned by this class.
  static BrowserMainLoop* GetInstance();

  static media::AudioManager* GetAudioManager();

  // The ThreadPoolInstance must exist but not to be started when building
  // BrowserMainLoop.
  explicit BrowserMainLoop(
      MainFunctionParams parameters,
      std::unique_ptr<base::ThreadPoolInstance::ScopedExecutionFence> fence);

  BrowserMainLoop(const BrowserMainLoop&) = delete;
  BrowserMainLoop& operator=(const BrowserMainLoop&) = delete;

  virtual ~BrowserMainLoop();

  void Init();

  // Return value is exit status. Anything other than RESULT_CODE_NORMAL_EXIT
  // is considered an error.
  int EarlyInitialization();

  // Initializes the toolkit. Returns whether the toolkit initialization was
  // successful or not.
  bool InitializeToolkit();

  void PreCreateMainMessageLoop();
  // Creates the main message loop, bringing APIs like
  // ThreadTaskRunnerHandle::Get() online.
  void CreateMainMessageLoop();
  void PostCreateMainMessageLoop();

  // Creates a "bare" message loop that is required to exit gracefully at the
  // early stage if the toolkit failed to initialise.
  void CreateMessageLoopForEarlyShutdown();

  // Create and start running the tasks we need to complete startup. Note that
  // this can be called more than once (currently only on Android) if we get a
  // request for synchronous startup while the tasks created by asynchronous
  // startup are still running. Completes tasks synchronously as part of this
  // method on non-Android platforms.
  void CreateStartupTasks();

  // Performs the default message loop run logic.
  void RunMainMessageLoop();

  // Performs the pre-shutdown steps.
  void PreShutdown();

  // Performs the shutdown sequence, starting with PostMainMessageLoopRun
  // through stopping threads to PostDestroyThreads.
  void ShutdownThreadsAndCleanUp();

  int GetResultCode() const { return result_code_; }

  // Needed by some embedders.
  void SetResultCode(int code) { result_code_ = code; }

  media::AudioManager* audio_manager() const;
  bool AudioServiceOutOfProcess() const;
  media::AudioSystem* audio_system() const { return audio_system_.get(); }
  MediaStreamManager* media_stream_manager() const {
    return media_stream_manager_.get();
  }
  media::UserInputMonitor* user_input_monitor() const {
    return user_input_monitor_.get();
  }
  MediaKeysListenerManagerImpl* media_keys_listener_manager() const {
    return media_keys_listener_manager_.get();
  }

#if BUILDFLAG(IS_CHROMEOS)
  // Only expose this on ChromeOS since it's only needed there. On Android this
  // be null if this process started in reduced mode.
  net::NetworkChangeNotifier* network_change_notifier() const {
    return network_change_notifier_.get();
  }
#endif

  midi::MidiService* midi_service() const { return midi_service_.get(); }

  // Returns the task runner for tasks that that are critical to producing a new
  // CompositorFrame on resize. On Mac this will be the task runner provided by
  // WindowResizeHelperMac, on other platforms it will just be the thread task
  // runner.
  scoped_refptr<base::SingleThreadTaskRunner> GetResizeTaskRunner();

  gpu::GpuChannelEstablishFactory* gpu_channel_establish_factory() const;

#if BUILDFLAG(IS_ANDROID)
  void SynchronouslyFlushStartupTasks();

  // |enabled| Whether or not CreateStartupTasks() posts any tasks. This is
  // useful because some javatests want to test native task posting without the
  // whole browser loaded. In that scenario tasks posted by CreateStartupTasks()
  // may crash if run.
  static void EnableStartupTasks(bool enabled);
#endif  // BUILDFLAG(IS_ANDROID)

#if !BUILDFLAG(IS_ANDROID)
  // TODO(fsamuel): We should find an object to own HostFrameSinkManager on all
  // platforms including Android. See http://crbug.com/732507.
  viz::HostFrameSinkManager* host_frame_sink_manager() const {
    return host_frame_sink_manager_.get();
  }
#endif

  // Binds a receiver to the singleton CompositingModeReporter.
  void GetCompositingModeReporter(
      mojo::PendingReceiver<viz::mojom::CompositingModeReporter> receiver);

#if BUILDFLAG(IS_MAC)
  media::DeviceMonitorMac* device_monitor_mac() const {
    return device_monitor_mac_.get();
  }
#endif

  SmsProvider* GetSmsProvider();
  void SetSmsProviderForTesting(std::unique_ptr<SmsProvider>);

  BrowserMainParts* parts() { return parts_.get(); }

 private:
  FRIEND_TEST_ALL_PREFIXES(BrowserMainLoopTest, CreateThreadsInSingleProcess);
  FRIEND_TEST_ALL_PREFIXES(
      BrowserMainLoopTest,
      PostTaskToIOThreadBeforeThreadCreationDoesNotRunTask);

  // Called just before creating the threads
  int PreCreateThreads();

  // Create all secondary threads.
  int CreateThreads();

  // Called just after creating the threads.
  int PostCreateThreads();
  void PostCreateThreadsImpl();

  int PreMainMessageLoopRun();

  // One last opportunity to intercept the upcoming MainMessageLoopRun (or
  // before yielding to the native loop on Android). Returns false iff the run
  // should proceed after this call.
  using ProceedWithMainMessageLoopRun =
      base::StrongAlias<class ProceedWithMainMessageLoopRunTag, bool>;
  ProceedWithMainMessageLoopRun InterceptMainMessageLoopRun();

  void MainMessageLoopRun();

  void InitializeMojo();

  void InitializeAudio();

  bool UsingInProcessGpu() const;

  void InitializeMemoryManagementComponent();

  // Quick reference for initialization order:
  // Constructor
  // Init()
  // EarlyInitialization()
  // InitializeToolkit()
  // PreCreateMainMessageLoop()
  // CreateMainMessageLoop()
  // PostCreateMainMessageLoop()
  // CreateStartupTasks()
  //   PreCreateThreads()
  //     InitializeMemoryManagementComponent()
  //   CreateThreads()
  //   PostCreateThreads()
  //     PostCreateThreadsImpl()
  //       InitializeMojo()
  //       InitializeAudio()
  // PreMainMessageLoopRun()
  // MainMessageLoopRun()
  //   OnFirstIdle()

  // Members initialized on construction ---------------------------------------
  MainFunctionParams parameters_;
  const base::CommandLine& parsed_command_line_;
  int result_code_;
  bool created_threads_;  // True if the non-UI threads were created.
  // //content must be initialized single-threaded until
  // BrowserMainLoop::CreateThreads() as things initialized before it require an
  // initialize-once happens-before relationship with all eventual content tasks
  // running on other threads. This ScopedExecutionFence ensures that no tasks
  // posted to ThreadPool gets to run before CreateThreads(); satisfying this
  // requirement even though the ThreadPoolInstance is created and started
  // before content is entered.
  std::unique_ptr<base::ThreadPoolInstance::ScopedExecutionFence>
      scoped_execution_fence_;

  // BEST_EFFORT tasks are not allowed to run between //content initialization
  // and startup completion.
  //
  // TODO(fdoray): Move this to a more elaborate class that prevents BEST_EFFORT
  // tasks from running when resources are needed to respond to user actions.
  absl::optional<base::ThreadPoolInstance::ScopedBestEffortExecutionFence>
      scoped_best_effort_execution_fence_;

  // Members initialized in |Init()| -------------------------------------------
  std::unique_ptr<mojo::core::ScopedIPCSupport> mojo_ipc_support_;

  // Members initialized in |InitializeToolkit()| ------------------------------
#if defined(USE_AURA)
  std::unique_ptr<aura::Env> env_;
#endif

  // Members initialized in |PostCreateMainMessageLoop()| ----------------------
  std::unique_ptr<base::SystemMonitor> system_monitor_;
  std::unique_ptr<base::HighResolutionTimerManager> hi_res_timer_manager_;
  std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier_;
  std::unique_ptr<ScreenlockMonitor> screenlock_monitor_;
  // Per-process listener for online state changes.
  std::unique_ptr<BrowserOnlineStateObserver> online_state_observer_;
#if BUILDFLAG(IS_ANDROID)
  // Android implementation of ScreenOrientationDelegate
  std::unique_ptr<ScreenOrientationDelegate> screen_orientation_delegate_;
#endif

  // Destroy |parts_| before above members (except the ones that are explicitly
  // reset() on shutdown) but after |main_thread_| and services below.
  std::unique_ptr<BrowserMainParts> parts_;

  // Members initialized in |CreateMainMessageLoop()| --------------------------
  // This must get destroyed before other threads that are created in |parts_|.
  std::unique_ptr<BrowserThreadImpl> main_thread_;

  // Members initialized in |CreateStartupTasks()| -----------------------------
  std::unique_ptr<StartupTaskRunner> startup_task_runner_;

  // Members initialized in |PreCreateThreads()| -------------------------------
  // Torn down in ShutdownThreadsAndCleanUp.
  std::unique_ptr<base::MemoryPressureMonitor> memory_pressure_monitor_;

  // Members initialized in |CreateThreads()| ----------------------------------
  std::unique_ptr<BrowserProcessIOThread> io_thread_;

  // BEGIN Members initialized in |PostCreateThreads()| ------------------------
  // ***************************************************************************
  std::unique_ptr<MediaKeysListenerManagerImpl> media_keys_listener_manager_;

  // |user_input_monitor_| has to outlive |audio_manager_|, so declared first.
  std::unique_ptr<media::UserInputMonitor> user_input_monitor_;

  // Support for out-of-process Data Decoder.
  std::unique_ptr<data_decoder::ServiceProvider> data_decoder_service_provider_;

  // |audio_manager_| is not instantiated when the audio service runs out of
  // process.
  std::unique_ptr<media::AudioManager> audio_manager_;

  std::unique_ptr<media::AudioSystem> audio_system_;

  std::unique_ptr<midi::MidiService> midi_service_;

  // Must be deleted on the IO thread.
  std::unique_ptr<SpeechRecognitionManagerImpl> speech_recognition_manager_;

#if BUILDFLAG(IS_WIN)
  std::unique_ptr<media::SystemMessageWindowWin> system_message_window_;
#elif (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(USE_UDEV)
  std::unique_ptr<media::DeviceMonitorLinux> device_monitor_linux_;
#elif BUILDFLAG(IS_MAC)
  std::unique_ptr<media::DeviceMonitorMac> device_monitor_mac_;
#endif

  std::unique_ptr<MediaStreamManager> media_stream_manager_;
  scoped_refptr<SaveFileManager> save_file_manager_;
  std::unique_ptr<content::TracingControllerImpl> tracing_controller_;
#if !BUILDFLAG(IS_ANDROID)
  std::unique_ptr<viz::HostFrameSinkManager> host_frame_sink_manager_;

  // Reports on the compositing mode in the system for clients to submit
  // resources of the right type. This is null if the display compositor
  // is not in this process.
  std::unique_ptr<viz::CompositingModeReporterImpl>
      compositing_mode_reporter_impl_;
#endif
  // ***************************************************************************
  // END Members initialized in |PostCreateThreads()| --------------------------

  // Members initialized in |PreMainMessageLoopRun()| --------------------------
  scoped_refptr<responsiveness::Watcher> responsiveness_watcher_;

  // Members not associated with a specific phase.
  std::unique_ptr<SmsProvider> sms_provider_;

  // DO NOT add members here. Add them to the right categories above.
};

}  // namespace content

#endif  // CONTENT_BROWSER_BROWSER_MAIN_LOOP_H_


text:
using Test
using DandelionWebSockets: masking!

@testset "Masking                " begin
    mask = b"\x37\xfa\x21\x3d"
    masking_test_examples = [
        # The first element in each tuple is the input, and the second element
        # is the expected masked output, when using the mask defined here.
        (b"Hello", b"\x7f\x9f\x4d\x51\x58"),
        (b"Hel",   b"\x7f\x9f\x4d"),
    ]

    @testset "Masking a payload" begin
        # Requirement
        # @5_3-3 Mask operation

        for example in masking_test_examples
            masked_input = copy(example[1])
            masking!(masked_input, mask)
            @test masked_input == example[2]
        end
    end

    @testset "Masking is its own inverse" begin
        # Requirement
        # @5_3-3 Mask operation

        for example in masking_test_examples
            masked_input = copy(example[2])
            masking!(masked_input, mask)
            @test masked_input == example[1]
        end
    end

    @testset "The mask bit is set for masked frames" begin
        # Requirement
        # @5_3-1

        frame = Frame(true, false, false, false, OPCODE_TEXT, true, 5, 0, b"\x01\x02\x03\x04", b"\x7f\x9f\x4d\x51\x58")
        s = IOBuffer()

        # Mark the beginning of the buffer...
        mark(s)
        write(s, frame)

        # ... so that we can reset it and read it all back
        reset(s)
        readframe = read(s, Frame)
        @test readframe.ismasked
    end
end


text:
'use strict';

exports.config = {
  framework: 'jasmine2',
  baseUrl: process.env.APP_URL || 'http://localhost:3000',
  capabilities: {
    browserName: 'chrome'
  }
};


text:
package org.zenframework.easyservices.resource.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zenframework.easyservices.config.Config;
import org.zenframework.easyservices.config.WebappConfig;
import org.zenframework.easyservices.resource.Resource;
import org.zenframework.easyservices.resource.ResourceFactory;

public class ResourceFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(ResourceFilter.class);

    public static final String PARAM_RESOURCE_FACTORY = "resources";

    private ResourceFactory resourceFactory;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Config config = new WebappConfig(filterConfig);
        LOG.debug(config.toString(true));
        resourceFactory = config.getInstance(PARAM_RESOURCE_FACTORY);
    }

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (isApplicable(request)) {
            Resource resource = resourceFactory.getResource(getRelativePath((HttpServletRequest) request));
            if (resource.exists()) {
                response.setContentType(getContentType((HttpServletRequest) request));
                InputStream in = resource.openStream();
                OutputStream out = response.getOutputStream();
                try {
                    IOUtils.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(in, out);
                }
                return;
            }
        }

        chain.doFilter(request, response);

    }

    protected boolean isApplicable(ServletRequest request) {
        return true;
    }

    protected String getContentType(HttpServletRequest request) {
        return request.getServletContext().getMimeType(request.getRequestURI());
    }

    protected static String getRelativePath(HttpServletRequest req) {
        return req.getRequestURI().substring(req.getContextPath().length());
    }

}


text:
using DotNetBlog.Core.Entity;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace DotNetBlog.Core.Data.Mappings
{
    public sealed class WidgetMapping
    {
        public static void Map(EntityTypeBuilder<Widget> builder)
        {
            builder.ToTable("Widget");

            builder.HasKey(t => new { t.ID });

            builder.Property(t => t.Config).IsRequired();
        }
    }
}


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

<title>RosterItemProvider (Openfire 3.10.2 Javadoc)</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jivesoftware.openfire.roster

Interface RosterItemProvider

All Known Implementing Classes:

DefaultRosterItemProvider

public interface RosterItemProvider

Method Summary

Methods

Modifier and Type
Method and Description

RosterItem
createItem(String username,
          RosterItem item)

Creates a new roster item for the given user (optional operation).

void
deleteItem(String username,
          long rosterItemID)

Delete the roster item with the given itemJID for the user (optional operation).

int
getItemCount(String username)

Obtain a count of the number of roster items available for the given user.

Iterator<RosterItem>
getItems(String username)

Retrieve an iterator of RosterItems for the given user.

Iterator<String>
getUsernames(String jid)

Returns an iterator on the usernames whose roster includes the specified JID.

void
updateItem(String username,
          RosterItem item)

Update the roster item in storage with the information contained in the given item
 (optional operation).

Method Detail

createItem

RosterItem createItem(String username,
                    RosterItem item)
                      throws UserAlreadyExistsException

Creates a new roster item for the given user (optional operation).

 Important! The item passed as a parameter to this method is strictly a convenience
 for passing all of the data needed for a new roster item. The roster item returned from the
 method will be cached by Openfire. In some cases, the roster item passed in will be passed
 back out. However, if an implementation may return RosterItems as a separate class
 (for example, a RosterItem that directly accesses the backend storage, or one that is an
 object in an object database).

Parameters:

username - the username of the user/chatbot that owns the roster item.

item - the settings for the roster item to create.

Returns:

the new roster item.

Throws:

UserAlreadyExistsException - if a roster item with the username already exists.

updateItem

void updateItem(String username,
              RosterItem item)
                throws UserNotFoundException

Update the roster item in storage with the information contained in the given item
 (optional operation).

 If you don't want roster items edited through openfire, throw UnsupportedOperationException.

Parameters:

username - the username of the user/chatbot that owns the roster item

item - The roster item to update

Throws:

UserNotFoundException - If no entry could be found to update

deleteItem

void deleteItem(String username,
              long rosterItemID)

Delete the roster item with the given itemJID for the user (optional operation).

 If you don't want roster items deleted through openfire, throw
 UnsupportedOperationException.

Parameters:

username - the long ID of the user/chatbot that owns the roster item

rosterItemID - The roster item to delete

getUsernames

Iterator<String> getUsernames(String jid)

Returns an iterator on the usernames whose roster includes the specified JID.

Parameters:

jid - the jid that the rosters should include.

Returns:

an iterator on the usernames whose roster includes the specified JID.

getItemCount

int getItemCount(String username)

Obtain a count of the number of roster items available for the given user.

Parameters:

username - the username of the user/chatbot that owns the roster items

Returns:

The number of roster items available for the user

getItems

Iterator<RosterItem> getItems(String username)

Retrieve an iterator of RosterItems for the given user.

 This method will commonly be called when a user logs in. The data will be cached
 in memory when possible. However, some rosters may be very large so items may need
 to be retrieved from the provider more frequently than usual for provider data.

Parameters:

username - the username of the user/chatbot that owns the roster items

Returns:

An iterator of all RosterItems owned by the user

Overview

Package

Class

Tree

Deprecated

Index

Help

Openfire 3.10.2 Javadoc

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2003-2008 Jive Software.


text:
<?php

use Faker\Generator as Faker;

/* @var Illuminate\Database\Eloquent\Factory $factory */

$factory->define(App\SettingNumberRewrite::class, function (Faker $faker) {
    return [
        'pattern' => '	^(0\d+)$',
        'replacement' => '0\1',
        'description' => $faker->realText(10),
    ];
});


text:
from __future__ import absolute_import, unicode_literals, print_function, division

import re

from flask import url_for

from restfulgit.plumbing.retrieval import get_commit
from restfulgit.plumbing.converters import convert_commit as _plumbing_convert_commit
from restfulgit.porcelain.retrieval import get_repo_description, get_diff

GIT_STATUS_TO_NAME = {
    'M': 'modified',
    'A': 'added',
    'R': 'renamed',
    'D': 'removed',
}
SPLIT_PATCH_TXT_RE = re.compile(r'^\+\+\+\ b\/([^\n]*?)\n(@@.*?)(?=\n^diff|\n\Z)', re.M | re.S)

def convert_repo(repo_key):
    description = get_repo_description(repo_key)
    return {
        "name": repo_key,
        "full_name": repo_key,
        "description": description,
        "url": url_for('porcelain.get_repo_info', _external=True, repo_key=repo_key),
        "branches_url": (url_for('porcelain.get_branches', _external=True, repo_key=repo_key).rstrip('/') + '{/branch}'),
        "blobs_url": (url_for('plumbing.get_blob', _external=True, repo_key=repo_key, sha='').rstrip('/') + '{/sha}'),
        "commits_url": (url_for('porcelain.get_commit', _external=True, repo_key=repo_key, branch_or_tag_or_sha='').rstrip('/') + '{/sha}'),
        "git_commits_url": (url_for('plumbing.get_commit', _external=True, repo_key=repo_key, sha='').rstrip('/') + '{/sha}'),
        "git_refs_url": (url_for('plumbing.get_refs', _external=True, repo_key=repo_key).rstrip('/') + '{/sha}'),
        "git_tags_url": (url_for('plumbing.get_tag', _external=True, repo_key=repo_key, sha='').rstrip('/') + '{/sha}'),
        "tags_url": url_for('porcelain.get_tags', _external=True, repo_key=repo_key),
        "trees_url": (url_for('plumbing.get_tree', _external=True, repo_key=repo_key, sha='').rstrip('/') + '{/sha}'),
    }

def convert_branch_summary(repo_key, branch):
    url = url_for('porcelain.get_commit', _external=True, repo_key=repo_key, branch_or_tag_or_sha=unicode(branch.target))
    return {
        "name": branch.branch_name,
        "commit": {
            "sha": unicode(branch.target),
            "url": url,
        }
    }

def convert_branch_verbose(repo_key, repo, branch):
    url = url_for('porcelain.get_branch', _external=True, repo_key=repo_key, branch_name=branch.branch_name)
    return {
        "name": branch.branch_name,
        "commit": convert_commit(repo_key, repo, branch.peel()),
        "url": url,
        "_links": {
            # For some reason GitHub API for branch does the self-link like this
            # instead of with "url" as everywhere else.
            "self": url,
        }
    }

def _filename_to_patch_from(diff):
    if diff.patch is None:
        return {}
    matches = re.findall(SPLIT_PATCH_TXT_RE, diff.patch)
    return dict(m for m in matches)

def _convert_patch(repo_key, commit, patch, filename_to_patch):
    deleted = patch.status == 'D'
    commit_sha = unicode(commit.id if not deleted else commit.parent_ids[0])
    result = {
        "sha": unicode(patch.new_id if not deleted else patch.old_id),
        "status": GIT_STATUS_TO_NAME[patch.status],
        "filename": patch.new_file_path,
        "old_filename": patch.old_file_path,  # NOTE: RestfulGit extension
        "additions": patch.additions,
        "deletions": patch.deletions,
        "changes": patch.additions + patch.deletions,
        "raw_url": url_for('porcelain.get_raw',
                           _external=True,
                           repo_key=repo_key,
                           branch_or_tag_or_sha=commit_sha,
                           file_path=patch.new_file_path),
        "contents_url": url_for('porcelain.get_contents',
                                _external=True,
                                repo_key=repo_key,
                                file_path=patch.new_file_path,
                                ref=commit_sha),
    }
    if patch.new_file_path in filename_to_patch:
        result['patch'] = filename_to_patch[patch.new_file_path]
    return result

def convert_commit(repo_key, repo, commit, include_diff=False):
    plain_commit_json = _plumbing_convert_commit(repo_key, commit, porcelain=True)
    result = {
        "commit": plain_commit_json,
        "sha": plain_commit_json['sha'],
        "author": plain_commit_json['author'],
        "committer": plain_commit_json['committer'],
        "url": url_for('porcelain.get_commit', _external=True,
                       repo_key=repo_key, branch_or_tag_or_sha=unicode(commit.id)),
        "parents": [{
            "sha": unicode(c.id),
            "url": url_for('porcelain.get_commit', _external=True,
                           repo_key=repo_key, branch_or_tag_or_sha=unicode(c.id))
        } for c in commit.parents],
    }
    if include_diff:
        diff = get_diff(repo, commit)
        patches = list(diff)
        filename_to_patch = _filename_to_patch_from(diff)
        patches_additions = sum(patch.additions for patch in patches)
        patches_deletions = sum(patch.deletions for patch in patches)
        result.update({
            "stats": {
                "additions": patches_additions,
                "deletions": patches_deletions,
                "total": patches_additions + patches_deletions,
            },
            "files": [_convert_patch(repo_key, commit, patch, filename_to_patch) for patch in patches],
        })
    return result

def convert_blame(repo_key, repo, blame, raw_lines, start_line):
    annotated_lines = []
    commit_shas = set()
    for line_num, line in enumerate(raw_lines, start=start_line):
        hunk = blame.for_line(line_num)
        commit_sha = hunk.final_commit_id
        commit_shas.add(commit_sha)
        annotated_lines.append({
            'commit': unicode(commit_sha),
            'origPath': hunk.orig_path,
            'lineNum': line_num,
            'line': line,
        })

    return {
        'lines': annotated_lines,
        'commits': {
            unicode(commit_sha): _plumbing_convert_commit(repo_key, get_commit(repo, commit_sha))
            for commit_sha in commit_shas
        }
    }


text:
package org.carrot2.workbench.vis.circles;

import org.carrot2.workbench.core.ui.SearchEditor;
import org.carrot2.workbench.vis.AbstractBrowserVisualizationViewPage;
import org.carrot2.workbench.vis.AbstractVisualizationView;
import org.eclipse.ui.IWorkbenchPart;

/**
 * {@link CirclesView} displays clusters using browser-embedded Flash application.
 */
public final class CirclesView extends AbstractVisualizationView
{
    /**
     * Public identifier of this view.
     */
    public static final String ID = "org.carrot2.workbench.views.circles";

    @Override
    protected AbstractBrowserVisualizationViewPage wrappedCreatePage(IWorkbenchPart part)
    {
        final SearchEditor editor = (SearchEditor) part;
        final CirclesViewPage page = new CirclesViewPage(editor);
        initPage(page);
        page.createControl(getPageBook());
        return page;
    }
}


text:
@interface NearbyController : XBScrollPageController

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2014, Kinvey, Inc.
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
  in compliance with the License. You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software distributed under the License
  is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  or implied. See the License for the specific language governing permissions and limitations under
  the License.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:background="@drawable/card_back"
              android:layout_height="wrap_content">

        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:orientation="vertical"
                android:paddingRight="5dp">

            <TextView
                    android:id="@+id/row_type_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:paddingTop="10dp"
                    android:singleLine="true"
                    android:paddingBottom="10dp"
                    android:paddingLeft="20dp"
                    android:text="Filter name probably has to be long to reproduce cutting off but maybe not I guess we'll see!"
                    android:textSize="18sp"
                    />

            <TextView
                    android:visibility="gone"
                    android:id="@+id/row_type_details"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Filter details"
                    />
        </LinearLayout>

        <ImageView
                android:id="@+id/drag_handle"
                android:layout_width="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_height="wrap_content"
                android:background="@drawable/drag_handle"/>

</RelativeLayout>


text:
package de.jamoo.muzei;

import java.io.Serializable;

public class NodeWallpaper implements Serializable {
	private static final long serialVersionUID = 1L;

	public String name;
	public String author;
	public String thumbUrl;
	public String url;
}


text:
static NSTimeInterval proiorTime = 0;
// eric end

@implementation RecogTimeUtil

+(void)alarmClock:(NSInteger)paramHour minute:(NSInteger)paramMinute
{
    NSDate * today = [NSDate date];
    NSCalendar * cal = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents * todayComps = [cal components:unitFlags fromDate:today];

    NSDateComponents *fireComps = [[NSDateComponents alloc] init];
    [fireComps setDay:todayComps.day];
    [fireComps setMonth:todayComps.month];
    [fireComps setYear:todayComps.year];
    [fireComps setHour:paramHour];
    [fireComps setMinute:paramMinute];
    [fireComps setSecond:0];

    //NSLog(@"%d %d %d ", todayComps.day, todayComps.month, todayComps.year);
    NSDate * fireDate = [cal dateFromComponents:fireComps];

    //NSLog(@"%lf", [fireDate timeIntervalSinceNow]);

//    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
//    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
//    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
//    fireDate = [formatter dateFromString:@"2015-01-29 14:13:00"];

    UILocalNotification * notification = [[UILocalNotification alloc]init];
    [notification setFireDate:fireDate];//fireDate
    //[notification setRepeatInterval:NSCalendarUnitDay];
    [notification setTimeZone:[NSTimeZone defaultTimeZone]];
    //[notification setAlertBody:@"wake up"];
    //[notification setAlertAction:@"起床了"];
    //[notification setSoundName:UILocalNotificationDefaultSoundName];
    NSDictionary * dic = @{kLocalNotificationId: @"LocalNotificationId"};
    notification.userInfo = dic;

    [[UIApplication sharedApplication]scheduleLocalNotification:notification];

}

// eric start
+(BOOL)isCrazyClick
{
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    BOOL isQuick = (currentTime - proiorTime < 1.0);
    proiorTime = currentTime;

    return isQuick;
}
// eric end

@end