text:
package org.elasticsearch.http.netty;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.netty.NettyStaticSetup;
import org.elasticsearch.common.netty.OpenChannelsHandler;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.network.NetworkUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.NetworkExceptionHelper;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.http.*;
import org.elasticsearch.http.HttpRequest;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.transport.BindTransportException;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.*;
import org.jboss.netty.handler.timeout.ReadTimeoutException;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

import static org.elasticsearch.common.network.NetworkService.TcpSettings.*;
import static org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory;

/**
 *
 */
public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpServerTransport> implements HttpServerTransport {

    static {
        NettyStaticSetup.setup();
    }

    private final NetworkService networkService;

    final ByteSizeValue maxContentLength;
    final ByteSizeValue maxInitialLineLength;
    final ByteSizeValue maxHeaderSize;
    final ByteSizeValue maxChunkSize;

    private final int workerCount;

    private final boolean blockingServer;

    final boolean compression;

    private final int compressionLevel;

    final boolean resetCookies;

    private final String port;

    private final String bindHost;

    private final String publishHost;

    private final Boolean tcpNoDelay;

    private final Boolean tcpKeepAlive;

    private final Boolean reuseAddress;

    private final ByteSizeValue tcpSendBufferSize;
    private final ByteSizeValue tcpReceiveBufferSize;
    private final ReceiveBufferSizePredictorFactory receiveBufferSizePredictorFactory;

    final ByteSizeValue maxCumulationBufferCapacity;
    final int maxCompositeBufferComponents;

    private volatile ServerBootstrap serverBootstrap;

    private volatile BoundTransportAddress boundAddress;

    private volatile Channel serverChannel;

    OpenChannelsHandler serverOpenChannels;

    private volatile HttpServerAdapter httpServerAdapter;

    @Inject
    public NettyHttpServerTransport(Settings settings, NetworkService networkService) {
        super(settings);
        this.networkService = networkService;

        if (settings.getAsBoolean("netty.epollBugWorkaround", false)) {
            System.setProperty("org.jboss.netty.epollBugWorkaround", "true");
        }

        ByteSizeValue maxContentLength = componentSettings.getAsBytesSize("max_content_length", settings.getAsBytesSize("http.max_content_length", new ByteSizeValue(100, ByteSizeUnit.MB)));
        this.maxChunkSize = componentSettings.getAsBytesSize("max_chunk_size", settings.getAsBytesSize("http.max_chunk_size", new ByteSizeValue(8, ByteSizeUnit.KB)));
        this.maxHeaderSize = componentSettings.getAsBytesSize("max_header_size", settings.getAsBytesSize("http.max_header_size", new ByteSizeValue(8, ByteSizeUnit.KB)));
        this.maxInitialLineLength = componentSettings.getAsBytesSize("max_initial_line_length", settings.getAsBytesSize("http.max_initial_line_length", new ByteSizeValue(4, ByteSizeUnit.KB)));
        // don't reset cookies by default, since I don't think we really need to
        // note, parsing cookies was fixed in netty 3.5.1 regarding stack allocation, but still, currently, we don't need cookies
        this.resetCookies = componentSettings.getAsBoolean("reset_cookies", settings.getAsBoolean("http.reset_cookies", false));
        this.maxCumulationBufferCapacity = componentSettings.getAsBytesSize("max_cumulation_buffer_capacity", null);
        this.maxCompositeBufferComponents = componentSettings.getAsInt("max_composite_buffer_components", -1);
        this.workerCount = componentSettings.getAsInt("worker_count", EsExecutors.boundedNumberOfProcessors(settings) * 2);
        this.blockingServer = settings.getAsBoolean("http.blocking_server", settings.getAsBoolean(TCP_BLOCKING_SERVER, settings.getAsBoolean(TCP_BLOCKING, false)));
        this.port = componentSettings.get("port", settings.get("http.port", "9200-9300"));
        this.bindHost = componentSettings.get("bind_host", settings.get("http.bind_host", settings.get("http.host")));
        this.publishHost = componentSettings.get("publish_host", settings.get("http.publish_host", settings.get("http.host")));
        this.tcpNoDelay = componentSettings.getAsBoolean("tcp_no_delay", settings.getAsBoolean(TCP_NO_DELAY, true));
        this.tcpKeepAlive = componentSettings.getAsBoolean("tcp_keep_alive", settings.getAsBoolean(TCP_KEEP_ALIVE, true));
        this.reuseAddress = componentSettings.getAsBoolean("reuse_address", settings.getAsBoolean(TCP_REUSE_ADDRESS, NetworkUtils.defaultReuseAddress()));
        this.tcpSendBufferSize = componentSettings.getAsBytesSize("tcp_send_buffer_size", settings.getAsBytesSize(TCP_SEND_BUFFER_SIZE, TCP_DEFAULT_SEND_BUFFER_SIZE));
        this.tcpReceiveBufferSize = componentSettings.getAsBytesSize("tcp_receive_buffer_size", settings.getAsBytesSize(TCP_RECEIVE_BUFFER_SIZE, TCP_DEFAULT_RECEIVE_BUFFER_SIZE));

        long defaultReceiverPredictor = 512 * 1024;
        if (JvmInfo.jvmInfo().mem().directMemoryMax().bytes() > 0) {
            // we can guess a better default...
            long l = (long) ((0.3 * JvmInfo.jvmInfo().mem().directMemoryMax().bytes()) / workerCount);
            defaultReceiverPredictor = Math.min(defaultReceiverPredictor, Math.max(l, 64 * 1024));
        }

        // See AdaptiveReceiveBufferSizePredictor#DEFAULT_XXX for default values in netty..., we can use higher ones for us, even fixed one
        ByteSizeValue receivePredictorMin = componentSettings.getAsBytesSize("receive_predictor_min", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor)));
        ByteSizeValue receivePredictorMax = componentSettings.getAsBytesSize("receive_predictor_max", componentSettings.getAsBytesSize("receive_predictor_size", new ByteSizeValue(defaultReceiverPredictor)));
        if (receivePredictorMax.bytes() == receivePredictorMin.bytes()) {
            receiveBufferSizePredictorFactory = new FixedReceiveBufferSizePredictorFactory((int) receivePredictorMax.bytes());
        } else {
            receiveBufferSizePredictorFactory = new AdaptiveReceiveBufferSizePredictorFactory((int) receivePredictorMin.bytes(), (int) receivePredictorMin.bytes(), (int) receivePredictorMax.bytes());
        }

        this.compression = settings.getAsBoolean("http.compression", false);
        this.compressionLevel = settings.getAsInt("http.compression_level", 6);

        // validate max content length
        if (maxContentLength.bytes() > Integer.MAX_VALUE) {
            logger.warn("maxContentLength[" + maxContentLength + "] set to high value, resetting it to [100mb]");
            maxContentLength = new ByteSizeValue(100, ByteSizeUnit.MB);
        }
        this.maxContentLength = maxContentLength;

        logger.debug("using max_chunk_size[{}], max_header_size[{}], max_initial_line_length[{}], max_content_length[{}], receive_predictor[{}->{}]",
                maxChunkSize, maxHeaderSize, maxInitialLineLength, this.maxContentLength, receivePredictorMin, receivePredictorMax);
    }

    public Settings settings() {
        return this.settings;
    }

    public void httpServerAdapter(HttpServerAdapter httpServerAdapter) {
        this.httpServerAdapter = httpServerAdapter;
    }

    @Override
    protected void doStart() throws ElasticsearchException {
        this.serverOpenChannels = new OpenChannelsHandler(logger);

        if (blockingServer) {
            serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")),
                    Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker"))
            ));
        } else {
            serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_boss")),
                    Executors.newCachedThreadPool(daemonThreadFactory(settings, "http_server_worker")),
                    workerCount));
        }

        serverBootstrap.setPipelineFactory(new MyChannelPipelineFactory(this));

        if (tcpNoDelay != null) {
            serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
        }
        if (tcpKeepAlive != null) {
            serverBootstrap.setOption("child.keepAlive", tcpKeepAlive);
        }
        if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
            serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes());
        }
        if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
            serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes());
        }
        serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
        serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
        if (reuseAddress != null) {
            serverBootstrap.setOption("reuseAddress", reuseAddress);
            serverBootstrap.setOption("child.reuseAddress", reuseAddress);
        }

        // Bind and start to accept incoming connections.
        InetAddress hostAddressX;
        try {
            hostAddressX = networkService.resolveBindHostAddress(bindHost);
        } catch (IOException e) {
            throw new BindHttpException("Failed to resolve host [" + bindHost + "]", e);
        }
        final InetAddress hostAddress = hostAddressX;

        PortsRange portsRange = new PortsRange(port);
        final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
        boolean success = portsRange.iterate(new PortsRange.PortCallback() {
            @Override
            public boolean onPortNumber(int portNumber) {
                try {
                    serverChannel = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber));
                } catch (Exception e) {
                    lastException.set(e);
                    return false;
                }
                return true;
            }
        });
        if (!success) {
            throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get());
        }

        InetSocketAddress boundAddress = (InetSocketAddress) serverChannel.getLocalAddress();
        InetSocketAddress publishAddress;
        try {
            publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), boundAddress.getPort());
        } catch (Exception e) {
            throw new BindTransportException("Failed to resolve publish address", e);
        }
        this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(boundAddress), new InetSocketTransportAddress(publishAddress));
    }

    @Override
    protected void doStop() throws ElasticsearchException {
        if (serverChannel != null) {
            serverChannel.close().awaitUninterruptibly();
            serverChannel = null;
        }

        if (serverOpenChannels != null) {
            serverOpenChannels.close();
            serverOpenChannels = null;
        }

        if (serverBootstrap != null) {
            serverBootstrap.releaseExternalResources();
            serverBootstrap = null;
        }
    }

    @Override
    protected void doClose() throws ElasticsearchException {
    }

    public BoundTransportAddress boundAddress() {
        return this.boundAddress;
    }

    @Override
    public HttpInfo info() {
        return new HttpInfo(boundAddress(), maxContentLength.bytes());
    }

    @Override
    public HttpStats stats() {
        OpenChannelsHandler channels = serverOpenChannels;
        return new HttpStats(channels == null ? 0 : channels.numberOfOpenChannels(), channels == null ? 0 : channels.totalChannels());
    }

    void dispatchRequest(HttpRequest request, HttpChannel channel) {
        httpServerAdapter.dispatchRequest(request, channel);
    }

    void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        if (e.getCause() instanceof ReadTimeoutException) {
            if (logger.isTraceEnabled()) {
                logger.trace("Connection timeout [{}]", ctx.getChannel().getRemoteAddress());
            }
            ctx.getChannel().close();
        } else {
            if (!lifecycle.started()) {
                // ignore
                return;
            }
            if (!NetworkExceptionHelper.isCloseConnectionException(e.getCause())) {
                logger.warn("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel());
                ctx.getChannel().close();
            } else {
                logger.debug("Caught exception while handling client http traffic, closing connection {}", e.getCause(), ctx.getChannel());
                ctx.getChannel().close();
            }
        }
    }

    static class MyChannelPipelineFactory implements ChannelPipelineFactory {

        private final NettyHttpServerTransport transport;

        private final HttpRequestHandler requestHandler;

        MyChannelPipelineFactory(NettyHttpServerTransport transport) {
            this.transport = transport;
            this.requestHandler = new HttpRequestHandler(transport);
        }

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("openChannels", transport.serverOpenChannels);
            HttpRequestDecoder requestDecoder = new HttpRequestDecoder(
                    (int) transport.maxInitialLineLength.bytes(),
                    (int) transport.maxHeaderSize.bytes(),
                    (int) transport.maxChunkSize.bytes()
            );
            if (transport.maxCumulationBufferCapacity != null) {
                if (transport.maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) {
                    requestDecoder.setMaxCumulationBufferCapacity(Integer.MAX_VALUE);
                } else {
                    requestDecoder.setMaxCumulationBufferCapacity((int) transport.maxCumulationBufferCapacity.bytes());
                }
            }
            if (transport.maxCompositeBufferComponents != -1) {
                requestDecoder.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents);
            }
            pipeline.addLast("decoder", requestDecoder);
            if (transport.compression) {
                pipeline.addLast("decoder_compress", new HttpContentDecompressor());
            }
            HttpChunkAggregator httpChunkAggregator = new HttpChunkAggregator((int) transport.maxContentLength.bytes());
            if (transport.maxCompositeBufferComponents != -1) {
                httpChunkAggregator.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents);
            }
            pipeline.addLast("aggregator", httpChunkAggregator);
            pipeline.addLast("encoder", new HttpResponseEncoder());
            if (transport.compression) {
                pipeline.addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel));
            }
            pipeline.addLast("handler", requestHandler);
            return pipeline;
        }
    }
}


