text:
```
cd /usr/share/munin/plugins
git clone git://github.com/tjstein/php5-fpm-munin-plugins.git
chmod +x php5-fpm-munin-plugins/phpfpm_*
ln -s /usr/share/munin/plugins/php5-fpm-munin-plugins/phpfpm_average /etc/munin/plugins/phpfpm_average
ln -s /usr/share/munin/plugins/php5-fpm-munin-plugins/phpfpm_connections /etc/munin/plugins/phpfpm_connections
ln -s /usr/share/munin/plugins/php5-fpm-munin-plugins/phpfpm_memory /etc/munin/plugins/phpfpm_memory
ln -s /usr/share/munin/plugins/php5-fpm-munin-plugins/phpfpm_status /etc/munin/plugins/phpfpm_status
ln -s /usr/share/munin/plugins/php5-fpm-munin-plugins/phpfpm_processes /etc/munin/plugins/phpfpm_processes
service munin-node restart
```

For the phpfpm_status and phpfpm_connections plugins, you'll need to enable the _status_ feature included in versions 5.3.2+ of PHP-FPM. The directive can be found in the php5-fpm.conf file:
```
pm.status_path = /status
```

Jérôme Loyet from the Nginx forums provided some useful insight on how to get this working with Nginx. You'll essentially set up the status location directive like this:

```
location ~ ^/(status|ping)$ {
    include fastcgi_params;
    fastcgi_pass backend;
    fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
    allow 127.0.0.1:9000;
    allow stats_collector.localdomain;
    allow watchdog.localdomain;
    deny all;
}
```

You'll need to make sure that from within your box, you can curl /status with `# curl http://localhost/status`. You should get a response similar to this:

```
accepted conn:    40163
pool:             www
process manager:  dynamic
idle processes:   6
active processes: 0
total processes:  6
```

#### Note:

The phpfpm_status plugin is particularly useful if you're using dynamic or on-demand process management. You can choose static, dynamic or on-demand in the php5-fpm.conf.

### Environment variables

* env.url: Set a custom url, defaults to _http://127.0.0.1/status_
* env.ports: Set a custom port, defaults to _80_
* env.phpbin: Set a custom php binary name, defaults to _php5-fpm_
* env.phppool: Set a custom php pool, defaults to www
* env.warning: Set the warning alarm, triggered when % of active/total connections higher than the defined value. Defaults to 0.6 (60%).
* env.critical: Set the critical alarm, triggered when % of active/total connections higher than the defined value. Defaults to 0.8 (80%).

#### Requirements:

libwww-perl


text:
cd /docker-build/support/build/sleep_all_day

gcc -o sleep_all_day sleep_all_day.c
cp sleep_all_day /usr/local/bin/sleep_all_day
chmod 755 /usr/local/bin/sleep_all_day

redpajama_set_name: RedPajamaGithub