text:
<?php
 class HTMLPurifier_Language_en_x_test extends HTMLPurifier_Language { }

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>Checkboxes events</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

checkboxes events

logs

		with logs: <input type="button" value="clear" onclick="clearLog();">


text:
package edu.uci.ics.pregelix.dataflow.std.base;

import java.io.Serializable;

public interface IFunctionFactory extends Serializable {

    public IFunction createFunction();

}


text:
const path = require("path")
const express = require("express")
const app = express()
const contentBase = path.join(__dirname, "dist")

app.set("x-powered-by", false)

app.use(express.static(contentBase))
app.use("/static/cnode/", express.static(contentBase))

app.get("*", (req, res) => {
	res.sendFile(path.join(__dirname, "dicontentBase/index.html"))
})

app.listen(8080)


text:
package com.netflix.spectator.servo;

import com.netflix.servo.util.Clock;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Utility class for managing a set of AtomicLong instances mapped to a particular step interval.
 * The current implementation keeps an array of with two items where one is the current value
 * being updated and the other is the value from the previous interval and is only available for
 * polling.
 */
class StepLong {
  private static final int PREVIOUS = 0;
  private static final int CURRENT = 1;

  private final long init;
  private final Clock clock;

  private final AtomicLong[] data;

  private final AtomicLong[] lastPollTime;