text:
$(function(){

    $('#search').keyup(function() {

        $.ajax({
            type: "POST",
            url: "/search/",
            data: {
                'search_text' : $('#search').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}


text:
Добавить страницу

			<?php echo validation_errors(); ?>
				<?= form_open('admin/edit_article') ?>

						<fieldset>
							Заголовок
							<input name="title" value="<?= $get_article['title']; ?>" type="text">
						</fieldset>
						<fieldset>

Содержимое

							<textarea name="text" rows="12"><?= $get_article['content_text']; ?></textarea>

						</fieldset>
						<fieldset style="width:48%; float:left; margin-right: 3%;">
							Категория
							<select name="category" style="width:92%;">
								<option><?= $get_article['category']; ?></option>
								<option>Главная</option>
								<option>Примеры работ</option>
								<option>Обучение</option>
								<option>Инструмент</option>
								<option>Оценить вмятину</option>
								<option>Контакты</option>
							</select>
						</fieldset>
						<fieldset style="width:48%; float:left;">
							Тэги
							<input name="meta" value="<?= $get_article['meta']; ?>" type="text" style="width:92%;">
						</fieldset>

						<input type="hidden" name="id" value="<?= $get_article['id']; ?>">
						<fieldset style="width:48%; float:left;">
							Адрес
							<input name="address" value="<?= $get_article['address']; ?>" type="text" style="width:92%;">
						</fieldset>

Включить страницу

    						<input name="status" type="checkbox">
    						</i

							<input type="submit" value="Опубликовать" class="alt_btn">
							<input type="reset" value="Отмена">

			</form>


text:
package org.apache.tomcat.websocket;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManagerFactory;
import javax.websocket.ClientEndpoint;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.Extension;
import javax.websocket.HandshakeResponse;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.websocket.pojo.PojoEndpointClient;

public class WsWebSocketContainer
        implements WebSocketContainer, BackgroundProcess {

    /**
     * Property name to set to configure the value that is passed to
     * {@link SSLEngine#setEnabledProtocols(String[])}. The value should be a
     * comma separated string.
     */
    public static final String SSL_PROTOCOLS_PROPERTY =
            "org.apache.tomcat.websocket.SSL_PROTOCOLS";
    public static final String SSL_TRUSTSTORE_PROPERTY =
            "org.apache.tomcat.websocket.SSL_TRUSTSTORE";
    public static final String SSL_TRUSTSTORE_PWD_PROPERTY =
            "org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD";
    public static final String SSL_TRUSTSTORE_PWD_DEFAULT = "changeit";
    /**
     * Property name to set to configure used SSLContext. The value should be an
     * instance of SSLContext. If this property is present, the SSL_TRUSTSTORE*
     * properties are ignored.
     */
    public static final String SSL_CONTEXT_PROPERTY =
            "org.apache.tomcat.websocket.SSL_CONTEXT";

    /**
     * Property name to set to configure the timeout (in milliseconds) when
     * establishing a WebSocket connection to server. The default is
     * {@link #IO_TIMEOUT_MS_DEFAULT}.
     */
    public static final String IO_TIMEOUT_MS_PROPERTY =
            "org.apache.tomcat.websocket.IO_TIMEOUT_MS";

    public static final long IO_TIMEOUT_MS_DEFAULT = 5000;

    private static final StringManager sm =
            StringManager.getManager(Constants.PACKAGE_NAME);
    private static final Random random = new Random();
    private static final byte[] crlf = new byte[] {13, 10};

    private volatile AsynchronousChannelGroup asynchronousChannelGroup = null;
    private final Object asynchronousChannelGroupLock = new Object();

    private final Log log = LogFactory.getLog(WsWebSocketContainer.class);
    private final Map<Class<?>, Set<WsSession>> endpointSessionMap =
            new HashMap<Class<?>, Set<WsSession>>();
    private final Map<WsSession,WsSession> sessions = new ConcurrentHashMap<WsSession, WsSession>();
    private final Object endPointSessionMapLock = new Object();

    private long defaultAsyncTimeout = -1;
    private int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE;
    private int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE;
    private volatile long defaultMaxSessionIdleTimeout = 0;
    private int backgroundProcessCount = 0;
    private int processPeriod = 10;

    @Override
    public Session connectToServer(Object pojo, URI path)
            throws DeploymentException {

        ClientEndpoint annotation =
                pojo.getClass().getAnnotation(ClientEndpoint.class);
        if (annotation == null) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.missingAnnotation",
                            pojo.getClass().getName()));
        }

        Endpoint ep = new PojoEndpointClient(pojo, annotation.decoders());

        Class<? extends ClientEndpointConfig.Configurator> configuratorClazz =
                annotation.configurator();

        ClientEndpointConfig.Configurator configurator = null;
        if (!ClientEndpointConfig.Configurator.class.equals(
                configuratorClazz)) {
            try {
                configurator = configuratorClazz.newInstance();
            } catch (InstantiationException e) {
                throw new DeploymentException(sm.getString(
                        "wsWebSocketContainer.defaultConfiguratorFail"), e);
            } catch (IllegalAccessException e) {
                throw new DeploymentException(sm.getString(
                        "wsWebSocketContainer.defaultConfiguratorFail"), e);
            }
        }

        ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
        // Avoid NPE when using RI API JAR - see BZ 56343
        if (configurator != null) {
            builder.configurator(configurator);
        }
        ClientEndpointConfig config = builder.
                decoders(Arrays.asList(annotation.decoders())).
                encoders(Arrays.asList(annotation.encoders())).
                preferredSubprotocols(Arrays.asList(annotation.subprotocols())).
                build();
        return connectToServer(ep, config, path);
    }

    @Override
    public Session connectToServer(Class<?> annotatedEndpointClass, URI path)
            throws DeploymentException {

        Object pojo;
        try {
            pojo = annotatedEndpointClass.newInstance();
        } catch (InstantiationException e) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.endpointCreateFail",
                    annotatedEndpointClass.getName()), e);
        } catch (IllegalAccessException e) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.endpointCreateFail",
                    annotatedEndpointClass.getName()), e);
        }

        return connectToServer(pojo, path);
    }

    @Override
    public Session connectToServer(Class<? extends Endpoint> clazz,
            ClientEndpointConfig clientEndpointConfiguration, URI path)
            throws DeploymentException {

        Endpoint endpoint;
        try {
            endpoint = clazz.newInstance();
        } catch (InstantiationException e) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.endpointCreateFail", clazz.getName()),
                    e);
        } catch (IllegalAccessException e) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.endpointCreateFail", clazz.getName()),
                    e);
        }

        return connectToServer(endpoint, clientEndpointConfiguration, path);
    }

    @Override
    public Session connectToServer(Endpoint endpoint,
            ClientEndpointConfig clientEndpointConfiguration, URI path)
            throws DeploymentException {

        boolean secure = false;

        String scheme = path.getScheme();
        if (!("ws".equalsIgnoreCase(scheme) ||
                "wss".equalsIgnoreCase(scheme))) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.pathWrongScheme", scheme));
        }
        String host = path.getHost();
        if (host == null) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.pathNoHost"));
        }
        int port = path.getPort();
        Map<String,List<String>> reqHeaders = createRequestHeaders(host, port,
                clientEndpointConfiguration.getPreferredSubprotocols(),
                clientEndpointConfiguration.getExtensions());
        clientEndpointConfiguration.getConfigurator().
                beforeRequest(reqHeaders);

        ByteBuffer request = createRequest(path, reqHeaders);

        SocketAddress sa;
        if (port == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                sa = new InetSocketAddress(host, 80);
            } else if ("wss".equalsIgnoreCase(scheme)) {
                sa = new InetSocketAddress(host, 443);
                secure = true;
            } else {
                throw new DeploymentException(
                        sm.getString("wsWebSocketContainer.invalidScheme"));
            }
        } else {
            if ("wss".equalsIgnoreCase(scheme)) {
                secure = true;
            }
            sa = new InetSocketAddress(host, port);
        }

        AsynchronousSocketChannel socketChannel;
        try {
            socketChannel = AsynchronousSocketChannel.open(getAsynchronousChannelGroup());
        } catch (IOException ioe) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.asynchronousSocketChannelFail"), ioe);
        }

        Future<Void> fConnect = socketChannel.connect(sa);

        AsyncChannelWrapper channel;
        if (secure) {
            SSLEngine sslEngine = createSSLEngine(
                    clientEndpointConfiguration.getUserProperties());
            channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine);
        } else {
            channel = new AsyncChannelWrapperNonSecure(socketChannel);
        }

        // Get the connection timeout
        long timeout = IO_TIMEOUT_MS_DEFAULT;
        String timeoutValue = (String) clientEndpointConfiguration.getUserProperties().get(
                IO_TIMEOUT_MS_PROPERTY);
        if (timeoutValue != null) {
            timeout = Long.valueOf(timeoutValue).intValue();
        }

        ByteBuffer response;
        String subProtocol;
        boolean success = false;
        try {
            fConnect.get(timeout, TimeUnit.MILLISECONDS);

            Future<Void> fHandshake = channel.handshake();
            fHandshake.get(timeout, TimeUnit.MILLISECONDS);

            int toWrite = request.limit();

            Future<Integer> fWrite = channel.write(request);
            Integer thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
            toWrite -= thisWrite.intValue();

            while (toWrite > 0) {
                fWrite = channel.write(request);
                thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
                toWrite -= thisWrite.intValue();
            }
            // Same size as the WsFrame input buffer
            response = ByteBuffer.allocate(maxBinaryMessageBufferSize);

            HandshakeResponse handshakeResponse =
                    processResponse(response, channel, timeout);
            clientEndpointConfiguration.getConfigurator().
                    afterResponse(handshakeResponse);

            // Sub-protocol
            // Header names are always stored in lower case
            List<String> values = handshakeResponse.getHeaders().get(
                    Constants.WS_PROTOCOL_HEADER_NAME_LOWER);
            if (values == null || values.size() == 0) {
                subProtocol = null;
            } else if (values.size() == 1) {
                subProtocol = values.get(0);
            } else {
                throw new DeploymentException(
                        sm.getString("Sec-WebSocket-Protocol"));
            }
            success = true;
        } catch (ExecutionException e) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        } catch (InterruptedException e) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        } catch (SSLException e) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        } catch (EOFException e) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        } catch (TimeoutException e) {
            throw new DeploymentException(
                    sm.getString("wsWebSocketContainer.httpRequestFailed"), e);
        } finally {
            if (!success) {
                channel.close();
            }
        }

        // Switch to WebSocket
        WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel);

        WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient,
                this, null, null, null, null, null, Collections.<Extension>emptyList(),
                subProtocol, Collections.<String,String>emptyMap(), secure,
                clientEndpointConfiguration);

        WsFrameClient wsFrameClient = new WsFrameClient(response, channel,
                wsSession);
        // WsFrame adds the necessary final transformations. Copy the
        // completed transformation chain to the remote end point.
        wsRemoteEndpointClient.setTransformation(wsFrameClient.getTransformation());

        endpoint.onOpen(wsSession, clientEndpointConfiguration);
        registerSession(endpoint, wsSession);

        wsFrameClient.startInputProcessing();

        return wsSession;
    }

    protected void registerSession(Endpoint endpoint, WsSession wsSession) {

        Class<?> endpointClazz = endpoint.getClass();

        if (!wsSession.isOpen()) {
            // The session was closed during onOpen. No need to register it.
            return;
        }
        synchronized (endPointSessionMapLock) {
            if (endpointSessionMap.size() == 0) {
                BackgroundProcessManager.getInstance().register(this);
            }
            Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz);
            if (wsSessions == null) {
                wsSessions = new HashSet<WsSession>();
                endpointSessionMap.put(endpointClazz, wsSessions);
            }
            wsSessions.add(wsSession);
        }
        sessions.put(wsSession, wsSession);
    }

    protected void unregisterSession(Endpoint endpoint, WsSession wsSession) {

        Class<?> endpointClazz = endpoint.getClass();

        synchronized (endPointSessionMapLock) {
            Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz);
            if (wsSessions != null) {
                wsSessions.remove(wsSession);
                if (wsSessions.size() == 0) {
                    endpointSessionMap.remove(endpointClazz);
                }
            }
            if (endpointSessionMap.size() == 0) {
                BackgroundProcessManager.getInstance().unregister(this);
            }
        }
        sessions.remove(wsSession);
    }

    Set<Session> getOpenSessions(Class<?> endpoint) {
        HashSet<Session> result = new HashSet<Session>();
        synchronized (endPointSessionMapLock) {
            Set<WsSession> sessions = endpointSessionMap.get(endpoint);
            if (sessions != null) {
                result.addAll(sessions);
            }
        }
        return result;
    }

    private Map<String,List<String>> createRequestHeaders(String host,
            int port, List<String> subProtocols, List<Extension> extensions) {

        Map<String,List<String>> headers = new HashMap<String, List<String>>();

        // Host header
        List<String> hostValues = new ArrayList<String>(1);
        if (port == -1) {
            hostValues.add(host);
        } else {
            hostValues.add(host + ':' + port);
        }

        headers.put(Constants.HOST_HEADER_NAME, hostValues);

        // Upgrade header
        List<String> upgradeValues = new ArrayList<String>(1);
        upgradeValues.add(Constants.UPGRADE_HEADER_VALUE);
        headers.put(Constants.UPGRADE_HEADER_NAME, upgradeValues);

        // Connection header
        List<String> connectionValues = new ArrayList<String>(1);
        connectionValues.add(Constants.CONNECTION_HEADER_VALUE);
        headers.put(Constants.CONNECTION_HEADER_NAME, connectionValues);

        // WebSocket version header
        List<String> wsVersionValues = new ArrayList<String>(1);
        wsVersionValues.add(Constants.WS_VERSION_HEADER_VALUE);
        headers.put(Constants.WS_VERSION_HEADER_NAME, wsVersionValues);

        // WebSocket key
        List<String> wsKeyValues = new ArrayList<String>(1);
        wsKeyValues.add(generateWsKeyValue());
        headers.put(Constants.WS_KEY_HEADER_NAME, wsKeyValues);

        // WebSocket sub-protocols
        if (subProtocols != null && subProtocols.size() > 0) {
            headers.put(Constants.WS_PROTOCOL_HEADER_NAME, subProtocols);
        }

        // WebSocket extensions
        if (extensions != null && extensions.size() > 0) {
            headers.put(Constants.WS_EXTENSIONS_HEADER_NAME,
                    generateExtensionHeaders(extensions));
        }

        return headers;
    }

    private List<String> generateExtensionHeaders(List<Extension> extensions) {
        List<String> result = new ArrayList<String>(extensions.size());
        for (Extension extension : extensions) {
            StringBuilder header = new StringBuilder();
            header.append(extension.getName());
            for (Extension.Parameter param : extension.getParameters()) {
                header.append(';');
                header.append(param.getName());
                String value = param.getValue();
                if (value != null && value.length() > 0) {
                    header.append('=');
                    header.append(value);
                }
            }
        }
        return result;
    }

    private String generateWsKeyValue() {
        byte[] keyBytes = new byte[16];
        random.nextBytes(keyBytes);
        return Base64.encodeBase64String(keyBytes);
    }

    private ByteBuffer createRequest(URI uri,
            Map<String,List<String>> reqHeaders) {
        ByteBuffer result = ByteBuffer.allocate(4 * 1024);

        // Request line
        result.put("GET ".getBytes(StandardCharsets.ISO_8859_1));
        result.put(uri.getRawPath().getBytes(StandardCharsets.ISO_8859_1));
        String query = uri.getRawQuery();
        if (query != null) {
            result.put((byte) '?');
            result.put(query.getBytes(StandardCharsets.ISO_8859_1));
        }
        result.put(" HTTP/1.1\r\n".getBytes(StandardCharsets.ISO_8859_1));

        // Headers
        Iterator<Entry<String,List<String>>> iter =
                reqHeaders.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String,List<String>> entry = iter.next();
            addHeader(result, entry.getKey(), entry.getValue());
        }

        // Terminating CRLF
        result.put(crlf);

        result.flip();

        return result;
    }

    private void addHeader(ByteBuffer result, String key, List<String> values) {
        StringBuilder sb = new StringBuilder();

        Iterator<String> iter = values.iterator();
        if (!iter.hasNext()) {
            return;
        }
        sb.append(iter.next());
        while (iter.hasNext()) {
            sb.append(',');
            sb.append(iter.next());
        }

        result.put(key.getBytes(StandardCharsets.ISO_8859_1));
        result.put(": ".getBytes(StandardCharsets.ISO_8859_1));
        result.put(sb.toString().getBytes(StandardCharsets.ISO_8859_1));
        result.put(crlf);
    }

    /**
     * Process response, blocking until HTTP response has been fully received.
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws DeploymentException
     * @throws TimeoutException
     */
    @SuppressWarnings("null") // line is not null in line.endsWith() call
    private HandshakeResponse processResponse(ByteBuffer response,
            AsyncChannelWrapper channel, long timeout) throws InterruptedException,
            ExecutionException, DeploymentException, EOFException,
            TimeoutException {

        Map<String,List<String>> headers = new HashMap<String, List<String>>();

        boolean readStatus = false;
        boolean readHeaders = false;
        String line = null;
        while (!readHeaders) {
            // On entering loop buffer will be empty and at the start of a new
            // loop the buffer will have been fully read.
            response.clear();
            // Blocking read
            Future<Integer> read = channel.read(response);
            Integer bytesRead = read.get(timeout, TimeUnit.MILLISECONDS);
            if (bytesRead.intValue() == -1) {
                throw new EOFException();
            }
            response.flip();
            while (response.hasRemaining() && !readHeaders) {
                if (line == null) {
                    line = readLine(response);
                } else {
                    line += readLine(response);
                }
                if ("\r\n".equals(line)) {
                    readHeaders = true;
                } else if (line.endsWith("\r\n")) {
                    if (readStatus) {
                        parseHeaders(line, headers);
                    } else {
                        parseStatus(line);
                        readStatus = true;
                    }
                    line = null;
                }
            }
        }

        return new WsHandshakeResponse(headers);
    }

    private void parseStatus(String line) throws DeploymentException {
        // This client only understands HTTP 1.1
        // RFC2616 is case specific
        if (!line.startsWith("HTTP/1.1 101")) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.invalidStatus", line));
        }
    }

    private void parseHeaders(String line, Map<String,List<String>> headers) {
        // Treat headers as single values by default.

        int index = line.indexOf(':');
        if (index == -1) {
            log.warn(sm.getString("wsWebSocketContainer.invalidHeader", line));
            return;
        }
        // Header names are case insensitive so always use lower case
        String headerName = line.substring(0, index).trim().toLowerCase();
        // TODO handle known multi-value headers
        String headerValue = line.substring(index + 1).trim();

        List<String> values = headers.get(headerName);
        if (values == null) {
            values = new ArrayList<String>(1);
            headers.put(headerName, values);
        }
        values.add(headerValue);
    }

    private String readLine(ByteBuffer response) {
        // All ISO-8859-1
        StringBuilder sb = new StringBuilder();

        char c = 0;
        while (response.hasRemaining()) {
            c = (char) response.get();
            sb.append(c);
            if (c == 10) {
                break;
            }
        }

        return sb.toString();
    }

    private SSLEngine createSSLEngine(Map<String,Object> userProperties)
            throws DeploymentException {

        try {
            // See if a custom SSLContext has been provided
            SSLContext sslContext =
                    (SSLContext) userProperties.get(SSL_CONTEXT_PROPERTY);

            if (sslContext == null) {
                // Create the SSL Context
                sslContext = SSLContext.getInstance("TLS");

                // Trust store
                String sslTrustStoreValue =
                        (String) userProperties.get(SSL_TRUSTSTORE_PROPERTY);
                if (sslTrustStoreValue != null) {
                    String sslTrustStorePwdValue = (String) userProperties.get(
                            SSL_TRUSTSTORE_PWD_PROPERTY);
                    if (sslTrustStorePwdValue == null) {
                        sslTrustStorePwdValue = SSL_TRUSTSTORE_PWD_DEFAULT;
                    }

                    File keyStoreFile = new File(sslTrustStoreValue);
                    KeyStore ks = KeyStore.getInstance("JKS");
                    InputStream is = null;
                    try {
                        is = new FileInputStream(keyStoreFile);
                        ks.load(is, sslTrustStorePwdValue.toCharArray());
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException ioe) {
                               // Ignore
                            }
                        }
                    }

                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                            TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init(ks);

                    sslContext.init(null, tmf.getTrustManagers(), null);
                } else {
                    sslContext.init(null, null, null);
                }
            }

            SSLEngine engine = sslContext.createSSLEngine();

            String sslProtocolsValue =
                    (String) userProperties.get(SSL_PROTOCOLS_PROPERTY);
            if (sslProtocolsValue != null) {
                engine.setEnabledProtocols(sslProtocolsValue.split(","));
            }

            engine.setUseClientMode(true);

            return engine;
        } catch (Exception e) {
            throw new DeploymentException(sm.getString(
                    "wsWebSocketContainer.sslEngineFail"), e);
        }
    }

    @Override
    public long getDefaultMaxSessionIdleTimeout() {
        return defaultMaxSessionIdleTimeout;
    }

    @Override
    public void setDefaultMaxSessionIdleTimeout(long timeout) {
        this.defaultMaxSessionIdleTimeout = timeout;
    }

    @Override
    public int getDefaultMaxBinaryMessageBufferSize() {
        return maxBinaryMessageBufferSize;
    }

    @Override
    public void setDefaultMaxBinaryMessageBufferSize(int max) {
        maxBinaryMessageBufferSize = max;
    }

    @Override
    public int getDefaultMaxTextMessageBufferSize() {
        return maxTextMessageBufferSize;
    }

    @Override
    public void setDefaultMaxTextMessageBufferSize(int max) {
        maxTextMessageBufferSize = max;
    }

    /**
     * {@inheritDoc}
     *
     * Currently, this implementation does not support any extensions.
     */
    @Override
    public Set<Extension> getInstalledExtensions() {
        return Collections.emptySet();
    }

    /**
     * {@inheritDoc}
     *
     * The default value for this implementation is -1.
     */
    @Override
    public long getDefaultAsyncSendTimeout() {
        return defaultAsyncTimeout;
    }

    /**
     * {@inheritDoc}
     *
     * The default value for this implementation is -1.
     */
    @Override
    public void setAsyncSendTimeout(long timeout) {
        this.defaultAsyncTimeout = timeout;
    }

    /**
     * Cleans up the resources still in use by WebSocket sessions created from
     * this container. This includes closing sessions and cancelling
     * {@link Future}s associated with blocking read/writes.
     */
    public void destroy() {
        CloseReason cr = new CloseReason(
                CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown"));

        for (WsSession session : sessions.keySet()) {
            try {
                session.close(cr);
            } catch (IOException ioe) {
                log.debug(sm.getString(
                        "wsWebSocketContainer.sessionCloseFail", session.getId()), ioe);
            }
        }

        // Only unregister with AsyncChannelGroupUtil if this instance
        // registered with it
        if (asynchronousChannelGroup != null) {
            synchronized (asynchronousChannelGroupLock) {
                if (asynchronousChannelGroup != null) {
                    AsyncChannelGroupUtil.unregister();
                    asynchronousChannelGroup = null;
                }
            }
        }
    }

    private AsynchronousChannelGroup getAsynchronousChannelGroup() {
        // Use AsyncChannelGroupUtil to share a common group amongst all
        // WebSocket clients
        AsynchronousChannelGroup result = asynchronousChannelGroup;
        if (result == null) {
            synchronized (asynchronousChannelGroupLock) {
                if (asynchronousChannelGroup == null) {
                    asynchronousChannelGroup = AsyncChannelGroupUtil.register();
                }
                result = asynchronousChannelGroup;
            }
        }
        return result;
    }

    // ----------------------------------------------- BackgroundProcess methods

    @Override
    public void backgroundProcess() {
        // This method gets called once a second.
        backgroundProcessCount ++;

        if (backgroundProcessCount >= processPeriod) {
            backgroundProcessCount = 0;

            for (WsSession wsSession : sessions.keySet()) {
                wsSession.checkExpiration();
            }
        }

    }

    @Override
    public void setProcessPeriod(int period) {
        this.processPeriod = period;
    }

    /**
     * {@inheritDoc}
     *
     * The default value is 10 which means session expirations are processed
     * every 10 seconds.
     */
    @Override
    public int getProcessPeriod() {
        return processPeriod;
    }
}