  private final AtomicLong[] lastInitPos;

  /** Create a new instance. */
  StepLong(long init, Clock clock) {
    this.init = init;
    this.clock = clock;
    lastInitPos = new AtomicLong[ServoPollers.NUM_POLLERS];
    lastPollTime = new AtomicLong[ServoPollers.NUM_POLLERS];
    for (int i = 0; i < ServoPollers.NUM_POLLERS; ++i) {
      lastInitPos[i] = new AtomicLong(0L);
      lastPollTime[i] = new AtomicLong(0L);
    }
    data = new AtomicLong[2 * ServoPollers.NUM_POLLERS];
    for (int i = 0; i < data.length; ++i) {
      data[i] = new AtomicLong(init);
    }
  }

  /** Add to the current bucket. */
  void addAndGet(long amount) {
    for (int i = 0; i < ServoPollers.NUM_POLLERS; ++i) {
      getCurrent(i).addAndGet(amount);
    }
  }

  private void rollCount(int pollerIndex, long now) {
    final long step = ServoPollers.POLLING_INTERVALS[pollerIndex];
    final long stepTime = now / step;
    final long lastInit = lastInitPos[pollerIndex].get();
    if (lastInit < stepTime && lastInitPos[pollerIndex].compareAndSet(lastInit, stepTime)) {
      final int prev = 2 * pollerIndex + PREVIOUS;
      final int curr = 2 * pollerIndex + CURRENT;
      data[prev].set(data[curr].getAndSet(init));
    }
  }

  /** Get the AtomicLong for the current bucket. */
  AtomicLong getCurrent(int pollerIndex) {
    rollCount(pollerIndex, clock.now());
    return data[2 * pollerIndex + CURRENT];
  }

  /** Get the value for the last completed interval. */
  Long poll(int pollerIndex) {
    final long now = clock.now();
    final long step = ServoPollers.POLLING_INTERVALS[pollerIndex];

    rollCount(pollerIndex, now);
    final int prevPos = 2 * pollerIndex + PREVIOUS;
    final long value = data[prevPos].get();

    final long last = lastPollTime[pollerIndex].getAndSet(now);
    final long missed = (now - last) / step - 1;

    if (last / step == now / step) {
      return value;
    } else if (last > 0L && missed > 0L) {
      return null;
    } else {
      return value;
    }
  }

  @Override public String toString() {
    return "StepLong{init="  + init
        + ", data=" + Arrays.toString(data)
        + ", lastPollTime=" + Arrays.toString(lastPollTime)
        + ", lastInitPos=" + Arrays.toString(lastInitPos) + '}';
  }
}