text:
goog.provide('goog.events.gestures');

goog.require('goog.asserts');
goog.require('goog.events.gestures.PanRecognizer');
goog.require('goog.events.gestures.PinchRecognizer');
goog.require('goog.events.gestures.RotateRecognizer');
goog.require('goog.events.gestures.SwipeRecognizer');
goog.require('goog.events.gestures.TapRecognizer');
goog.require('goog.events.gestures.TouchView');

/**
 * Creates a new {@see goog.events.gestures.PanRecognizer}.
 *
 * @param {!Element} target DOM element to attach to.
 * @param {!function(this:T, !goog.events.gestures.Recognizer)} callback
 *     Function called on each gesture action.
 * @param {T=} opt_scope Scope that the callback will be called in.
 * @return {!goog.events.gestures.PanRecognizer} A new bound gesture instance.
 * @template T
 */
goog.events.gestures.attachPanGesture =
    function(target, callback, opt_scope) {
  var recognizer = new goog.events.gestures.PanRecognizer(target);
  recognizer.addListener(callback, opt_scope);
  return recognizer;
};

/**
 * Creates a new {@see goog.events.gestures.PinchRecognizer}.
 *
 * @param {!Element} target DOM element to attach to.
 * @param {!function(this:T, !goog.events.gestures.Recognizer)} callback
 *     Function called on each gesture action.
 * @param {T=} opt_scope Scope that the callback will be called in.
 * @return {!goog.events.gestures.PinchRecognizer} A new bound gesture instance.
 * @template T
 */
goog.events.gestures.attachPinchGesture =
    function(target, callback, opt_scope) {
  var recognizer = new goog.events.gestures.PinchRecognizer(target);
  recognizer.addListener(callback, opt_scope);
  return recognizer;
};

/**
 * Creates a new {@see goog.events.gestures.RotateRecognizer}.
 *
 * @param {!Element} target DOM element to attach to.
 * @param {!function(this:T, !goog.events.gestures.Recognizer)} callback
 *     Function called on each gesture action.
 * @param {T=} opt_scope Scope that the callback will be called in.
 * @return {!goog.events.gestures.RotateRecognizer} A new bound gesture
 *     instance.
 * @template T
 */
goog.events.gestures.attachRotateGesture =
    function(target, callback, opt_scope) {
  var recognizer = new goog.events.gestures.RotateRecognizer(target);
  recognizer.addListener(callback, opt_scope);
  return recognizer;
};

/**
 * Creates a new {@see goog.events.gestures.SwipeRecognizer}.
 *
 * @param {!Element} target DOM element to attach to.
 * @param {!function(this:T, !goog.events.gestures.Recognizer)} callback
 *     Function called on each gesture action.
 * @param {T=} opt_scope Scope that the callback will be called in.
 * @return {!goog.events.gestures.SwipeRecognizer} A new bound gesture instance.
 * @template T
 */
goog.events.gestures.attachSwipeGesture =
    function(target, callback, opt_scope) {
  var recognizer = new goog.events.gestures.SwipeRecognizer(target);
  recognizer.addListener(callback, opt_scope);
  return recognizer;
};

/**
 * Creates a new {@see goog.events.gestures.TapRecognizer}.
 *
 * @param {!Element} target DOM element to attach to.
 * @param {!function(this:T, !goog.events.gestures.Recognizer)} callback
 *     Function called on each gesture action.
 * @param {T=} opt_scope Scope that the callback will be called in.
 * @return {!goog.events.gestures.TapRecognizer} A new bound gesture instance.
 * @template T
 */
goog.events.gestures.attachTapGesture =
    function(target, callback, opt_scope) {
  var recognizer = new goog.events.gestures.TapRecognizer(target);
  recognizer.addListener(callback, opt_scope);
  return recognizer;
};

/**
 * Removes and disposes all of the gestures from the given element.
 * @param {!Element} target DOM element to clean up.
 */
goog.events.gestures.unattachAllGestures = function(target) {
  goog.events.gestures.TouchView.disposeInstance(target);
};

/**
 * Allows for symmetrical simultaneous recognition of the given list of
 * gesture recognizers.
 * @param {...!goog.events.gestures.Recognizer} var_args Recognizers that are
 *     allowed to simultaneously recognize.
 */
goog.events.gestures.allowSimultaneousRecognition = function(var_args) {
  for (var n = 0; n < arguments.length; n++) {
    var target = /** @type {goog.events.gestures.Recognizer} */ (arguments[n]);
    goog.asserts.assert(target);
    for (var m = 0; m < arguments.length; m++) {
      if (n != m) {
        var other =
            /** @type {goog.events.gestures.Recognizer} */ (arguments[m]);
        goog.asserts.assert(other);
        target.addAllowedSimultaneousRecognizer(other);
      }
    }
  }
};


text:
New User

    <form class="form-horizontal">

            Username

                <input type="text" id="inputUsername" placeholder="Username" autocomplete="off">

            Name

                <input type="text" id="inputName" placeholder="Name" autocomplete="off">

            Email

                <input type="text" id="inputEmail" placeholder="Email" autocomplete="off">

            Password

                <input type="text" id="inputPassword" placeholder="Password" autocomplete="off">

            Permission Group

                <input type="hidden" id="inputPermissionGroup" style="width: 220px;" autocomplete="off">

            Collection Centers

                <input type="hidden" id="inputCollectionCenters" style="width: 220px;" autocomplete="off">

                <button class="btn btn-primary" type="button" id="new_user_create_btn" data-loading-text="Creating..." autocomplete="off">Create User</button>

    </form>


text:
/* global check, Match, Meteor, _, Tabular */

/*
 * These are the two publications used by TabularTable.
 *
 * The genericPub one can be overridden by supplying a `pub`
 * property with a different publication name. This publication
 * is given only the list of ids and requested fields. You may
 * want to override it if you need to publish documents from
 * related collections along with the table collection documents.
 *
 * The getInfo one runs first and handles all the complex logic
 * required by this package, so that you don't have to duplicate
 * this logic when overriding the genericPub function.
 *
 * Having two publications also allows fine-grained control of
 * reactivity on the client.
 */

Meteor.publish("tabular_genericPub", function (tableName, ids, fields) {
  var self = this;

  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  var table = Tabular.tablesByName[tableName];
  if (!table) {
    // We throw an error in the other pub, so no need to throw one here
    self.ready();
    return;
  }

  // Check security. We call this in both publications.
  if (typeof table.allow === 'function' && !table.allow(self.userId, fields)) {
    self.ready();
    return;
  }

  // Check security for fields. We call this only in this publication
  if (typeof table.allowFields === 'function' && !table.allowFields(self.userId, fields)) {
    self.ready();
    return;
  }

  return table.collection.find({_id: {$in: ids}}, {fields: fields});
});

Meteor.publish("tabular_getInfo", function(tableName, selector, sort, skip, limit) {
  var self = this;

  check(tableName, String);
  check(selector, Match.Optional(Match.OneOf(Object, null)));
  check(sort, Match.Optional(Match.OneOf(Array, null)));
  check(skip, Number);
  check(limit, Match.Optional(Match.OneOf(Number, null)));

  var table = Tabular.tablesByName[tableName];
  if (!table) {
    throw new Error('No TabularTable defined with the name "' + tableName + '". Make sure you are defining your TabularTable in common code.');
  }

  // Check security. We call this in both publications.
  // Even though we're only publishing _ids and counts
  // from this function, with sensitive data, there is
  // a chance someone could do a query and learn something
  // just based on whether a result is found or not.
  if (typeof table.allow === 'function' && !table.allow(self.userId)) {
    self.ready();
    return;
  }

  selector = selector || {};

  // Allow the user to modify the selector before we use it
  if (typeof table.changeSelector === 'function') {
    selector = table.changeSelector(selector, self.userId);
  }

  // Apply the server side selector specified in the tabular
  // table constructor. Both must be met, so we join
  // them using $and, allowing both selectors to have
  // the same keys.
  if (typeof table.selector === 'function') {
    var tableSelector = table.selector(self.userId);
    if (_.isEmpty(selector)) {
      selector = tableSelector;
    } else {
      selector = {$and: [tableSelector, selector]};
    }
  }

  var findOptions = {
    skip: skip,
    fields: {_id: 1}
  };

  // `limit` may be `null`
  if (limit > 0) {
    findOptions.limit = limit;
  }

  // `sort` may be `null`
  if (_.isArray(sort)) {
    findOptions.sort = sort;
  }

  var filteredCursor = table.collection.find(selector, findOptions);

  var filteredRecordIds = filteredCursor.map(function (doc) {
    return doc._id;
  });

  var countCursor = table.collection.find(selector, {fields: {_id: 1}});

  var recordReady = false;
  var updateRecords = function updateRecords() {
    var currentCount = countCursor.count();

    // From https://datatables.net/manual/server-side
    // recordsTotal: Total records, before filtering (i.e. the total number of records in the database)
    // recordsFiltered: Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).

    var record = {
      ids: filteredRecordIds,
      // count() will give us the updated total count
      // every time. It does not take the find options
      // limit into account.
      recordsTotal: currentCount,
      recordsFiltered: currentCount
    };

    if (recordReady) {
      //console.log("changed", tableName, record);
      self.changed('tabular_records', tableName, record);
    } else {
      //console.log("added", tableName, record);
      self.added("tabular_records", tableName, record);
      recordReady = true;
    }
  };

  if (table.throttleRefresh) {
    updateRecords = _.throttle(updateRecords, table.throttleRefresh);
  }

  updateRecords();

  self.ready();

  // Handle docs being added or removed from the result set.
  var initializing = true;
  var handle = filteredCursor.observeChanges({
    added: function (id) {
      if (initializing) return;

      //console.log("ADDED");
      filteredRecordIds.push(id);
      updateRecords();
    },
    removed: function (id) {
      //console.log("REMOVED");
      // _.findWhere is used to support Mongo ObjectIDs
      filteredRecordIds = _.without(filteredRecordIds, _.findWhere(filteredRecordIds, id));
      updateRecords();
    }
  });
  initializing = false;

  // It is too inefficient to use an observe without any limits to track count perfectly
  // accurately when, for example, the selector is {} and there are a million documents.
  // Instead we will update the count every 10 seconds, in addition to whenever the limited
  // result set changes.
  var interval = Meteor.setInterval(updateRecords, 10000);

  // Stop observing the cursors when client unsubs.
  // Stopping a subscription automatically takes
  // care of sending the client any removed messages.
  self.onStop(function () {
    Meteor.clearInterval(interval);
    handle.stop();
  });
});