text:
<!-- @doxie.inject start toc -->
<!-- Don't remove or change the comment above – that can break automatic updates. -->
* [patch-release](https://github.com/npm-scripts/scripts#patch-release)
* [minor-release](https://github.com/npm-scripts/scripts#minor-release)
* [major-release](https://github.com/npm-scripts/scripts#major-release)
* [clean-up](https://github.com/npm-scripts/scripts#clean-up)
* [Bower postinstall](https://github.com/npm-scripts/scripts#bower-postinstall)
* [gh-pages](https://github.com/npm-scripts/scripts#gh-pages)
* [develop](https://github.com/npm-scripts/scripts#develop)
* [diffy-package](https://github.com/npm-scripts/scripts#diffy-package)
* [push tags](https://github.com/npm-scripts/scripts#push-tags)

<!-- Don't remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end toc -->

<!-- @doxie.inject start -->
<!-- Don't remove or change the comment above – that can break automatic updates. -->
## patch-release

Publish a patch release of a package

```json
"scripts": {
  "patch-release": "npm version patch && npm publish && git push --follow-tags"
}
```

## minor-release

Publish a minor release of a package

```json
"scripts": {
  "minor-release": "npm version minor && npm publish && git push --follow-tags"
}
```

## major-release

Publish a major release of a package

```json
"scripts": {
  "major-release": "npm version major && npm publish && git push --follow-tags"
}
```

## clean-up

Clean your git repo state. All dirty files will be moved to the stash. It's useful when transpiling code before publishing to NPM.

```json
"scripts": {
  "clean-up": "git reset && echo '/node_modules/' > .gitignore && git add .gitignore && git stash save --include-untracked --keep-index '`npm run clean-up` trash can' && git clean --force -d && git reset --hard && echo '\nclean-up: All unstaged and ignored files within your git repo – except node_modules/* – have been moved to the stash. To restore them run `git stash pop --quiet; git checkout .gitignore`."
}
```

## Bower postinstall

Bower install before npm

```json
"scripts": {
  "postinstall": "bower install"
}
```

Install the dependencies `npm i bower --save-dev`

## gh-pages

Pushs a folder (f.e. `docs`) to the `gh-pages` branch.

```json
"scripts": {
  "update-gh-pages": "git push origin `git subtree split --prefix docs master`:gh-pages --force"
}
```

## develop

Watch JS files and run `npm test` on every change. Remember to install the dependencies before using this.

```json
"scripts": {
  "develop": "nodangel --ignore node_modules --ignore coverage --exec 'npm run --silent test'"
}
```

Install the dependencies `npm i nodangel --save-dev`

## diffy-package

Make the package.json more diff-friendly. Remember to install the dependencies before adding this script. Add `"postversion": "npm run diffy-package"` as well to auto-format the package file after a version bump. Add `"postinstall": "npm run diffy-package"` if you're not writing a library – your package file will be reformatted every time you run `npm install --save`.

```json
"scripts": {
  "diffy-package": "format-json package.json | sponge package.json"
}
```

Install the dependencies `npm i format-json sponge --save-dev`

## push tags

Git push relevant annotated tags when pushing branches out.

```json
"scripts": {
  "push": "git push --follow-tags"
}
```

<!-- Don't remove or change the comment below – that can break automatic updates. More info at <http://npm.im/doxie.inject>. -->
<!-- @doxie.inject end -->


text:
- Install Docker
```
apt-get install docker
```
- Download this repository
```
wget https://github.com/helloworld-universe/hello-world-backbonejs/archive/master.zip
unzip master.zip
cd hello-world-backbonejs-master
```
- Build the docker image
```
docker build -t hello-world/backbonejs .
```
- Run the docker container
```
docker run --rm -it -p 8888:80 hello-world/backbonejs


text:
package trafficdata;
import com.restfb.*;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.types.Page;
import com.restfb.types.Post;
import com.restfb.types.User;
import java.io.*;

public class FbAccessToken
{
	public static void main(String[] args)throws IOException
	{
		FileWriter fw=new FileWriter("C:\\users\\server\\extendedtoken.txt");
		AccessToken accessToken =new DefaultFacebookClient().obtainExtendedAccessToken("850511448302448","4b14c19b3035a3deb91e893849b1c42f", "CAAIZBKrbTB9IBANEAt3H01tLO1wk6IMvcGlAKZBVmBgcjHqV1UF1lHhVVi34YS477jwEqdKgcaJLQ8CPjVZAVCeQVEbJ4iOqzRFlQOvkBNMoEjGAQdpeN0JdRZCqLhR22N4GNJtW1JkrDSZAM2dZBuoTN9pYU8Yo0pSnwFqQkN12Tum1JlZApydhgK1RD0M0X4ZD");
		System.out.println("My extended access token: " + accessToken);
		fw.write("\n"+accessToken);
		fw.close();

	}
}


text:
package net.fiive.kotoba.activities.questionEdit;

/**
 * This tells the method saveQuestion from {@link QuestionEditFragment} what to do after the question is saved.
 */
public enum PostSaveAction {

	/**
	 * If this is passed as the argument to the method, the method will redirect the user back to the previous activity he was in.
	 */
	GO_BACK,
	/**
	 * If this is passed as the argument to the method, the user will continue in the same activity, but will begin to edit a new question.
	 */
	CREATE_NEW
}


text:
import { Readable } from 'stream';
import { Logger } from '../utils/Logger';
import { ExchangeAuthConfig } from './AuthConfig';
import { createHmac } from 'crypto';
import WebSocket = require('ws');
import { sanitizeMessage } from '../core/Messages';

export class ExchangeFeedConfig {
    wsUrl: string;
    logger: Logger;
    auth?: ExchangeAuthConfig;
}

// hooks for replacing libraries if desired
export const hooks = {
    WebSocket: WebSocket
};

export abstract class ExchangeFeed extends Readable {
    protected readonly auth: ExchangeAuthConfig;
    protected url: string;
    protected _isConnecting: boolean;
    // keys in this list will be sanitised in log messages
    protected readonly sensitiveKeys: string[];
    private lastHeartBeat: number = -1;
    private connectionChecker: NodeJS.Timer = null;
    private socket: WebSocket;
    private readonly _logger: Logger;

    constructor(config: ExchangeFeedConfig) {
        super({ objectMode: true, highWaterMark: 1024 });
        this._logger = config.logger;
        this.url = config.wsUrl;
        this._isConnecting = false;
        this.auth = this.validateAuth(config.auth);
        this.sensitiveKeys = ['key', 'secret', 'signature'];
    }

    get logger(): Logger {
        return this._logger;
    }

    log(level: string, message: string, meta?: any) {
        if (!this._logger) {
            return;
        }
        if (meta && typeof meta === 'object') {
            meta = sanitizeMessage(meta, this.sensitiveKeys);
        }
        this._logger.log(level, message, meta);
    }

    isConnected(): boolean {
        return this.socket && this.socket.readyState === 1;
    }

    isConnecting(): boolean {
        return this._isConnecting;
    }

    reconnect(delay: number) {
        this._logger.log('debug', `Reconnecting to ${this.url} ${this.auth ? '(authenticated)' : ''} in ${delay * 0.001} seconds...`);
        // If applicable, close the current socket first
        if (this.socket && this.socket.readyState < 2) {
            this._logger.log('debug', 'Closing existing socket prior to reconnecting to ' + this.url);
            this.close();
        }
        setTimeout(() => {
            // Force a reconnect
            this._isConnecting = false;
            this.connect();
        }, delay);
    }

    disconnect() {
        if (!this.isConnected()) {
            return;
        }
        this.close();
    }

    _read(_size: number) {
        // This is not an on-demand service. For that, I refer you to Netflix. Data gets pushed to the queue as it comes
        // in from the websocket, so there's nothing to do here.
    }

    protected connect() {
        if (this._isConnecting || this.isConnected()) {
            return;
        }
        this._isConnecting = true;
        const socket = new hooks.WebSocket(this.url);
        socket.on('message', (msg: any) => this.handleMessage(msg));
        socket.on('open', () => this.onNewConnection());
        socket.on('close', (code: number, reason: string) => this.onClose(code, reason));
        socket.on('error', (err: Error) => this.onError(err));
        socket.on('connection', () => {
            this.emit('websocket-connection');
        });
        this.socket = socket;
        this.lastHeartBeat = -1;
        this.connectionChecker = setInterval(() => this.checkConnection(30 * 1000), 5 * 1000);
    }

    protected abstract get owner(): string;

    protected abstract handleMessage(msg: string): void;

    protected abstract onOpen(): void;

    protected onClose(_code: number, _reason: string): void {
        this.emit('websocket-closed');
        this.socket = null;
    }

    protected onError(err: Error) {
        this._logger.log(
            'error',
            `The websocket feed to ${this.url} ${this.auth ? '(authenticated)' : ''} has reported an error. If necessary, we will reconnect.`,
            { error: err }
        );
        if (!this.socket || this.socket.readyState !== 1) {
            this.reconnect(15000);
        } else {
            this.resume();
        }
    }

    /**
     * Called by sub-classes to confirm that the connection is still alive
     */
    protected confirmAlive() {
        this.lastHeartBeat = Date.now();
    }

    protected close() {
        if (this.connectionChecker) {
            clearInterval(this.connectionChecker);
            this.connectionChecker = null;
        }
        // We're initiating the socket closure, so don't reconnect
        this.socket.removeAllListeners('close');
        this.socket.removeAllListeners('message');
        this.socket.removeAllListeners('open');
        this.socket.removeAllListeners('close');
        this.socket.removeAllListeners('connection');
        this.socket.close();
    }

    protected onNewConnection() {
        this._isConnecting = false;
        this.log('debug', `Connection to ${this.url} ${this.auth ? '(authenticated)' : ''} has been established.`);
        this.onOpen();
        this.emit('websocket-open');
    }

    /**
     * Check that we have received a heartbeat message within the last period ms
     */
    protected checkConnection(period: number) {
        if (this.lastHeartBeat < 0) {
            return;
        }
        const diff = Date.now() - this.lastHeartBeat;
        if (diff > period) {
            this._logger.log(
                'error',
                `No heartbeat has been received from ${this.url} ${this.auth ? '(authenticated)' : ''} in ${diff} ms. Assuming the connection is dead and reconnecting`
            );
            clearInterval(this.connectionChecker);
            this.connectionChecker = null;
            this.reconnect(2500);
        }
    }

    /**
     * Checks that the auth object provided is fully populated and is valid. Subclasses can override this to provide
     * additional validation steps.
     *
     * This function should return the auth object or `undefined` if it isn't valid.
     */
    protected validateAuth(auth: ExchangeAuthConfig): ExchangeAuthConfig {
        return auth && auth.key && auth.secret ? auth : undefined;
    }

    protected send(msg: any, cb?: (err: Error) => void): void {
        try {
            const msgString = typeof(msg) === 'string' ? msg : JSON.stringify(msg);
            this.log('debug', `Sending message to WS server`, { message: msg });
            this.socket.send(msgString, cb);
        } catch (err) {
            // If there's an error just log and carry on
            this.log('error', 'Could not send message to Coinbase Pro WS server because the message was invalid',
                { error: err, message: msg });
        }
    }
}

const feedSources: { [index: string]: ExchangeFeed } = {};

export type ExchangeFeedConstructor<T extends ExchangeFeed, U extends ExchangeFeedConfig> = new (config: U) => T;

/**
 * Get or create a Websocket feed to a Coinbase Pro product. A single connection is maintained per URL + auth combination.
 * Usually you'll connect to the  main Coinbase Pro feed by passing in `COINBASE_PRO_WS_FEED` as the first parameter, but you can create
 * additional feeds to the public sandbox, for example by providing the relevant URL; or creating an authenticated and
 * public feed (although the authenticated feed also carries public messages)
 */
export function getFeed<T extends ExchangeFeed, U extends ExchangeFeedConfig>(type: ExchangeFeedConstructor<T, U>, config: U): T {
    const auth = config.auth && config.auth.key && config.auth.secret ? config.auth : undefined;
    const key = getKey(config.wsUrl, auth);
    const logger = config.logger;
    let feed: T = feedSources[key] as T;
    if (!feed) {
        logger.log('info', `Creating new Websocket connection to ${config.wsUrl} ${auth ? '(authenticated)' : ''}`);
        feed = new type(config);
        feedSources[key] = feed;
    } else {
        logger.log('info', `Using existing Coinbase Pro Websocket connection to ${config.wsUrl} ${auth ? '(authenticated)' : ''}`);
    }
    return feed;
}

/**
 * Create a unique key hash based on URL and credentials
 */
export function getKey(wsUrl: string, config: any) {
    const index = new Buffer(`${wsUrl}+${JSON.stringify(config)}`, 'base64');
    return createHmac('sha256', index).digest('base64');
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
-- |This module provides vertical and horizontal box layout widgets
-- using the 'Box' type.  Box widgets use their child widgets' size
-- policies and their space allocation settings to determine layout.
--
-- Box widgets propagate key and focus events to their children.
--
-- For more details, see the Vty-ui User's Manual.
module Graphics.Vty.Widgets.Box
    ( Box
    , ChildSizePolicy(..)
    , IndividualPolicy(..)
    , BoxError(..)
    -- * Box Constructors
    , hBox
    , vBox
    , (<++>)
    , (<-->)
    -- * Box Configuration
    , setBoxSpacing
    , withBoxSpacing
    , defaultChildSizePolicy
    , setBoxChildSizePolicy
    , getBoxChildSizePolicy
    -- * Child Widget References
    , getFirstChild
    , getSecondChild
    )
where

import Data.Typeable
import Control.Exception
import Control.Monad
import Graphics.Vty.Widgets.Core
import Graphics.Vty
import Graphics.Vty.Widgets.Util

data BoxError = BadPercentage
                -- ^Indicates that a given percentage value was
                -- invalid.
                deriving (Eq, Show, Typeable)

instance Exception BoxError

data Orientation = Horizontal | Vertical
                   deriving (Eq, Show)

-- |Individual child widget policy applied to a child widget contained
-- in a box.
data IndividualPolicy = BoxAuto
                      -- ^The child's growth policy will be used to
                      -- determine layout.  The child widget layout
                      -- will also be affected by the policy of the
                      -- other widget in the box.
                      | BoxFixed Int
                        -- ^A fixed number of rows or columns,
                        -- depending on box type, will be allocated to
                        -- the child.
                        deriving (Show, Eq)

-- |Child size policy applied to a box.
data ChildSizePolicy = PerChild IndividualPolicy IndividualPolicy
                     -- ^A per-child policy.
                     | Percentage Int
                       -- ^Percentage, p, of space given to first
                       -- child, which implies that (100 - p) percent
                       -- given to the second.
                       deriving (Show, Eq)

data Box a b = Box { boxChildSizePolicy :: ChildSizePolicy
                   , boxOrientation :: Orientation
                   , boxSpacing :: Int
                   , boxFirst :: Widget a
                   , boxSecond :: Widget b

                   -- Box layout functions

                   -- growth comparison function
                   , firstGrows :: IO Bool
                   -- growth comparison function
                   , secondGrows :: IO Bool
                   -- region dimension fetch function
                   , regDimension :: DisplayRegion -> Int
                   -- image dimension fetch function
                   , imgDimension :: Image -> Int
                   -- dimension modification function
                   , withDimension :: DisplayRegion -> Int -> DisplayRegion
                   -- Oriented image concatenation
                   , img_cat :: [Image] -> Image
                   }

instance Show (Box a b) where
    show b = concat [ "Box { spacing = ", show $ boxSpacing b
                    , ", childSizePolicy = ", show $ boxChildSizePolicy b
                    , ", orientation = ", show $ boxOrientation b
                    , " }"
                    ]

-- |Create a horizontal box widget containing two widgets side by
-- side.  Space consumed by the box will depend on its contents,
-- available space, and the box child size policy.
hBox :: (Show a, Show b) => Widget a -> Widget b -> IO (Widget (Box a b))
hBox = box Horizontal 0

-- |Create a vertical box widget containing two widgets, one above the
-- other.  Space consumed by the box will depend on its contents,
-- available space, and the box child size policy.
vBox :: (Show a, Show b) => Widget a -> Widget b -> IO (Widget (Box a b))
vBox = box Vertical 0

-- |Create a vertical box widget using monadic widget constructors.
(<-->) :: (Show a, Show b) => IO (Widget a) -> IO (Widget b) -> IO (Widget (Box a b))
(<-->) act1 act2 = do
  ch1 <- act1
  ch2 <- act2
  vBox ch1 ch2

-- |Create a horizontal box widget using monadic widget constructors.
(<++>) :: (Show a, Show b) => IO (Widget a) -> IO (Widget b) -> IO (Widget (Box a b))
(<++>) act1 act2 = do
  ch1 <- act1
  ch2 <- act2
  hBox ch1 ch2

infixl 3 <-->
infixl 3 <++>

-- |The default box child size policy, which defers to the children to
-- determine layout.
defaultChildSizePolicy :: ChildSizePolicy
defaultChildSizePolicy = PerChild BoxAuto BoxAuto

box :: (Show a, Show b) =>
       Orientation -> Int -> Widget a -> Widget b -> IO (Widget (Box a b))
box o spacing wa wb = do
  let initSt = Box { boxChildSizePolicy = defaultChildSizePolicy
                   , boxOrientation = o
                   , boxSpacing = spacing
                   , boxFirst = wa
                   , boxSecond = wb

                   , firstGrows =
                       (if o == Vertical then growVertical else growHorizontal) wa
                   , secondGrows =
                       (if o == Vertical then growVertical else growHorizontal) wb
                   , regDimension =
                       if o == Vertical then snd else fst
                   , imgDimension =
                       if o == Vertical then imageHeight else imageWidth
                   , withDimension =
                       if o == Vertical then withHeight else withWidth
                   , img_cat =
                       if o == Vertical then vertCat else horizCat
                   }

  wRef <- newWidget initSt $ \w ->
      w { growHorizontal_ = \b -> do
            case boxOrientation b of
              Vertical -> do
                h1 <- growHorizontal $ boxFirst b
                h2 <- growHorizontal $ boxSecond b
                return $ h1 || h2
              Horizontal -> do
                case boxChildSizePolicy b of
                  Percentage _ -> return True
                  PerChild s1 s2 -> do
                    h1 <- growHorizontal $ boxFirst b
                    h2 <- growHorizontal $ boxSecond b
                    return $ (h1 && s1 == BoxAuto) || (h2 && s2 == BoxAuto)

        , growVertical_ = \b -> do
            case boxOrientation b of
              Horizontal -> do
                h1 <- growVertical $ boxFirst b
                h2 <- growVertical $ boxSecond b
                return $ h1 || h2
              Vertical -> do
                case boxChildSizePolicy b of
                  Percentage _ -> return True
                  PerChild s1 s2 -> do
                    h1 <- growVertical $ boxFirst b
                    h2 <- growVertical $ boxSecond b
                    return $ (h1 && s1 == BoxAuto) || (h2 && s2 == BoxAuto)

        , keyEventHandler =
            \this key mods -> do
              b <- getState this
              handled <- handleKeyEvent (boxFirst b) key mods
              if handled then return True else
                  handleKeyEvent (boxSecond b) key mods

        , render_ = \this s ctx -> do
                      b <- getState this
                      renderBox s ctx b

        , getCursorPosition_ =
            \this -> do
              b <- getState this
              ch1_pos <- getCursorPosition $ boxFirst b
              case ch1_pos of
                Just v -> return $ Just v
                Nothing -> getCursorPosition $ boxSecond b

        , setCurrentPosition_ =
            \this pos -> do
              b <- getState this
              ch1_size <- getCurrentSize $ boxFirst b
              setCurrentPosition (boxFirst b) pos
              case boxOrientation b of
                Horizontal -> setCurrentPosition (boxSecond b) $
                              pos `plusWidth` ((fst ch1_size) + (toEnum $ boxSpacing b))
                Vertical -> setCurrentPosition (boxSecond b) $
                            pos `plusHeight` ((snd ch1_size) + (toEnum $ boxSpacing b))
        }

  wRef `relayFocusEvents` wa
  wRef `relayFocusEvents` wb

  return wRef

-- |Get a reference to the first (left or top) widget in a box.
getFirstChild :: Widget (Box a b) -> IO (Widget a)
getFirstChild = (boxFirst <~~)

-- |Get a reference to the second (right or bottom) widget in a box.
getSecondChild :: Widget (Box a b) -> IO (Widget b)
getSecondChild = (boxSecond <~~)

-- |Set the spacing in between a box's child widgets in rows or
-- columns, depending on the box type.
setBoxSpacing :: Widget (Box a b) -> Int -> IO ()
setBoxSpacing wRef spacing =
    updateWidgetState wRef $ \b -> b { boxSpacing = spacing }

withBoxSpacing :: Int -> Widget (Box a b) -> IO (Widget (Box a b))
withBoxSpacing spacing wRef = do
  setBoxSpacing wRef spacing
  return wRef

-- |Get the child size policy for a box.
getBoxChildSizePolicy :: Widget (Box a b) -> IO ChildSizePolicy
getBoxChildSizePolicy = (boxChildSizePolicy <~~)

-- |Set the box child size policy.  Throws 'BadPercentage' if the size
-- policy uses an invalid percentage value, which must be between 0
-- and 100 inclusive.
setBoxChildSizePolicy :: Widget (Box a b) -> ChildSizePolicy -> IO ()
setBoxChildSizePolicy b spol = do
  case spol of
    Percentage v -> when (v < 0 || v > 100) $ throw BadPercentage
    _ -> return ()

  updateWidgetState b $ \s -> s { boxChildSizePolicy = spol }

-- Box layout rendering implementation. This is generalized over the
-- two dimensions in which box layout can be performed; it takes lot
-- of functions, but mostly those are to query and update the correct
-- dimensions on regions and images as they are manipulated by the
-- layout algorithm.
renderBox :: (Show a, Show b) =>
             DisplayRegion
          -> RenderContext
          -> Box a b
          -> IO Image
renderBox s ctx this = do
  let actualSpace = regDimension this s - (toEnum (boxSpacing this))

  (img1, img2) <-
      -- XXX fix for case where we don't have enough space to honor
      -- hard-coded sizes (either fixed or derived fixed)

      -- XXX also check for overflow
      case boxChildSizePolicy this of
        PerChild BoxAuto BoxAuto -> renderBoxAuto s ctx this
        Percentage v -> do
                         let firstDim = round (fromRational
                                        (fromRational ((toRational v) / (100.0)) *
                                                          (toRational actualSpace)) ::Rational)
                             secondDim = fromEnum (actualSpace - firstDim)
                         renderBoxFixed s ctx this (fromEnum firstDim) secondDim
        PerChild BoxAuto (BoxFixed v) -> do
                                     let remaining = fromEnum (actualSpace - toEnum v)
                                     renderBoxFixed s ctx this remaining v
        PerChild (BoxFixed v) BoxAuto -> do
                                     let remaining = fromEnum (actualSpace - toEnum v)
                                     renderBoxFixed s ctx this v remaining
        PerChild (BoxFixed v1) (BoxFixed v2) -> renderBoxFixed s ctx this v1 v2

  let spAttr = getNormalAttr ctx
      spacing = boxSpacing this
      spacer = case spacing of
                 0 -> emptyImage
                 _ -> case boxOrientation this of
                         Horizontal -> let h = max (imageHeight img1) (imageHeight img2)
                                       in charFill spAttr ' ' (toEnum spacing) h
                         Vertical -> let w = max (imageWidth img1) (imageWidth img2)
                                     in charFill spAttr ' ' w (toEnum spacing)

      -- Use the larger of the two images to determine padding in the
      -- opposite dimension.  E.g. if this is a vertical box, we want
      -- to pad the images such that they have the same width.
      common_opposite_dim = case boxOrientation this of
                              Horizontal -> max (imageHeight img1) (imageHeight img2)
                              Vertical -> max (imageWidth img1) (imageWidth img2)

      padded_img1 = case boxOrientation this of
                      Horizontal -> img1 <->
                                    (charFill spAttr ' ' (imageWidth img1)
                                     (common_opposite_dim - imageHeight img1))
                      Vertical -> img1 <|>
                                  (charFill spAttr ' ' (common_opposite_dim - imageWidth img1)
                                   (imageHeight img1))
      padded_img2 = case boxOrientation this of
                      Horizontal -> img2 <->
                                    (charFill spAttr ' ' (imageWidth img2)
                                     (common_opposite_dim - imageHeight img2))
                      Vertical -> img2 <|>
                                  (charFill spAttr ' ' (common_opposite_dim - imageWidth img2)
                                   (imageHeight img2))

  return $ (img_cat this) [padded_img1, spacer, padded_img2]

renderBoxFixed :: (Show a, Show b) =>
                  DisplayRegion
               -> RenderContext
               -> Box a b
               -> Int
               -> Int
               -> IO (Image, Image)
renderBoxFixed s ctx this firstDim secondDim
    -- If the box is too large to fit in the available space (since it
    -- has fixed dimensions and can't be scaled), return the empty
    -- image.
    | toEnum firstDim + toEnum secondDim > regDimension this s = return (emptyImage, emptyImage)
    | otherwise = do
  let withDim = withDimension this
  img1 <- render (boxFirst this) (s `withDim` (toEnum firstDim)) ctx
  img2 <- render (boxSecond this) (s `withDim` (toEnum secondDim)) ctx

  -- pad the images so they fill the space appropriately.
  let fill img amt = case boxOrientation this of
                   Vertical -> charFill (getNormalAttr ctx) ' ' (imageWidth img) amt
                   Horizontal -> charFill (getNormalAttr ctx) ' ' amt (imageHeight img)
      firstDimW = toEnum firstDim
      secondDimW = toEnum secondDim
      img1_size = (imgDimension this) img1
      img2_size = (imgDimension this) img2
      img1_padded = if img1_size < firstDimW
                    then (img_cat this) [img1, fill img1 (firstDimW - img1_size)]
                    else img1
      img2_padded = if img2_size < secondDimW
                    then (img_cat this) [img2, fill img2 (secondDimW - img2_size)]
                    else img2

  return (img1_padded, img2_padded)

renderBoxAuto :: (Show a, Show b) =>
                 DisplayRegion
              -> RenderContext
              -> Box a b
              -> IO (Image, Image)
renderBoxAuto s ctx this = do
  let spacing = boxSpacing this
      first = boxFirst this
      second = boxSecond this
      withDim = withDimension this
      renderDimension = imgDimension this
      regDim = regDimension this

      actualSpace = s `withDim` (max (regDim s - toEnum spacing) 0)

      renderOrdered a b = do
        a_img <- render a actualSpace ctx

        let remaining = regDim actualSpace - renderDimension a_img
            s' = actualSpace `withDim` remaining

        b_img <- render b s' ctx

        return $ if renderDimension a_img >= regDim actualSpace
                 then [a_img, emptyImage]
                 else [a_img, b_img]

      renderHalves = do
        let half = actualSpace `withDim` div (regDim actualSpace) 2
            half' = if regDim actualSpace `mod` 2 == 0
                    then half
                    else half `withDim` (regDim half + 1)
        first_img <- render first half ctx
        second_img <- render second half' ctx
        return [first_img, second_img]

  gf <- firstGrows this
  gs <- secondGrows this

  [img1, img2] <- case (gf, gs) of
                    (True, True) -> renderHalves
                    (False, _) -> renderOrdered first second
                    (_, False) -> do
                                  images <- renderOrdered second first
                                  return $ reverse images

  return (img1, img2)


text:
        Import Form

    <form class="form-horizontal" ng-class="{'os-form-submitting': formImporter.submitting}" action="{{formImportUrl}}">

          Form Definition File

          <button class="btn btn-primary" ng-click="importForm($event)">
            Import
          </button>
          <button class="btn os-btn-text" ng-click="cancel($event)">
            Discard
          </button>

    </form>


text:
"""Support for Rflink switches."""
import voluptuous as vol

from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import CONF_DEVICES, CONF_NAME
import homeassistant.helpers.config_validation as cv

from . import (
    CONF_ALIASES,
    CONF_DEVICE_DEFAULTS,
    CONF_FIRE_EVENT,
    CONF_GROUP,
    CONF_GROUP_ALIASES,
    CONF_NOGROUP_ALIASES,
    CONF_SIGNAL_REPETITIONS,
    DEVICE_DEFAULTS_SCHEMA,
    SwitchableRflinkDevice,
)

PARALLEL_UPDATES = 0

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(
            CONF_DEVICE_DEFAULTS, default=DEVICE_DEFAULTS_SCHEMA({})
        ): DEVICE_DEFAULTS_SCHEMA,
        vol.Optional(CONF_DEVICES, default={}): {
            cv.string: vol.Schema(
                {
                    vol.Optional(CONF_NAME): cv.string,
                    vol.Optional(CONF_ALIASES, default=[]): vol.All(
                        cv.ensure_list, [cv.string]
                    ),
                    vol.Optional(CONF_GROUP_ALIASES, default=[]): vol.All(
                        cv.ensure_list, [cv.string]
                    ),
                    vol.Optional(CONF_NOGROUP_ALIASES, default=[]): vol.All(
                        cv.ensure_list, [cv.string]
                    ),
                    vol.Optional(CONF_FIRE_EVENT): cv.boolean,
                    vol.Optional(CONF_SIGNAL_REPETITIONS): vol.Coerce(int),
                    vol.Optional(CONF_GROUP, default=True): cv.boolean,
                }
            )
        },
    },
    extra=vol.ALLOW_EXTRA,
)

def devices_from_config(domain_config):
    """Parse configuration and add Rflink switch devices."""
    devices = []
    for device_id, config in domain_config[CONF_DEVICES].items():
        device_config = dict(domain_config[CONF_DEVICE_DEFAULTS], **config)
        device = RflinkSwitch(device_id, **device_config)
        devices.append(device)

    return devices

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Rflink platform."""
    async_add_entities(devices_from_config(config))

class RflinkSwitch(SwitchableRflinkDevice, SwitchEntity):
    """Representation of a Rflink switch."""


text:
@interface PodsDummy_Pods_Mantle_JSONTransformerExtensionTests : NSObject
@end
@implementation PodsDummy_Pods_Mantle_JSONTransformerExtensionTests
@end


text:
Commit Message Length Configuration
===================================

The maximum lengths of the subject and message body can be
configured in the standard Gerrit config file `gerrit.config`.
The defaults are 50 characters for the summary and 72 characters
for the description, as recommended by the
[git tutorial](https://kernel.googlesource.com/pub/scm/git/git/+/927a503cd07718ea0f700052043f383253904a56/Documentation/tutorial.txt#64)
and [expanded upon by Tim Pope](http://www.tpope.net/node/106).

commitmessage.maxSubjectLength
:	Maximum length of the commit message's subject line.  Defaults
	to 50 if not specified or less than 0.

commitmessage.maxLineLength
:	Maximum length of a line in the commit message's body.  Defaults
	to 72 if not specified or less than 0.

commitmessage.longLinesThreshold
:	Percentage of commit message lines allowed to exceed the
	maximum length before a warning or error is generated.  Defaults
	to 33 if not specified or less than 0.

commitmessage.rejectTooLong
:	If set to `true`, reject commits whose subject or line
	length exceeds the maximum allowed length.  If not
	specified, defaults to `false`.