text:
"use strict";

var ControlRod = require('control-rod'),
    ControlRodAssembly = require('../index.js'),
    events = require('events');

var test = module.exports = {};

test['connect() connects all control rods in assembly'] = function (test) {
    test.expect(8);
    var emitter1 = new events.EventEmitter();
    var emitter2 = new events.EventEmitter();
    var handler1 = function () {};
    var handler2 = function () {};
    var handler3 = function () {};
    var rod1 = new ControlRod(emitter1, 'e1h1', handler1);
    var rod2 = new ControlRod(emitter2, 'e2h1', handler1);
    var rod3 = new ControlRod(emitter2, 'e2h2', handler2);
    var rod4 = new ControlRod(emitter1, 'e1h3', handler3);
    test.strictEqual(rod1.connected, false);
    test.strictEqual(rod2.connected, false);
    test.strictEqual(rod3.connected, false);
    test.strictEqual(rod4.connected, false);
    var assembly = new ControlRodAssembly(rod1, rod2, rod3, rod4);
    assembly.connect();
    test.strictEqual(rod1.connected, true);
    test.strictEqual(rod2.connected, true);
    test.strictEqual(rod3.connected, true);
    test.strictEqual(rod4.connected, true);
    test.done();
};

test['connect() emits "connected" event after connecting all rods in assembly'] = function (test) {
    test.expect(3);
    var emitter1 = new events.EventEmitter();
    var handler1 = function () {};
    var rod1 = new ControlRod(emitter1, 'e1h1', handler1);
    test.strictEqual(rod1.connected, false);
    var assembly = new ControlRodAssembly(rod1);
    assembly.on('connected', function () {
        test.ok(true);
    });
    assembly.connect();
    test.strictEqual(rod1.connected, true);
    test.done();
};


text:
/**
 * @file   E_Module.hpp
 * @Author leeopop (dlrmsghd@gmail.com)
 * @date   November, 2014
 * @brief  Header for E::Module
 */

#ifndef E_MODULE_HPP_
#define E_MODULE_HPP_

#include <E/E_Common.hpp>

namespace E {
class System;
using ModuleID = uintptr_t;

/**
 * @brief Module is an interface for classes
 * which can send/receive Message to/from the System.
 *
 * @see System
 */
class Module {
private:
  System &system;
  ModuleID id;

public:
  /**
   * @brief Module must belong to a System.
   * Module is registered to a System when it is created.
   * @param system System to be registered.
   */
  Module(System &system);
  virtual ~Module();

  std::string getModuleName();
  std::string getModuleName(const ModuleID moduleID);
  Time getCurrentTime();

  /**
   * @brief Interface of Message. Every message implementation
   * must inherit this class.
   *
   * @see Module::messageReceived, Module::messageFinished, and
   * Module::messageCancelled for further information.
   */
  class MessageBase {
  public:
    MessageBase() {}
    virtual ~MessageBase() {}
  };

  class EmptyMessage : public MessageBase {
  public:
    static EmptyMessage &shared();
    bool operator==(const EmptyMessage &b) const { return true; }
  };

  using Message = std::unique_ptr<MessageBase>;

protected:
  /**
   * @brief This is a callback function called by the System.
   * This function is automatically called when you received a Message.
   * If you want to handle Message, override this function with your own
   * handler.
   *
   * @param from Source module which created and sent the message.
   * This cannot be null (someone must create the message).
   * If you sent a message to yourself, this parameter would be [this].
   * @param message Message you received. This message is allocated by other
   * module, so DO NOT DEALLOCATE THE GIVEN MESSAGE (even it is your self
   * message).
   * @return If you want to give a feedback to the sender of this message,
   * ALLOCATE ANOTHER MESSAGE and return it.
   *
   * @note Using default implementation is forbidden.
   * If you use the default implementation, no module can send messages to you.
   */
  virtual Module::Message messageReceived(const ModuleID from,
                                          Module::MessageBase &message) {
    (void)from;
    (void)message;
    assert(0);
    return nullptr;
  }

  /**
   * @brief This is a callback function called by the System.
   * This function is automatically called after your message is processed by
   * the destination module. If you want to handle Message, override this
   * function with your own handler. YOU MUST DEALLOCATE EVERY SUCCESSFUL
   * MESSAGE YOU ALLOCATED JUST HERE. INSTANT RESPONSE messages(return value of
   * messageReceived) are also deallocated here. SELF messages are also
   * deallocated here.
   *
   * @param to Destination of the Message(including [this]).
   * If you sent a message to yourself, this parameter would be [this].
   * @param message Message to be deallocated.
   * This is the message you allocated.
   * @param response If the message is successfully processed,
   * the receiver may give an instance response by return value.
   * Response message is deallocated by the responder's messageFinished, so
   * DO NOT DEALLOCATE THE RESPONSE MESSAGE.
   *
   * @note Using default implementation is forbidden.
   * If you use send any message, you must override this function with your own
   * implementation.
   */
  virtual void messageFinished(const ModuleID to, Message message,
                               Module::MessageBase &response) {
    (void)to;
    (void)message;
    (void)response;
    assert(0);
  }

  /**
   * @brief This is a callback function called by the System.
   * This function is automatically called when the message is cancelled before
   * it is processed. This function is called AT THE TIME WHEN THE MESSAGE WAS
   * SUPPOSED TO BE SENT. If you want to handle Message, override this function
   * with your own handler. YOU MUST DEALLOCATE EVERY CANCELLED MESSAGE YOU
   * ALLOCATED JUST HERE.
   *
   * @param to Destination of the Message(including [this]).
   * If you sent a message to yourself, this parameter would be [this].
   * @param message Message to be deallocated.
   * This is the message you allocated.
   *
   * @note Using default implementation is forbidden.
   * If you use send any message, you must override this function with your own
   * implementation. This function is similar to messageFinished except its
   * response message is always null.
   *
   * @see messageFinished
   */
  virtual void messageCancelled(const ModuleID to, Message message) {
    (void)to;
    (void)message;
    assert(0);
  }

  /**
   * @brief Send a Message to other Module.
   * Every message has its own delay before it is actually sent.
   * The System guarantees the total ordering of all delayed messages in the
   * System.
   *
   * @param to Destination Module. You can send a Message to yourself (this).
   * @param message Message to be sent. YOU MUST ALLOCATE THE MESSAGE TO BE
   * SENT.
   * @param timeAfter Delay of this message. The receiver will receive the
   * Message at [current time] + [delay].
   * @return UUID of generated message. This UUID is used for cancellation of
   * the message.
   *
   * @note You cannot override this function.
   * @see messageFinished and messageReceived for allocate/deallocate
   * convention.
   */
  virtual UUID sendMessage(const ModuleID to, Module::Message message,
                           Time timeAfter) final;

  /**
   * @brief Send a Message to self
   * Every message has its own delay before it is actually sent.
   * The System guarantees the total ordering of all delayed messages in the
   * System.
   *
   * @param message Message to be sent. YOU MUST ALLOCATE THE MESSAGE TO BE
   * SENT.
   * @param timeAfter Delay of this message. The receiver will receive the
   * Message at [current time] + [delay].
   * @return UUID of generated message. This UUID is used for cancellation of
   * the message.
   *
   * @note You cannot override this function.
   * @see messageFinished and messageReceived for allocate/deallocate
   * convention.
   */
  virtual UUID sendMessageSelf(Module::Message message, Time timeAfter) final;

  /**
   * @brief Cancel the raised Message.
   * If a message is not actually sent yet, you can cancel the message.
   * If the message is already sent, this function has no effect.
   *
   * @param messageID Unique ID that represents the target Message to be
   * cancelled.
   * @return Whether the cancellation is successful.
   *
   * @note You cannot override this function.
   * @see sendMessage
   */
  virtual bool cancelMessage(UUID messageID) final;

  friend class System;
};

} // namespace E

#endif /* E_MODULE_HPP_ */


text:
require 'spec_helper'

describe Recruiter::HeaderHelper, type: :helper do
end


text:
import config
import pygsheets
from oauth2client.service_account import ServiceAccountCredentials

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    **config.GOOGLE_SERVICE_ACCOUNT_CONFIG)  # https://github.com/nithinmurali/pygsheets/issues/100#issuecomment-322970227
google_client = pygsheets.authorize(credentials=credentials, no_cache=True)
spreadsheet = google_client.open_by_key(config.GOOGLE_SPREADSHEET_KEY)


text:
Authorised

Each of the following links should lead to a valid page

Unrestricted method in a controller that requires a role holder to be present

A method with specific restrictions which the role holder has

Unauthorised

Each of the following links should lead to a forbidden page

A method with specific restrictions which the role holder doesn't have

Tags

The following box should contain text

    #{deadbolt.roleHolderPresent}
    blah blah blah
    #{/deadbolt.roleHolderPresent}


text:
var React = require('react');
var PropTypes = require('prop-types');
var moment = require('moment');

module.exports = React.createClass({
  displayName: 'Tweet',

  propTypes: {
    tweet: PropTypes.object.isRequired
  },

  getStyles: function() {
    return {
      avatar: {
        width: '32px',
        border: '1px solid gray'
      },
      imageContainer: {
        display: 'inline-block',
        verticalAlign: 'top',
        width: '32px'
      },
      contentContainer: {
        display: 'inline-block',
        marginLeft: '8px',
        maxWidth: '85%'
      },
      title: {
        lineHeight: '32px',
        display: 'inline-block'
      },
      text: {
        marginBottom: '5px'
      },
      timestamp: {
        display: 'inline-block',
        marginLeft: '8px',
        color: '#999',
        fontSize: '14px'
      }
    }
  },

  render: function () {
    var styles = this.getStyles();
    var tweet = this.props.tweet;
    var timestamp = moment(tweet.data.createdAt).fromNow().split(' ago')[0];

    return (

            Nickname

            {'- ' + timestamp}

            {tweet.data.text}

    );
  }
});


text:
<?php

/*
 * Class Name: wp_bootstrap_navlist_walker
 * GitHub URI: https://github.com/twittem/wp-bootstrap-navlist-walker
 * Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager.
 * Version: 1.0 RC1
 * Author: Edward McIntyre - @twittem
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

class wp_bootstrap_navlist_walker extends Walker_Nav_Menu {

	/**
	 * @see Walker::start_lvl()
	 * @since 3.0.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int $depth Depth of page. Used for padding.
	 */
	public function start_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat( "\t", $depth );
		$output .= "\n$indent

\n";
	}

	/**
	 * Ends the list of after the elements are added.
	 *
	 * @see Walker::end_lvl()
	 *
	 * @since 3.0.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int    $depth  Depth of menu item. Used for padding.
	 * @param array  $args   An array of arguments. @see wp_nav_menu()
	 */
	function end_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat("\t", $depth);
		$output .= 0 == $depth ? "$indent
\n" : "$indent

\n";
	}

	/**
	 * @see Walker::start_el()
	 * @since 3.0.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param object $item Menu item data object.
	 * @param int $depth Depth of menu item. Used for padding.
	 * @param int $current_page Menu item ID.
	 * @param object $args
	 */
	public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

		// Check if the link it disables Disabled, Active or regular menu item.
		if ( stristr( $item->attr_title, 'disabled' ) )
			$output .= $indent . '
title ) . '">' . esc_attr( $item->title ) . '';
		else
			$output .= $item->current ? $indent . '
' : $indent . '
';

		$atts = array();
		$atts['title']  = ! empty( $item->title )	? $item->title	: '';
		$atts['target'] = ! empty( $item->target )	? $item->target	: '';
		$atts['rel']    = ! empty( $item->xfn )		? $item->xfn	: '';
		$atts['href'] 	= ! empty( $item->url ) 	? $item->url : '';

		$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );

		$attributes = '';
		foreach ( $atts as $attr => $value ) {
			if ( ! empty( $value ) ) {
				$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
				$attributes .= ' ' . $attr . '="' . $value . '"';
			}
		}

		/*
		 * el-icons
		 * ===========
		 * We check to see there is a value in the attr_title property. If the attr_title
		 * property is NOT null or divider we apply it as the class name for the el-icon.
		 */
		$item_output = '';

		if ( ! empty( $item->attr_title ) )
			$item_output .= 'attr_title ) . '"> ';
		else
			$item_output .= '';

		$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
		$item_output .= '';
		$item_output .= $args->after;

		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}

	/**
	 * Traverse elements to create list from elements.
	 *
	 * @see Walker::start_el()
	 * @since 2.5.0
	 *
	 * @param object $element Data object
	 * @param array $children_elements List of elements to continue traversing.
	 * @param int $max_depth Max depth to traverse.
	 * @param int $depth Depth of current element.
	 * @param array $args
	 * @param string $output Passed by reference. Used to append additional content.
	 * @return null Null on failure with no changes to parameters.
	 */
	public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
        if ( ! $element )
            return;

        //If parent is not current item, don't output children
        if( ! $element->current )
        	parent::unset_children( $element, $children_elements );

        parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }

	/**
	 * Menu Fallback
	 * =============
	 * If this function is assigned to the wp_nav_menu's fallback_cb variable
	 * and a manu has not been assigned to the theme location in the WordPress
	 * menu manager the function with display nothing to a non-logged in user,
	 * and will add a link to the WordPress menu manager if logged in as an admin.
	 *
	 * @param array $args passed from the wp_nav_menu function.
	 *
	 */
	public static function fallback( $args ) {
		if ( current_user_can( 'manage_options' ) ) {

			extract( $args );

			$output = null;

			if ( $container ) {
				$output = '<' . $container;

				if ( $container_id )
					$output .= ' id="' . $container_id . '"';

				if ( $container_class )
					$output .= ' class="' . $container_class . '"';

				$output .= '>';
			}

			$output .= '
';
			$output .= '
Add a menu
';
			$output .= '
';

			if ( $container )
				$output .= '</' . $container . '>';

			echo $output;
		}
	}
}


text:
package org.genericsystem.reactor.annotations;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.BiConsumer;

import org.genericsystem.reactor.Context;
import org.genericsystem.reactor.Tag;
import org.genericsystem.reactor.annotations.BindText.BindTextGenericProcessor;
import org.genericsystem.reactor.annotations.BindText.BindTextProcessor;
import org.genericsystem.reactor.annotations.BindText.BindTexts;
import org.genericsystem.reactor.context.TextBinding;
import org.genericsystem.reactor.context.TextBinding.GENERIC_STRING;
import org.genericsystem.reactor.contextproperties.TextPropertyDefaults;
import org.genericsystem.reactor.extended.ExtendedAnnotationsManager.IGenericAnnotationProcessor;
import org.genericsystem.reactor.extended.ExtendedRootTag.GTag;
import org.genericsystem.reactor.extended.ExtendedRootTag.GTagAnnotation;
import org.genericsystem.reactor.extended.ExtendedRootTag.GTagAnnotationContent;
import org.genericsystem.reactor.gscomponents.TagImpl;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Repeatable(BindTexts.class)
@Process(BindTextProcessor.class)
@GenericProcess(BindTextGenericProcessor.class)
public @interface BindText {
	Class<? extends TagImpl>[] path() default {};

	Class<? extends TextBinding> value() default GENERIC_STRING.class;

	int[] pos() default {};

	@Retention(RetentionPolicy.RUNTIME)
	@Target({ ElementType.TYPE })
	public @interface BindTexts {
		BindText[] value();
	}

	public static class BindTextProcessor implements BiConsumer<Annotation, Tag> {

		@Override
		public void accept(Annotation annotation, Tag tag) {
			tag.getRootTag().processBindText(tag, ((BindText) annotation).value());
		}
	}

	public static class BindTextGenericProcessor implements IGenericAnnotationProcessor {

		@Override
		public void setAnnotation(GTag gTag, Annotation annotation) {
			gTag.setAnnotation(BindText.class, null, ((BindText) annotation).value().getName(), ((BindText) annotation).path(), ((BindText) annotation).pos());
		}

		@Override
		public void onRemove(Tag tag, Context context, GTagAnnotation gTagAnnotation, GTagAnnotationContent annotationContent) {
			tag.getDomNodeTextProperty(context).unbind();
			context.getAttributes(tag).remove(TextPropertyDefaults.TEXT_BINDING);
			tag.getDomNodeTextProperty(context).setValue(null);
		}

		@Override
		public void onAdd(Tag tag, Context context, GTagAnnotation gTagAnnotation, GTagAnnotationContent annotationContent) {
			tag.getRootTag().processBindText(tag, context, (Class<? extends TextBinding>) annotationContent.getClassContent());
		}
	}
}


text:
"""The Terraformer model -- highly configurable version for research.

Implements the Terraformer model, introduced in the paper ...
"""

import functools
from trax import layers as tl
from trax.fastmath import numpy as jnp
from trax.models.reformer import reformer
from trax.models.research import configurable_transformer as ct
from trax.models.research import transformer2 as t2

# Layers are always CamelCase, but functions in general are snake_case
# pylint: disable=invalid-name

def ConfigurableTerraformer(input_vocab_size,
                            output_vocab_size=None,
                            d_model=512,
                            d_ff=2048,
                            d_attention_key=None,
                            d_attention_value=None,
                            n_encoder_layers=6,
                            n_decoder_layers=6,
                            n_heads=8,
                            dropout=0.1,
                            max_len=2048,
                            encoder_attention_type=tl.SelfAttention,
                            encoder_decoder_attention_type=tl.SelfAttention,
                            pos_type='fixed-base',
                            pos_axial_shape=(),
                            pos_d_axial_embs=None,
                            pos_start_from_zero_prob=1.0,
                            pos_max_offset_to_add=0,
                            ff_activation=tl.Relu,
                            ff_use_sru=0,
                            ff_chunk_size=0,
                            ff_dropout=None,
                            ff_sparsity=0,
                            loss_sparsity_type='mult',
                            loss_sparsity=0,
                            loss_d_lowrank=0,
                            loss_sparsity_prob=None,
                            attention_chunk_size=0,
                            n_layers_forget=0,
                            forget_dense=True,
                            n_decoder_attention_layers=2,
                            use_bfloat16=False,
                            reversible_encoder=False,
                            use_two_swaps_per_encoder_block=True,
                            center_layernorm=True,
                            half_before_layer=None,
                            double_after_layer=None,
                            mode='train'):
  """Returns a highly configurable Terraformer encoder-decoder model.

  This model maps paired text sequences (source and target) to float-valued
  losses. If ``input_vocab_size`` is not ``None``, the layer takes
  two input sequences:

    - inputs (2):

        - source: 2-D int array representing a batch of text strings via token
          IDs plus padding markers; shape is `(batch_size, sequence_length)`,
          where sequence_length <= ``max_len``. Array elements are in
          ``range(input_vocab_size)``, and 0 values mark padding positions.

        - target: 2-D int array representing a batch of text strings via token
          IDs plus padding markers; shape is `(batch_size, sequence_length)`,
          where sequence_length <= ``max_len``. Array elements are in
          ``range(output_vocab_size)``, and 0 values mark padding positions.

    - output: 1-D float array of losses; shape is `(batch_size)`.

  If ``input_vocab_size`` is ``None``, the layer takes three input sequences:

    - inputs (3):

        - source: 3-D float array representing a batch of already-embedded text
          strings; shape is `(batch_size, sequence_length, d_model)`, where
          sequence_length <= ``max_len``.

        - mask: 2-D int array representing active versus masked positions; 0
          values mark masked (padding) positions.

        - target: 2-D int array representing a batch of text strings via token
          IDs plus padding markers; shape is `(batch_size, sequence_length)`,
          where sequence_length <= ``max_len``. Array elements are in
          ``range(output_vocab_size)``, and 0 values mark padding positions.

    - output: 1-D float array of losses; shape is `(batch_size)`.

  Args:
    input_vocab_size: Input vocabulary size -- each element of the input tensor
        should be an integer in ``range(vocab_size)``. These integers typically
        represent token IDs from a vocabulary-based tokenizer.
    output_vocab_size: If specified, gives the vocabulary size for the targets;
        if ``None``, then input and target integers (token IDs) are assumed to
        come from the same vocabulary.
    d_model: Last/innermost dimension of activation arrays at most points in
        the model, including the initial embedding output.
    d_ff: Last/innermost dimension of special (typically wider)
        :py:class:`Dense` layer in the feedforward part of each encoder block.
    d_attention_key: Depth of key vectors in each attention head.
    d_attention_value: Depth of value vectors in each attention head.
    n_encoder_layers: Number of encoder blocks.
    n_decoder_layers: Number of decoder blocks.
    n_heads: Number of attention heads.
    dropout: Stochastic rate (probability) for dropping an activation value
        when applying dropout within encoder/decoder blocks. The same rate is
        also used for attention dropout in encoder/decoder blocks.
    max_len: Maximum symbol length for positional encoding.
    encoder_attention_type: Type of attention to use in the encoder; must be
        an attention-type subclass of :py:class:`trax.layers.Layer`.
    encoder_decoder_attention_type: Type of attention to use in the decoder;
        must be an attention-type subclass of :py:class:`trax.layers.Layer`.
    pos_type: String indicating the type of positional embeddings to use.
    pos_axial_shape: Shape (tuple of ints) to use for the axial position
      encoding. If unset, axial position encoding is disabled.
    pos_d_axial_embs: Tuple of ints specifying the depth of position embedding
        for each axis. Tuple length must match ``pos_axial_shape``, and values
        must sum to ``d_model``.
    pos_start_from_zero_prob: Stochastic rate (probability) for starting
        positional encoding at position 0 during training. If 1.0, always start
        from position 0; if < 1.0, the non-zero starts will be uniformly
        distributed up to ``pos_max_offset_to_add``.
    pos_max_offset_to_add: Maximum offset to add to positions during training
        when randomizing. This offset plus input length must be less than
        ``max_len`` for all training examples.
    ff_activation: Type of activation function at the end of each block; must
        be an activation-type subclass of :py:class:`trax.layers.Layer`.
    ff_use_sru: If > 0, use this number of SRU layers in place of feedforward
        layers.
    ff_chunk_size: If > 0, chunk each feedforward layer into chunks of this
        size.
    ff_dropout: Stochastic rate (probability) for dropping an activation value
        at feedforward nonlinearities.
    ff_sparsity: If > 0, use sparse feedforward blocks with this level of
        sparsity.
    loss_sparsity_type: String indicating the type of sparsity to used in loss
        layer; see :py:class:`SparseDenseWithOptions` for options. If ``None``,
        use no sparsity.
    loss_sparsity: If > 0, use this level of sparsity in the loss layer.
    loss_d_lowrank: If > 0, use a (low-rank) intermediate layer, with this
        dimension, in the loss.
    loss_sparsity_prob: Stochastic rate (probability) for using the sparse
        version of the loss. If ``None``, use the sparse version exclusively.
    attention_chunk_size: If > 0, compute attention using chunks of this size.
    n_layers_forget: How often to have a forgetting block between layers.
    forget_dense: If True, use :py:class:`Dense` instances as forget layers;
        else use no-ops.
    n_decoder_attention_layers: Number of attention layers in a decoder block.
    use_bfloat16: If True, use bfloat16 for weights; else use float32.
    reversible_encoder: If True, make the encoder be reversible.
    use_two_swaps_per_encoder_block: If True, ensure that there is a an even
        number of swaps across the encoder.
    center_layernorm: If True, use centering in :py:class:`LayerNorm` (the
        default); else omit centering (which is known as RMS normalization).
    half_before_layer: If not None, specifies an n'th layer such that all
        layers before the n'th use half the normal values for ``d_model`` and
        ``d_ff``.
    double_after_layer: If not None, specifies an n'th layer such that all
        layers after the n'th use double the normal values for ``d_model`` and
        ``d_ff``.
    mode: If ``'train'``, include dropout in each encoder/decoder block; else
        dropout layers have no effect.

  Returns:
    A Terraformer encoder-decoder as a layer that maps from target and source
    text sequences to a scalar loss.
  """
  if mode == 'predict':
    portal_mask = _PortalInput()
  else:
    portal_mask = None

  # Set default dimensions for attention head key and value sizes.
  if (d_model / 2) % n_heads != 0:
    raise ValueError(f'n_heads ({n_heads}) must divide d_model/2 ({d_model/2})')
  if d_attention_key is None:
    d_attention_key = d_model // n_heads
  if d_attention_value is None:
    d_attention_value = d_model // n_heads

  # Set values of d_model, d_ff and d_qkv for the first stage.
  d_model1, d_ff1 = d_model, d_ff
  d_attention_key1, d_attention_value1 = d_attention_key, d_attention_value
  if half_before_layer:
    d_model1, d_ff1 = d_model / 2, d_ff / 2
    d_attention_key1 = d_attention_key / 2
    d_attention_value1 = d_attention_value / 2

  # Set values of d_model, d_ff and d_qkv for the final stage.
  d_model2, d_ff2 = d_model, d_ff
  d_attention_key2, d_attention_value2 = d_attention_key, d_attention_value
  if double_after_layer:
    d_model2, d_ff2 = d_model * 2, d_ff * 2
    d_attention_key2 = d_attention_key * 2
    d_attention_value2 = d_attention_value * 2

  # Vector embeddings.
  in_encoder, out_encoder, output_vocab_size = (
      ct.EmbeddingAndPositionalEncodings(
          input_vocab_size,
          d_model1,
          mode,
          dropout,
          [-2],  # dropout_shared_axes
          max_len,
          output_vocab_size=output_vocab_size,
          pos_type=pos_type,
          pos_axial_shape=pos_axial_shape,
          pos_d_axial_embs=pos_d_axial_embs,
          pos_start_from_zero_prob=pos_start_from_zero_prob,
          pos_max_offset_to_add=pos_max_offset_to_add,
          use_bfloat16=use_bfloat16)
  )

  def _EncoderBlock():
    return reformer.EncoderBlock(
        d_model1,
        d_ff1,
        n_heads,
        encoder_attention_type,
        dropout=dropout,
        ff_activation=ff_activation,
        ff_dropout=ff_dropout,
        ff_use_sru=ff_use_sru,
        ff_chunk_size=ff_chunk_size,
        ff_sparsity=ff_sparsity,
        attention_chunk_size=attention_chunk_size,
        center_layernorm=center_layernorm,
        use_bfloat16=use_bfloat16,
        use_two_swaps_per_block=use_two_swaps_per_encoder_block,
        mode=mode)

  def _Encoder():  # vec_e mask_e tok_e tok_d tok_d
    layers = [
        tl.ReversibleSelect([0, 0]),
        _ReversibleSerialForget(
            [_EncoderBlock() for _ in range(n_encoder_layers)],
            d_model1,
            n_layers_forget,
            forget_dense)
    ]
    if not reversible_encoder:
      layers += [
          _XYAvg(),
          tl.Dense(d_model1, use_bfloat16=use_bfloat16),
          tl.LayerNorm(),
      ]
    if mode == 'predict':
      return tl.Cache(tl.Serial(layers))
    else:
      return tl.Serial(layers)

  if mode == 'predict':
    # TODO(jaszczur): Remove temporary fix of Terraformer padding in predict.
    # In predict mode Terraformer needs masking for merged encoder-decoder
    # sequence. This monkey patches the layer with a mask to neccessary places.
    # This shouldn't be a permanent solution - mask should be passed through
    # the stack and all the layers.
    tl.attention.DotProductCausalAttention.monkey_patched_mask = (
        lambda x: portal_mask)
    tl.research.sparsity._RememberPad.monkey_patched_mask = (  # pylint: disable=protected-access
        lambda x: portal_mask)
    originalScanSRUCell = tl.rnn.ScanSRUCell
    tl.rnn.ScanSRUCell = functools.partial(tl.rnn.ScanSRUCell,
                                           monkey_patched_mask=portal_mask)

  decoder_blocks = []

  if isinstance(encoder_decoder_attention_type, (tuple, list)):
    assert n_decoder_layers % len(encoder_decoder_attention_type) == 0
  else:
    encoder_decoder_attention_type = [encoder_decoder_attention_type]
  for layer_idx in range(n_decoder_layers):
    layer_attention_type = encoder_decoder_attention_type[
        layer_idx % len(encoder_decoder_attention_type)]
    # Grow d_model, d_ff, and d_qkv if requested.
    d_m, d_f, d_k, d_v = d_model1, d_ff1, d_attention_key1, d_attention_value1
    if half_before_layer and layer_idx >= half_before_layer:
      d_m, d_f, d_k, d_v = d_model, d_ff, d_attention_key, d_attention_value
    if double_after_layer and layer_idx > double_after_layer:
      d_m, d_f, d_k, d_v = d_model2, d_ff2, d_attention_key2, d_attention_value2
    decoder_block = reformer.DecoderBlock(
        d_m, d_f, d_k, d_v, n_heads,
        attention_type=layer_attention_type,
        dropout=dropout,
        ff_activation=ff_activation,
        ff_dropout=ff_dropout,
        ff_use_sru=ff_use_sru,
        ff_chunk_size=ff_chunk_size,
        ff_sparsity=ff_sparsity,
        attention_chunk_size=attention_chunk_size,
        n_attention_layers=n_decoder_attention_layers,
        center_layernorm=center_layernorm,
        use_bfloat16=use_bfloat16,
        mode=mode)
    decoder_blocks.append(decoder_block)
    if half_before_layer and layer_idx == half_before_layer - 1:
      decoder_blocks.append(tl.ReversibleConcatenatePair())
    if double_after_layer and layer_idx == double_after_layer:
      decoder_blocks.append(tl.ReversibleConcatenatePair())

  if mode == 'predict':
    # After initializing the decoder we can revert to original state of
    # previously monkey-patched classes/functions.
    tl.attention.DotProductCausalAttention.monkey_patched_mask = (
        lambda x: None)
    tl.research.sparsity._RememberPad.monkey_patched_mask = (lambda x: None)  # pylint: disable=protected-access
    tl.rnn.ScanSRUCell = originalScanSRUCell

  def _Loss():
    return tl.SparseDenseWithOptions(
        output_vocab_size,
        d_input=d_model2,
        sparsity_type=loss_sparsity_type,
        sparsity=loss_sparsity,
        d_lowrank=loss_d_lowrank,
        prob_sparse=loss_sparsity_prob,
        use_bfloat16=use_bfloat16,
        mode=mode)

  def _enc_dec_concat():
    """Layers to merge encoder and decoder."""
    if reversible_encoder:
      return [
          tl.ReversibleSelect([0, 1, 4, 2, 3]),  # v_e v_d mask_e tok_e tok_d
          t2.ConcatWithPadding2(mode=mode),      # v_ed v_ed tok_e tok_d
      ]
    else:
      return [
          tl.ReversibleSelect([0, 3, 1, 2]),     # v_e v_d mask_e tok_e tok_d
          t2.ConcatWithPadding(mode=mode),       # v_ed tok_e tok_d
          tl.ReversibleSelect([0, 0]),           # v_ed v_ed tok_e tok_d
      ]

  def _inp_layers():
    if input_vocab_size is not None:
      return tl.AssertFunction(
          'bl,br->bld,bl,bl,br',  # b: batch, l/r: enc/dec length, d: vec depth
          tl.Serial(  # tok_e tok_d
              tl.Select([0, 0, 0, 1]),
              tl.Parallel(in_encoder, [tl.PaddingMask(),
                                       _RemoveAxes12()])
          ))  # vec_e mask_e tok_e tok_d
    else:
      # Input in this case is vec_e, mask_e, tok_d. Where all downstream
      # operations expect tok_e, we give it instead mask_e, expecting that
      # downstream ops only are looking for padding/not padding.
      return tl.AssertFunction(
          'blf,bl,br->bld,bl,bl,br',  # f: in-feature depth, d: out-vector depth
          tl.Serial(  # vec_e mask_e tok_d
              tl.Select([0, 1, 1, 2]),
              tl.Parallel(in_encoder, [], _AsTokenIDs())
          ))  # vec_e mask_e tok_e tok_d

  # Assemble and return the model.
  return tl.Serial(
      _inp_layers(),               # vec_e mask_e tok_e tok_d
      tl.Parallel([], portal_mask),

      tl.Select([0, 1, 2, 3, 3]),  # Copy decoder tokens for use in loss.

      # Embed in and out tokens; done together as weights may be shared.
      tl.Parallel([], [], [], [tl.ShiftRight(mode=mode),
                               out_encoder]),  # vec_e mask_e tok_e vec_d tok_d

      # Encode; then concat encoder and decoder, given encoder mask.
      _Encoder(),                             # vec_e mask_e tok_e vec_d tok_d
      _enc_dec_concat(),

      # Run decoder blocks.
      _ReversibleSerialForget(decoder_blocks, d_model2, n_layers_forget,
                              forget_dense),  # vec_ed1 vec_ed2 tok_e tok_d
      _XYAvg(),                               # vec_ed tok_e tok_d
      tl.LayerNorm(),                         # vec_ed tok_e tok_d

      # Separate out the encoder part from the concatenated vector,
      # then compute loss.
      tl.Select([0, 1, 2, 2]),                        # vec_ed tok_e tok_d tok_d
      t2.StripFromConcatenateWithPadding(mode=mode),  # vec_d tok_d
      _Loss(),  # vec_d tok_d
  )

def _InsertAxes12():
  """Returns a layer that inserts two internal size-1 axes into an array."""
  return tl.Fn('InsertAxes12',
               lambda x: jnp.reshape(x, (x.shape[0], 1, 1, x.shape[1])))

def _RemoveAxes12():
  """Returns a layer that removes two internal size-1 axes from an array."""
  return tl.Fn('RemoveAxes12', lambda x: jnp.squeeze(x, (1, 2)))

def _AsTokenIDs():
  """Returns a layer that makes mask values look like token ID ints."""
  return tl.Fn('AsTokenIDs', lambda x: x.astype(jnp.int32))

def _XYAvg():
  """Returns a layer that computes the element-wise average of two arrays."""
  return tl.Fn('XYAvg', lambda x, y: (x + y) / 2.0)

def _ReversibleSerialForget(layers, d_model, n_layers, forget_dense=True):
  """ReversibleSerial but with a forgetting block every n_layers."""
  if not n_layers or len(layers) <= n_layers + 1:
    return tl.ReversibleSerial(layers)
  layers1, layers2 = layers[:n_layers], layers[n_layers:]

  if forget_dense:
    forgetting_layer = tl.Serial(
        _XYAvg(),
        tl.Dense(d_model),
        tl.Dup(),
    )
  else:
    forgetting_layer = tl.Select([0, 1])

  return tl.Serial(
      tl.ReversibleSerial(layers1),
      forgetting_layer,
      _ReversibleSerialForget(layers2, d_model, n_layers, forget_dense)
  )

def _ConvertToNaNsOnAnyZero():
  def _convert_to_nans(x, y):
    # if all values in y are non-zeros, return x; otherwise return 0s
    return jnp.where(jnp.all(y, keepdims=False), x, x/0.), y
  return tl.Fn('ConvertToNaNsOnAnyZero', _convert_to_nans, n_out=2)

class _PortalInput(tl.Layer):
  """Portal input for monkey-patching of mask in predict mode."""

  def __init__(self):
    super().__init__(name='_PortalInput', n_out=1, n_in=1)
    self._portal_output = _PortalOutput(self)

  def forward(self, x):
    if isinstance(x, (list, tuple)):
      x = x[0]
    self.state = (x,)
    return x

  def init_weights_and_state(self, input_signature):
    """Initializes this layer's weights."""
    if isinstance(input_signature, (list, tuple)):
      input_signature = input_signature[0]
    self.state = (jnp.zeros(input_signature.shape),)

  def get_value(self):
    return self.state[0]

  def get_layer(self):
    return self._portal_output

class _PortalOutput(tl.Layer):
  """Portal input for monkey-patching of mask in predict mode."""

  def __init__(self, portal_input):
    super().__init__(name='_PortalOutput', n_out=1, n_in=0)
    self._portal_input = portal_input

  def forward(self, x):
    return self._portal_input.get_value()

  def get_value(self):
    return self._portal_input.get_value()


text:
package org.apache.pinot.broker.routing.timeboundary;

public class TimeBoundaryInfo {
  private final String _timeColumn;
  private final String _timeValue;

  public TimeBoundaryInfo(String timeColumn, String timeValue) {
    _timeColumn = timeColumn;
    _timeValue = timeValue;
  }

  public String getTimeColumn() {
    return _timeColumn;
  }

  public String getTimeValue() {
    return _timeValue;
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=trait.SubAssign.html">

Redirecting to trait.SubAssign.html...


text:
		{{options.label || 'Number'}}
		{{options.required ? '*' : ''}}

	<input type="number"
		   id="{{id}}"
		   placeholder="{{options.placeholder}}"
		   aria-describedby="{{id}}_description"
		   ng-required="options.required"
		   ng-disabled="options.disabled"
		   min="{{options.min}}"
		   max="{{options.max}}"
		   ng-minlength="{{options.minlength}}"
		   ng-maxlength="{{options.maxlength}}"
		   ng-model="value">

{{options.description}}