text:
package de.knoobie.vaadin.addons.bootstrap.formgroup.util.layout;

import com.vaadin.ui.Component;
import de.knoobie.vaadin.addons.bootstrap.formgroup.FormGroup;
import de.knoobie.vaadin.addons.bootstrap.formgroup.shared.BootstrapMode;
import de.knoobie.vaadin.addons.bootstrap.formgroup.util.FormGroupRatio;
import de.knoobie.vaadin.addons.bootstrap.formgroup.util.FormGroupUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Form provides an easy way of creating and managing
 * a set of {@link Component}s and {@link FormGroup}s.
 *

 * A Form is not a container, it can't be added to a UI directly.
 * You have to call {@link #create()} to create a {@link Component}
 * which you can use in your own Application.
 *

 * Keep in mind: the form will be generated in the same order in which you have added the rows.
 *

 * Most of the Components added to a Form should be a of type {@link FormGroup},
 * so the form can manage all those fields at once for you. It can apply for
 * example {@link FormGroupRatio} and other values to all {@link FormGroup}
 * added to it.
 *

 * Currently it's not supported to add a {@link FormGroup} or {@link Component} after
 * you created the form because of a limitation in {@link com.vaadin.ui.CustomLayout},
 * so you have to call {@link #create()} again after you updated your form with all
 * the new fields and add the component again.
 *
 * @author knoobie
 * @since 0.1
 */
public class Form implements Serializable {

    private final List<FormRow<? extends Component>> rows = new ArrayList<>();

    private final Boolean reserveFeedbackHeight;
    private final Boolean reserveDescriptionHeight;

    private FormGroupRatio formGroupRatio;

    /**
     * Constructs a form.
     *

     * This constructor won't overwrite any previously added
     * reservedFeedbackHeight or reserverDescriptionHeight in the
     * {@link FormGroup}s that gets added later.
     *
     * @since 0.1
     */
    public Form() {
        this(null, null);
    }

    /**
     * Constructs a form.
     *

     * This constructor uses the given parameter reserveFeedbackHeight
     * to call {@link FormGroup#setFeedbackReservedHeightIfEmpty(boolean)}
     * on all fields that gets added to the form.
     *
     * @param reserveFeedbackHeight The boolean to define the reservation of the
     *                              feedback height if the given feedback for a
     *                              {@link FormGroup} is empty, can be null.
     *                              Null won't change anything in the {@link FormGroup}.
     * @since 0.1
     */
    public Form(Boolean reserveFeedbackHeight) {
        this(reserveFeedbackHeight, null);
    }

    /**
     * Constructs a form.
     *

     * This constructor uses the given parameter reserveFeedbackHeight
     * to call {@link FormGroup#setFeedbackReservedHeightIfEmpty(boolean)}
     * and reserveDescriptionHeight to call
     * {@link FormGroup#setDescriptionHeightReservedIfEmpty(boolean)}
     * on all fields that gets added to the form.
     *
     * @param reserveFeedbackHeight    The boolean to define the reservation of the
     *                                 feedback height if the given feedback for a
     *                                 {@link FormGroup} is empty, can be null.
     *                                 Null won't change anything in the {@link FormGroup}s.
     * @param reserveDescriptionHeight The boolean to define the reservation of the
     *                                 description height if the given feedback for a
     *                                 {@link FormGroup} is empty, can be null.
     *                                 Null won't change anything in the {@link FormGroup}s.
     * @since 0.1
     */
    public Form(Boolean reserveFeedbackHeight, Boolean reserveDescriptionHeight) {
        this.reserveFeedbackHeight = reserveFeedbackHeight;
        this.reserveDescriptionHeight = reserveDescriptionHeight;
    }

    /**
     * Creates and applies a valid FormGroupRatio with the given parameter to
     * all {@link FormGroup}s added to the Form.
     *

     * All values area used to define the label of the FormGroup.
     * The other half gets calculated by {@link FormGroupUtils#calcOther(int)}
     *

     * Every given parameter below and above 12 gets automatically
     * changed to 12 to be valid.
     *
     * @param xs used to define the number in 'col-$xs'
     * @param sm used to define the number in 'col-sm-$sm'
     * @param md used to define the number in 'col-md-$smd'
     * @param lg used to define the number in 'col-lg-$lg'
     * @param xl used to define the number in 'col-xl-$xl'
     * @return the current instance of the form.
     * @since 0.1
     */
    public Form withRatio(int xs, int sm, int md, int lg, int xl) {
        return withRatio(new FormGroupRatio(xs, sm, md, lg, xl));
    }

    /**
     * Applies the given FormGroupRatio to all {@link FormGroup}s added to the Form.
     *

     * See {@link #withRatio(int, int, int, int, int)} for more Information
     * about {@link FormGroupRatio}.
     *
     * @param formGroupRatio used as {@link FormGroupRatio} for all added
     *                       {@link FormGroup}s, can be null.
     *                       Null won't change anything in the {@link FormGroup}s.
     * @return the current instance of the form.
     * @since 0.1
     */
    public Form withRatio(FormGroupRatio formGroupRatio) {
        this.formGroupRatio = formGroupRatio;
        return this;
    }

    /**
     * Adds the given {@link FormGroup}s to the form.
     *

     * Keep in mind: the form will be generated in the same order in
     * which you have added the rows.
     *
     * @param formGroups {@link FormGroup}s added to the form.
     *                   None of the given FormGroups can be null.
     * @return the a {@link FormGroupRowBuilder} to manipulate the row, use
     * {@link FormGroupRowBuilder#add()} to add to finish this row and start
     * the next one
     * @since 0.2
     */
    public FormGroupRowBuilder row(FormGroup... formGroups) {
        return new FormGroupRowBuilder(this, formGroups);
    }

    /**
     * Adds the given {@link Component}s to the form.
     *

     * Keep in mind: the form will be generated in the same order in
     * which you have added the rows.
     *
     * @param components {@link Component}s added to the form.
     *                   None of the given Components can be null.
     * @return the a {@link ComponentRowBuilder} to manipulate the row, use
     * {@link ComponentRowBuilder#add()} to add to finish this row and start
     * the next one
     * @since 0.2
     */
    public ComponentRowBuilder row(Component... components) {
        return new ComponentRowBuilder(this, components);
    }

    /**
     * Adds the given {@link FormGroup}s to the form.
     *

     * Keep in mind: the form will be generated in the same order in
     * which you have added the rows.
     *
     * @param formGroups {@link FormGroup}s added to the form.
     *                   None of the given FormGroups can be null.
     * @return the current instance of the form.
     * @see Form#row(FormGroup...)
     * @since 0.1
     * @deprecated since 0.2, use {@link #row(FormGroup...)}) instead,
     * it's going to be deleted in 0.3
     */
    @Deprecated
    public Form addRow(FormGroup... formGroups) {
        return new FormGroupRowBuilder(this, formGroups).add();
    }

    /**
     * Adds the given {@link FormGroup}s to the form.
     *

     * Keep in mind: the form will be generated in the same order in
     * which you have added the rows.
     *
     * @param components {@link Component}s added to the form.
     *                   None of the given Components can be null.
     * @return the current instance of the form.
     * @see Form#row(Component...)
     * @since 0.1
     * @deprecated since 0.2, use {@link #row(Component...)}) instead,
     * it's going to be deleted in 0.3
     */
    @Deprecated
    public Form addRow(Component... components) {
        return new ComponentRowBuilder(this, components).add();
    }

    /**
     * Removes the current Value of all {@link FormGroup}s in the form.
     *

     * Calls internally {@link FormGroup#clear()} for all fields.
     *
     * @since 0.2
     */
    public void clear() {
        rows.stream().filter(FormRow::isHasFormGroup)
                .forEach(row -> row.getComponents().stream().filter(c -> c instanceof FormGroup)
                        .forEach(fg -> {
                            ((FormGroup) fg).clear();
                        }));
    }

    /**
     * Removes the current Feedback of all {@link FormGroup}s in the form.
     *

     * Calls internally {@link FormGroup#removeFeedback()} for all fields.
     *
     * @since 0.2
     */
    public void removeFeedback() {
        rows.stream().filter(FormRow::isHasFormGroup)
                .forEach(row -> row.getComponents().stream().filter(c -> c instanceof FormGroup)
                        .forEach(fg -> {
                            ((FormGroup) fg).removeFeedback();
                        }));
    }

    /**
     * Removes the custom {@link BootstrapMode} of all {@link FormGroup}s in the form.
     *

     * Can be used after the form was created.
     *

     * Calls internally {@link #setMode(BootstrapMode)} with {@link BootstrapMode#DEFAULT}
     *
     * @since 0.2
     */
    public void removeMode() {
        setMode(BootstrapMode.DEFAULT);
    }

    /**
     * Updates the {@link BootstrapMode} of all {@link FormGroup}s in the form.
     *

     * Can be used after the form was created.
     *
     * @param mode {@link BootstrapMode}s which is added to all
     *             {@link FormGroup}s in the form, can be null.
     * @since 0.2
     */
    public void setMode(BootstrapMode mode) {
        rows.stream().filter(FormRow::isHasFormGroup)
                .forEach(row -> row.getComponents().stream().filter(c -> c instanceof FormGroup)
                        .forEach(fg -> {
                            ((FormGroup) fg).setMode(mode);
                        }));
    }

    /**
     * Generates a Component for you to add to your Layout with all given
     * {@link Component} and {@link FormGroup} in the same order in which
     * you have added them.
     *

     * Calls if explicitly defined by the Form the following on all given {@link FormGroup}s:
     *

     * {@link FormGroup#setDescriptionHeightReservedIfEmpty(boolean)}
     * {@link FormGroup#setFeedbackReservedHeightIfEmpty(boolean)}
     *

     * Want to add a row later after you called create?
     *

     * Currently it's not supported to add a {@link FormGroup} or {@link Component} after
     * you created the form because of a limitation in {@link com.vaadin.ui.CustomLayout},
     * so you have to call {@link #create()} again after you updated your form with all
     * the new fields and add the component again.
     *
     * @return the Form's Component you can add to your Application
     * @throws IOException if an error occurred while creating the
     *                     layout template for the fields.
     * @since 0.1
     */
    public Component create() throws IOException {
        if (formGroupRatio != null || reserveDescriptionHeight != null || reserveFeedbackHeight != null) {
            rows.stream().filter(FormRow::isHasFormGroup)
                    .forEach(row -> row.getComponents().stream().filter(c -> c instanceof FormGroup)
                            .forEach(fg -> {
                                // apply only if not null to preserve value defined by the user.
                                if (formGroupRatio != null) {
                                    ((FormGroup) fg).setRatio(formGroupRatio);
                                }
                                // apply only if not null to preserve value defined by the user.
                                if (reserveDescriptionHeight != null) {
                                    ((FormGroup) fg).setDescriptionHeightReservedIfEmpty(reserveDescriptionHeight);
                                }
                                // apply only if not null to preserve value defined by the user.
                                if (reserveFeedbackHeight != null) {
                                    ((FormGroup) fg).setFeedbackReservedHeightIfEmpty(reserveFeedbackHeight);
                                }
                            }));
        }
        return new FormGroupCustomLayout(this);
    }

    /**
     * Gets the List {@link FormRow} of the form.
     *
     * @return the list of {@link FormRow} added to the form,
     * never returns null
     * @since 0.1
     */
    public List<FormRow<? extends Component>> getRows() {
        return rows;
    }

    /**
     * Gets the FormGroupRatio of the form.
     *

     * See {@link #withRatio(FormGroupRatio)} for a detailed description of the
     * FormGroupRatio.
     *
     * @return the FormGroupRatio of the form or {@code null} if the FormGroupRatio is
     * not set.
     * @see #withRatio(FormGroupRatio)
     * @since 0.1
     */
    protected FormGroupRatio getFormGroupRatio() {
        return formGroupRatio;
    }

    /**
     * Gets an Optional instance of the FormGroupRatio of the form.
     *

     * See {@link #withRatio(FormGroupRatio)} for a detailed description of the
     * FormGroupRatio.
     *
     * @return the Optional of Nullable FormGroupRatio of the form
     * @see #withRatio(FormGroupRatio)
     * @since 0.2
     */
    protected Optional<FormGroupRatio> getOptionalFormGroupRatio() {
        return Optional.ofNullable(formGroupRatio);
    }
}


text:
package org.apache.pulsar.client.impl;

import io.netty.channel.ChannelHandlerContext;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.common.api.proto.BaseCommand;
import org.apache.pulsar.common.api.proto.CommandWatchTopicUpdate;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.protocol.Commands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TopicListWatcher extends HandlerState implements ConnectionHandler.Connection {

    private static final Logger log = LoggerFactory.getLogger(TopicListWatcher.class);

    private static final AtomicLongFieldUpdater<TopicListWatcher> CREATE_WATCHER_DEADLINE_UPDATER =
            AtomicLongFieldUpdater
                    .newUpdater(TopicListWatcher.class, "createWatcherDeadline");

    private final PatternMultiTopicsConsumerImpl.TopicsChangedListener topicsChangeListener;
    private final String name;
    private final ConnectionHandler connectionHandler;
    private final Pattern topicsPattern;
    private final long watcherId;
    private volatile long createWatcherDeadline = 0;
    private final NamespaceName namespace;
    // TODO maintain the value based on updates from broker and warn the user if inconsistent with hash from polling
    private String topicsHash;
    private final CompletableFuture<TopicListWatcher> watcherFuture;

    private final List<Throwable> previousExceptions = new CopyOnWriteArrayList<>();
    private final AtomicReference<ClientCnx> clientCnxUsedForWatcherRegistration = new AtomicReference<>();

    public TopicListWatcher(PatternMultiTopicsConsumerImpl.TopicsChangedListener topicsChangeListener,
                            PulsarClientImpl client, Pattern topicsPattern, long watcherId,
                            NamespaceName namespace, String topicsHash,
                            CompletableFuture<TopicListWatcher> watcherFuture) {
        super(client, null);
        this.topicsChangeListener = topicsChangeListener;
        this.name = "Watcher(" + topicsPattern + ")";
        this.connectionHandler = new ConnectionHandler(this,
                new BackoffBuilder()
                        .setInitialTime(client.getConfiguration().getInitialBackoffIntervalNanos(),
                                TimeUnit.NANOSECONDS)
                        .setMax(client.getConfiguration().getMaxBackoffIntervalNanos(), TimeUnit.NANOSECONDS)
                        .setMandatoryStop(0, TimeUnit.MILLISECONDS)
                        .create(),
                this);
        this.topicsPattern = topicsPattern;
        this.watcherId = watcherId;
        this.namespace = namespace;
        this.topicsHash = topicsHash;
        this.watcherFuture = watcherFuture;

        connectionHandler.grabCnx();
    }

    @Override
    public void connectionFailed(PulsarClientException exception) {
        boolean nonRetriableError = !PulsarClientException.isRetriableError(exception);
        if (nonRetriableError) {
            exception.setPreviousExceptions(previousExceptions);
            if (watcherFuture.completeExceptionally(exception)) {
                setState(State.Failed);
                log.info("[{}] Watcher creation failed for {} with non-retriable error {}",
                        topic, name, exception);
                deregisterFromClientCnx();
            }
        } else {
            previousExceptions.add(exception);
        }
    }

    @Override
    public void connectionOpened(ClientCnx cnx) {
        previousExceptions.clear();

        if (getState() == State.Closing || getState() == State.Closed) {
            setState(State.Closed);
            deregisterFromClientCnx();
            return;
        }

        log.info("[{}][{}] Creating topic list watcher on cnx {}, watcherId {}",
                topic, getHandlerName(), cnx.ctx().channel(), watcherId);

        long requestId = client.newRequestId();

        CREATE_WATCHER_DEADLINE_UPDATER
                .compareAndSet(this, 0L, System.currentTimeMillis()
                        + client.getConfiguration().getOperationTimeoutMs());

        // synchronized this, because redeliverUnAckMessage eliminate the epoch inconsistency between them
        synchronized (this) {
            setClientCnx(cnx);
            BaseCommand watchRequest = Commands.newWatchTopicList(requestId, watcherId, namespace.toString(),
                            topicsPattern.pattern(), topicsHash);

            cnx.newWatchTopicList(watchRequest, requestId)

                    .thenAccept(response -> {
                        synchronized (TopicListWatcher.this) {
                            if (!changeToReadyState()) {
                                // Watcher was closed while reconnecting, close the connection to make sure the broker
                                // drops the watcher on its side
                                setState(State.Closed);
                                deregisterFromClientCnx();
                                cnx.channel().close();
                                return;
                            }
                        }

                        this.connectionHandler.resetBackoff();

                        watcherFuture.complete(this);

                    }).exceptionally((e) -> {
                        deregisterFromClientCnx();
                        if (getState() == State.Closing || getState() == State.Closed) {
                            // Watcher was closed while reconnecting, close the connection to make sure the broker
                            // drops the watcher on its side
                            cnx.channel().close();
                            return null;
                        }
                        log.warn("[{}][{}] Failed to subscribe to topic on {}", topic,
                                getHandlerName(), cnx.channel().remoteAddress());

                        if (e.getCause() instanceof PulsarClientException
                                && PulsarClientException.isRetriableError(e.getCause())
                                && System.currentTimeMillis()
                                    < CREATE_WATCHER_DEADLINE_UPDATER.get(TopicListWatcher.this)) {
                            reconnectLater(e.getCause());
                        } else if (!watcherFuture.isDone()) {
                            // unable to create new watcher, fail operation
                            setState(State.Failed);
                            watcherFuture.completeExceptionally(
                                    PulsarClientException.wrap(e, String.format("Failed to create topic list watcher %s"
                                                    + "when connecting to the broker", getHandlerName())));
                        } else {
                            // watcher was subscribed and connected, but we got some error, keep trying
                            reconnectLater(e.getCause());
                        }
                        return null;
                    });
        }
    }

    @Override
    String getHandlerName() {
        return name;
    }

    public boolean isConnected() {
        return getClientCnx() != null && (getState() == State.Ready);
    }

    public ClientCnx getClientCnx() {
        return this.connectionHandler.cnx();
    }

    public CompletableFuture<Void> closeAsync() {

        CompletableFuture<Void> closeFuture = new CompletableFuture<>();

        if (getState() == State.Closing || getState() == State.Closed) {
            closeFuture.complete(null);
            return closeFuture;
        }

        if (!isConnected()) {
            log.info("[{}] [{}] Closed watcher (not connected)", topic, getHandlerName());
            setState(State.Closed);
            deregisterFromClientCnx();
            closeFuture.complete(null);
            return closeFuture;
        }

        setState(State.Closing);

        long requestId = client.newRequestId();

        ClientCnx cnx = cnx();
        if (null == cnx) {
            cleanupAtClose(closeFuture, null);
        } else {
            BaseCommand cmd = Commands.newWatchTopicListClose(watcherId, requestId);
            cnx.newWatchTopicListClose(cmd, requestId).handle((v, exception) -> {
                final ChannelHandlerContext ctx = cnx.ctx();
                boolean ignoreException = ctx == null || !ctx.channel().isActive();
                if (ignoreException && exception != null) {
                    log.debug("Exception ignored in closing watcher", exception);
                }
                cleanupAtClose(closeFuture, ignoreException ? null : exception);
                return null;
            });
        }

        return closeFuture;
    }

    // wrapper for connection methods
    ClientCnx cnx() {
        return this.connectionHandler.cnx();
    }

    public void connectionClosed(ClientCnx clientCnx) {
        this.connectionHandler.connectionClosed(clientCnx);
    }

    void setClientCnx(ClientCnx clientCnx) {
        if (clientCnx != null) {
            this.connectionHandler.setClientCnx(clientCnx);
            clientCnx.registerTopicListWatcher(watcherId, this);
        }
        ClientCnx previousClientCnx = clientCnxUsedForWatcherRegistration.getAndSet(clientCnx);
        if (previousClientCnx != null && previousClientCnx != clientCnx) {
            previousClientCnx.removeTopicListWatcher(watcherId);
        }
    }

    void deregisterFromClientCnx() {
        setClientCnx(null);
    }

    void reconnectLater(Throwable exception) {
        this.connectionHandler.reconnectLater(exception);
    }

    private void cleanupAtClose(CompletableFuture<Void> closeFuture, Throwable exception) {
        log.info("[{}] Closed topic list watcher", getHandlerName());
        setState(State.Closed);
        deregisterFromClientCnx();
        if (exception != null) {
            closeFuture.completeExceptionally(exception);
        } else {
            closeFuture.complete(null);
        }
    }

    public void handleCommandWatchTopicUpdate(CommandWatchTopicUpdate update) {
        List<String> deleted = update.getDeletedTopicsList();
        if (!deleted.isEmpty()) {
            topicsChangeListener.onTopicsRemoved(deleted);
        }
        List<String> added = update.getNewTopicsList();
        if (!added.isEmpty()) {
            topicsChangeListener.onTopicsAdded(added);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Craft;

/**
 * The class name is the UTC timestamp in the format of mYYMMDD_HHMMSS_pluginHandle_migrationName
 */
class m160715_000000_seomatic_addSeoImageTransforms extends BaseMigration
{
	/**
	 * Any migration code in here is wrapped inside of a transaction.
	 *
	 * @return bool
	 */
	public function safeUp()
	{

		// Trim the fat

        $this->alterColumn('seomatic_settings', 'siteSeoTitleSeparator', array(ColumnType::Varchar, 'maxLength' => 10));
        $this->alterColumn('seomatic_settings', 'siteRobots', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteTwitterCardType', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteOpenGraphType', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteLinksQueryInput', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'googleSiteVerification', array(ColumnType::Varchar, 'maxLength' => 100));
        $this->alterColumn('seomatic_settings', 'bingSiteVerification', array(ColumnType::Varchar, 'maxLength' => 100));
        $this->alterColumn('seomatic_settings', 'googleAnalyticsUID', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'googleTagManagerID', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteOwnerType', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteOwnerSubType', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'siteOwnerSpecificType', array(ColumnType::Varchar, 'maxLength' => 50));

        $this->alterColumn('seomatic_settings', 'twitterHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'facebookHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'facebookProfileId', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'facebookAppId', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'linkedInHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'googlePlusHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'youtubeHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'youtubeChannelHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'instagramHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'pinterestHandle', array(ColumnType::Varchar, 'maxLength' => 50));
        $this->alterColumn('seomatic_settings', 'githubHandle', array(ColumnType::Varchar, 'maxLength' => 50));

		// specify columns and AttributeType
		$newColumns = array (
			'seoImageTransform' => ColumnType::Varchar,
			'seoFacebookImageTransform' => ColumnType::Varchar,
			'seoTwitterImageTransform' => ColumnType::Varchar
		);

		$this->_addColumnsAfter("seomatic_meta", $newColumns, "seoKeywords");

		// specify columns and AttributeType
		$newColumns = array (
			'siteSeoImageTransform' => ColumnType::Varchar,
			'siteSeoFacebookImageTransform' => ColumnType::Varchar,
			'siteSeoTwitterImageTransform' => ColumnType::Varchar
		);

		$this->_addColumnsAfter("seomatic_settings", $newColumns, "siteSeoKeywords");

		// return true and let craft know its done
		return true;
	}

	private function _addColumnsAfter($tableName, $newColumns, $afterColumnHandle)
	{

		// this is a foreach loop, enough said
		foreach ($newColumns as $columnName => $columnType)
		{
			// check if the column does NOT exist
			if (!craft()->db->columnExists($tableName, $columnName))
			{
				$this->addColumnAfter($tableName, $columnName, array(
					'column' => $columnType,
					'null'   => false,
					),
					$afterColumnHandle
				);

				// log that we created the new column
				SeomaticPlugin::log("Created the `$columnName` in the `$tableName` table.", LogLevel::Info, true);

			}

			// if the column already exists in the table
			else {

				// tell craft that we couldn't create the column as it alredy exists.
				SeomaticPlugin::log("Column `$columnName` already exists in the `$tableName` table.", LogLevel::Info, true);

			}
		}
	}
}


text:
namespace OpenApoc
{

class Colour
{
  private:
  public:
	Colour(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255) : r(r), g(g), b(b), a(a) {}
	uint8_t r, g, b, a;
	bool operator==(const Colour &other) const
	{
		return (this->r == other.r && this->g == other.g && this->b == other.b &&
		        this->a == other.a);
	}
	bool operator!=(const Colour &other) const { return !(*this == other); }
	// convert html4 color name to a color object (case-insensitive)
	static Colour FromHtmlName(const UString &name);
	// convert a hex triplet such as #ff00ff into a color object (case-insensitive)
	static Colour FromHex(const UString &hexcode);
};

static_assert(sizeof(Colour) == 4, "Colour should be 4 bytes");

struct ColourArgB8888Le
{
	uint8_t r;
	uint8_t g;
	uint8_t b;
	uint8_t a;
};

static const Colour COLOUR_BLACK{0, 0, 0};
static const Colour COLOUR_RED{255, 0, 0};

}; // namespace OpenApoc


text:
import { StackNavigator } from 'react-navigation';
import PrimaryNav from './primary';
import Landing from '../screens/landing';
import Login from '../screens/login';

export default StackNavigator({
  Landing: {
    screen: Landing,
    navigationOptions: {
      header: null
    }
  },
  Login: {
    screen: Login,
    navigationOptions: {
      title: 'Login',
      headerBackTitle: null
    }
  },
  Primary: {
    screen: PrimaryNav,
    navigationOptions: {
      header: null
    }
  }
}, {
  initialRouteName: 'Landing'
});


text:
/**
 *
 */

var async = require('async');

console.time('cost');
var list = [{name:'zhangsan',age:5},{name:'lisi',age:6}];
var count =5;
async.doUntil(
    function(callback){
        setTimeout(function(){
          count --;
            callback();
        },1000)
    },function(){
        return count <0;
    },function(err){
       console.timeEnd('cost');
    }
)


text:
var _ = require('lodash')
  , dbc = require('dbc.js')
  , Cocktail = require('cocktail')
  ;

function Objectify() {
}

Cocktail.mix(Objectify, {
  '@exports': module
});

Objectify.build = function (schema, defaults) {
  var self = this;

  if (_.isObject(schema)) {
    dbc([typeof schema === 'object'], 'Schema type is required');
    createObjectOfType(schema.type);

  } else if (_.isString(schema)) {

    var schemaFromPath = require(schema);
    if (schemaFromPath == null || schemaFromPath.length === 0) {
      throw new Error('Schema path is wrong');
    }

  } else {
    throw new Error('Schema must be a string or an object');
  }
};

function createObjectOfType(type) {
  type = type.toLowerCase() || 'object';
  if (type === 'object')
    return {};
  else if (type === 'boolean')
    return false;
  else if (type === 'string')
    return ''
  else if (type === 'number') {
    return 0;
  } else if (type === 'array') {
    return []
  } else if (type === 'regex') {
    return /\*/;
  } else if (type === 'function') {
    return function () {
    };
  } else if (type === 'undefined') {
    return undefined;
  } else if (type === 'null') {
    return null;
  }
}

module.exports = Objectify;


text:
@implementation TweetCell

- (void)prepareForReuse {
    [super prepareForReuse];
    [self.profileImageView prepareForReuse];
}

- (void)configureWithTweet:(Tweet *)tweet {
    if (tweet.retweetedStatus) {
        self.retweetedByLabel.text = [NSString stringWithFormat:@"%@ retweeted", tweet.user.name];
        tweet = tweet.retweetedStatus;
    } else {
        self.retweetedByLabel.text = nil;
    }

    [self configureDateLabelWithDate:tweet.createdAt];

    if ([tweet.user.profileImageURL length]) {
        [self.profileImageView setUserProfileImageURL:tweet.user.profileImageURL];
    }

    self.nameLabel.text = tweet.user.name;
    self.statusLabel.text = tweet.text;
}

- (CGFloat)height {
    UIView *view = self.retweetedByLabel.text ? self.retweetedByLabel : self.statusLabel;
    return MAX(CGRectGetMaxY(view.frame), CGRectGetMaxY(self.profileImageView.frame)) + 8;
}

- (void)configureDateLabelWithDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];

#if ((defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || \
    (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 101000))
    NSCalendarUnit unitFlags = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay;
#else
    NSCalendarUnit unitFlags = NSSecondCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit;
#endif
    NSDateComponents *components = [calendar components:unitFlags
                                               fromDate:now
                                                 toDate:date
                                                options:0];

    NSString *dateString = NSLocalizedString(@"now", @"");

    if ([components day] != 0) {
        NSUInteger days = ABS([components day]);
        dateString = [NSString stringWithFormat:NSLocalizedString(@"%ud", @""), days];
    } else if ([components hour] != 0) {
        NSUInteger hours = ABS([components hour]);
        dateString = [NSString stringWithFormat:NSLocalizedString(@"%uh", @""), hours];
    } else if ([components minute] != 0) {
        NSUInteger minutes = ABS([components minute]);
        dateString = [NSString stringWithFormat:NSLocalizedString(@"%um", @""), minutes];
    } else if ([components second] != 0) {
        NSUInteger seconds = ABS([components second]);
        dateString = [NSString stringWithFormat:NSLocalizedString(@"%us", @""), seconds];
    }

    self.dateLabel.text = dateString;
}

@end


text:
class User < ActiveRecord::Base
  has_secure_password
  acts_as_messageable
  has_many :trips, foreign_key: :driver_id
  has_many :parcels, foreign_key: :sender_id

  has_many :reviews, foreign_key: :reviewer_id
  has_many :received_reviews, class_name: "Review", foreign_key: :reviewee_id
  # has_many :driver_reviews, class_name: "Review", through: :trips, source: :driver
  # has_many :sender_reviews, class_name: "Review", through: :parcels, source: :sender

  validates :username, presence: true, uniqueness: true

  def get_reputation
    reviews =  self.received_reviews
    reviews.map do |review|
      review.rating
    end.reduce(:+)/(reviews.count)
  end

  # method for mailbox gem
  def name
    username
  end

  def mailboxer_email(object)
    nil # no mail to be sent by mailbox
  end
end


text:
package edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.util.comp;

import java.util.List;

import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.math.ArrayDimensionNode;
import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.ibiosim.analysis.simulation.hierarchical.math.HierarchicalNode;

/**
 * Container for events that have been triggered.
 *
 * @author Leandro Watanabe
 * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
 * @version %I%
 */
public class TriggeredEvent implements Comparable<TriggeredEvent> {
  private double priority;
  private double[] assignmentValues;
  private final int index;
  private final double fireTime;
  private final EventNode parent;
  private boolean hasFlipped;
  private final double[] eventDimensions;

  public TriggeredEvent(int index, double fireTime, EventNode parent) {
    this.parent = parent;
    this.index = index;
    this.hasFlipped = false;
    this.fireTime = fireTime;
    if (parent.isArray()) {
      List<ArrayDimensionNode> dimensions = parent.getListOfDimensions();
      eventDimensions = new double[dimensions.size()];
      for (int i = 0; i < dimensions.size(); i++) {
        eventDimensions[i] = dimensions.get(i).getValue(index);
      }
    } else {
      eventDimensions = null;
    }
  }

  /**
   * Gets the index of the model that had the event triggered.
   *
   * @return the model index.
   */
  public int getIndex() {
    return index;
  }

  /**
   * Gets the firing time of the triggered event.
   *
   * @return the fire time.
   */
  public double getFireTime() {
    return fireTime;
  }

  /**
   * Gets the triggered event priority.
   *
   * @return the priority.
   */
  public double getPriority() {
    return priority;
  }

  /**
   * Sets the priority of the triggered event.
   *
   * @param priority
   *          - the new priority.
   */
  public void setPriority(double priority) {
    this.priority = priority;
  }

  /**
   * Gets the reference to the triggered event node.
   *
   * @return the event node.
   */
  public EventNode getParent() {
    return parent;
  }

  /**
   * Checks if the event has its triggering condition changing to false before firing.
   */
  public void setFlipped() {
    hasFlipped = true;
  }

  /**
   * Sets the event assignment values.
   *
   * @param assignmentValues
   *          - the evaluated event assignments.
   */
  public void setAssignmentValues(double[] assignmentValues) {
    this.assignmentValues = assignmentValues;
  }

  /**
   * Fire the event and perform the event assignments.
   *
   * @param time
   *          - current time.
   */
  public void fireEvent(double time) {

    if (fireTime <= time) {

      if (!parent.getState().getChild(index).isPersistent()) {
        if (hasFlipped) { return; }
      }
      if (eventDimensions != null) {
        List<ArrayDimensionNode> dimensions = parent.getListOfDimensions();
        for (int i = eventDimensions.length - 1; i >= 0; i--) {
          dimensions.get(i).setValue(index, eventDimensions[i]);
        }
      }
      if (!parent.getState().getChild(index).isUseTriggerValue()) {
        double[] eventAssignments = parent.computeEventAssignmentValues(index);

        if (eventAssignments != null) {
          setAssignmentValues(eventAssignments);
        }
      }

      if (assignmentValues != null) {
        List<FunctionNode> eventAssignments = parent.getEventAssignments();
        int assignmentIndex = 0;
        for (FunctionNode eventAssigment : eventAssignments) {
          for (HierarchicalNode subNode : eventAssigment) {
            eventAssigment.updateVariable(index, assignmentValues[assignmentIndex++]);
          }
        }
      }
    }

  }

  @Override
  public int compareTo(TriggeredEvent event2) {
    if (this.getFireTime() > event2.getFireTime()) {
      return 1;
    } else if (this.getFireTime() < event2.getFireTime()) {
      return -1;
    } else {
      if (this.getPriority() > event2.getPriority()) {
        return -1;
      } else if (this.getPriority() < event2.getPriority()) {
        return 1;
      } else {
        return Math.random() >= 0.5 ? 1 : -1;
      }

    }
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Contact controller contain contact related functions
 * @package    CI
 * @subpackage Controller
 * @author  Antony
 */

class Contact extends Site_Controller{

    function __construct(){
        parent::__construct();
        $this->load->model('site/contact_model');
        $this->load->library('MailChimp');
        $this->load->model('site/email_model');
        }
    /*
     * function name :index
     * To display contact us form
     *
     * @author  Antony
     * @access  public
     * @param :
     * @return : none
     */

    public function index(){
    	  $this->form_validation->set_rules('name', 'Name', 'trim|required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('contactno', 'Contact Us', 'required|numeric|min_length[10]|max_length[10]');
        $this->form_validation->set_rules('message', 'Message', 'required');
        if ($this->form_validation->run() == FALSE){
    	  $this->render('index');
        }else{
        	$name = $this->input->post('name');
            $email = $this->input->post('email');
            $contactno = $this->input->post('contactno');
            $message = $this->input->post('message');
            $data=array(
              'name'=>$name,
              'email'=>$email,
              'contact_no'=>$contactno,
              'message'=>$message,
            	);
            $this->db->set('created_date', 'NOW()', FALSE);
            $this->contact_model->insert_message($data);

            $data1=array($name,$email,$contactno,$message);
            $arr1=array('{name}','{email}','{contact no.}','{comment}');
            $contact_us=$this->email_model->template('contact us');
            $subject=$contact_us->subject;
            $content=$contact_us->content;
            $var_content=str_replace($arr1,$data1,$content);

            $contact_us=array(
             'email'=>'antony.george@neosofttech.com',
             'subject'=>$subject,
             'content'=>$var_content,
              );
            //var_dump($contact_us);die();
            $this->email_model->email($contact_us);

            $this->session->set_flashdata('success', 'Your message has been sent successfully');
            $this->render('index');
        }
    }

    /*
     * function name :newsletter
     * To send subscription mail through mailchimp
     * @author  Antony
     * @access  public
     * @param :
     * @return :
     */
    public function newsletter(){

        $email = $this->input->post('newsletter');

        $list_id= LIST_KEY;

        $result = $this->mailchimp->post("lists/$list_id/members", [ 'email_address' => $email, 'status' => 'subscribed', ]);

        if($result){
            $this->session->set_flashdata('newsletter', 'You have been subscribed to Newsletter');
           redirect('site/home');

        }else{
            $this->session->set_flashdata('newsletter_error', 'Try again');
           redirect('site/home');
        }

     }
}


text:
/**
   * Bootstrap 3 templates
   */
  Form.template = _.template('\
    <form class="form-horizontal" role="form">\

\
      <% if (submitButton) { %>\
        <button type="submit" class="btn"><%= submitButton %></button>\
      <% } %>\
    </form>\
  ');

  Form.Fieldset.template = _.template('\
    <fieldset data-fields>\
      <% if (legend) { %>\
        <legend><%= legend %></legend>\
      <% } %>\
    </fieldset>\
  ');

  Form.Field.template = _.template('\
    <div class="form-group field-<%= key %>">\
      <label class="col-sm-2 control-label" for="<%= editorId %>">\
        <% if (titleHTML){ %><%= titleHTML %>\
        <% } else { %><%- title %><% } %>\
      \

\
        \

\

<%= help %>
\

\

\
  ');

  Form.NestedField.template = _.template('\
    <div class="field-<%= key %>">\
      <div title="<% if (titleHTML){ %><%= titleHTML %><% } else { %><%- title %><% } %>" class="input-xlarge">\
        \

\

\

<%= help %>
\

\
  ');

  Form.editors.Base.prototype.className = 'form-control';
  Form.editors.Checkbox.prototype.className = 'checkbox';
  Form.editors.Checkboxes.prototype.className = 'checkbox';
  Form.editors.Radio.prototype.className = 'radio';
  Form.Field.errorClassName = 'has-error';

  if (Form.editors.List) {

    Form.editors.List.template = _.template('\

\

\
        <button type="button" class="btn bbf-add" data-action="add">Add</button>\

\
    ');

    Form.editors.List.Item.template = _.template('\

\

\
        <button type="button" class="btn bbf-del" data-action="remove">×</button>\

\
    ');

    Form.editors.List.Object.template = Form.editors.List.NestedModel.template = _.template('\

<%= summary %>
\
    ');

  }


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>NG6-Starter by @AngularClass</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="description" content="NG6-Starter by @AngularClass">
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <base href="/">
  </head>
  <body ng-app="app" ng-strict-di ng-cloak>
    <app>
      Loading...
    </app>
  <script src="/dist/vendor.bundle.js"></script><script src="/dist/app.bundle.js"></script></body>
</html>


text:
from django.contrib.auth import get_user_model

from loginurl.models import Key

class LoginUrlBackend(object):
    """
    Authentication backend that checks the given ``key`` to a record in the
    ``Key`` model. If the record is found, then ``is_valid()`` method is called
    to check if the key is still valid.
    """
    supports_object_permissions = False
    supports_anonymous_user = False

    def authenticate(self, key):
        """
        Check if the key is valid.
        """
        data = Key.objects.filter(key=key)
        if len(data) == 0:
            return None

        data = data[0]
        if not data.is_valid():
            return None

        return data.user

    def get_user(self, user_id):
        user_model = get_user_model()
        try:
            return user_model.objects.get(pk=user_id)
        except user_model.DoesNotExist:
            return None


text:
Pattern: Missing blank lines around access modifier

Issue: -

## Description

Access modifiers should be surrounded by blank lines.

## Examples

```ruby
# bad
class Foo
  def bar; end
  private
  def baz; end
end

# good
class Foo
  def bar; end

  private

  def baz; end
end
```

## Further Reading

* [RuboCop - Layout/EmptyLinesAroundAccessModifier](https://rubocop.readthedocs.io/en/latest/cops_layout/#layoutemptylinesaroundaccessmodifier)
* [https://github.com/bbatsov/ruby-style-guide#empty-lines-around-access-modifier](https://github.com/bbatsov/ruby-style-guide#empty-lines-around-access-modifier)


text:
from google.cloud.billing import gapic_version as package_version

__version__ = package_version.__version__

from google.cloud.billing_v1.services.cloud_billing.async_client import (
    CloudBillingAsyncClient,
)
from google.cloud.billing_v1.services.cloud_billing.client import CloudBillingClient
from google.cloud.billing_v1.services.cloud_catalog.async_client import (
    CloudCatalogAsyncClient,
)
from google.cloud.billing_v1.services.cloud_catalog.client import CloudCatalogClient
from google.cloud.billing_v1.types.cloud_billing import (
    BillingAccount,
    CreateBillingAccountRequest,
    GetBillingAccountRequest,
    GetProjectBillingInfoRequest,
    ListBillingAccountsRequest,
    ListBillingAccountsResponse,
    ListProjectBillingInfoRequest,
    ListProjectBillingInfoResponse,
    ProjectBillingInfo,
    UpdateBillingAccountRequest,
    UpdateProjectBillingInfoRequest,
)
from google.cloud.billing_v1.types.cloud_catalog import (
    AggregationInfo,
    Category,
    GeoTaxonomy,
    ListServicesRequest,
    ListServicesResponse,
    ListSkusRequest,
    ListSkusResponse,
    PricingExpression,
    PricingInfo,
    Service,
    Sku,
)

__all__ = (
    "CloudBillingClient",
    "CloudBillingAsyncClient",
    "CloudCatalogClient",
    "CloudCatalogAsyncClient",
    "BillingAccount",
    "CreateBillingAccountRequest",
    "GetBillingAccountRequest",
    "GetProjectBillingInfoRequest",
    "ListBillingAccountsRequest",
    "ListBillingAccountsResponse",
    "ListProjectBillingInfoRequest",
    "ListProjectBillingInfoResponse",
    "ProjectBillingInfo",
    "UpdateBillingAccountRequest",
    "UpdateProjectBillingInfoRequest",
    "AggregationInfo",
    "Category",
    "GeoTaxonomy",
    "ListServicesRequest",
    "ListServicesResponse",
    "ListSkusRequest",
    "ListSkusResponse",
    "PricingExpression",
    "PricingInfo",
    "Service",
    "Sku",
)


text:
@parent aleph-frontend
@module {can.Component} aleph-frontend/ventas/reportes <aleph-ventas-reportes>

A short description of the aleph-ventas-reportes component

@signature `<aleph-ventas-reportes>`

@body

## Use


text:
import warnings
from inspect import signature
import functools as ft
from typing import List, Dict

import numpy as np

from .broadbean import PulseAtoms, marked_for_deletion

class SegmentDurationError(Exception):
    pass

class BluePrint():
    """
    The class of a waveform to become.
    """

    def __init__(self, funlist=None, argslist=None, namelist=None,
                 marker1=None, marker2=None, segmentmarker1=None,
                 segmentmarker2=None, SR=None, durslist=None):
        """
        Create a BluePrint instance

        Args:
            funlist (list): List of functions
            argslist (list): List of tuples of arguments
            namelist (list): List of names for the functions
            marker1 (list): List of marker1 specification tuples
            marker2 (list): List of marker2 specifiation tuples
            durslist (list): List of durations

        Returns:
            BluePrint
        """
        # TODO: validate input

        # Sanitising
        if funlist is None:
            funlist = []
        if argslist is None:
            argslist = []
        if namelist is None:
            namelist = []
        if durslist is None:
            durslist = []

        # Are the lists of matching lengths?
        lenlist = [len(funlist), len(argslist), len(namelist), len(durslist)]

        if len(set(lenlist)) is not 1:
            raise ValueError('All input lists must be of same length. '
                             'Received lengths: {}'.format(lenlist))
        # Are the names valid names?
        for name in namelist:
            if not isinstance(name, str):
                raise ValueError('All segment names must be strings. '
                                 'Received {}'.format(name))
            elif name is not '':
                if name[-1].isdigit():
                    raise ValueError('Segment names are not allowed to end'
                                     ' in a number. {} is '.format(name) +
                                     'therefore not a valid name.')

        self._funlist = funlist

        # Make special functions live in the funlist but transfer their names
        # to the namelist
        # Infer names from signature if not given, i.e. allow for '' names
        for ii, name in enumerate(namelist):
            if isinstance(funlist[ii], str):
                namelist[ii] = funlist[ii]
            elif name == '':
                namelist[ii] = funlist[ii].__name__

        # Allow single arguments to be given as not tuples
        for ii, args in enumerate(argslist):
            if not isinstance(args, tuple):
                argslist[ii] = (args,)
        self._argslist = argslist

        self._namelist = namelist
        namelist = self._make_names_unique(namelist)

        # initialise markers
        if marker1 is None:
            self.marker1 = []
        else:
            self.marker1 = marker1
        if marker2 is None:
            self.marker2 = []
        else:
            self.marker2 = marker2
        if segmentmarker1 is None:
            self._segmark1 = [(0, 0)]*len(funlist)
        else:
            self._segmark1 = segmentmarker1
        if segmentmarker2 is None:
            self._segmark2 = [(0, 0)]*len(funlist)
        else:
            self._segmark2 = segmentmarker2

        if durslist is not None:
            self._durslist = list(durslist)
        else:
            self._durslist = None

        self._SR = SR

    @staticmethod
    def _basename(string):
        """
        Remove trailing numbers from a string.
        """

        if not isinstance(string, str):
            raise ValueError('_basename received a non-string input!'
                             ' Got the following: {}'.format(string))

        if string == '':
            return string
        if not(string[-1].isdigit()):
            return string
        else:
            counter = 0
            for ss in string[::-1]:
                if ss.isdigit():
                    counter += 1
                else:
                    break
            return string[:-counter]

        # lst = [letter for letter in string if not letter.isdigit()]
        # return ''.join(lst)

    @staticmethod
    def _make_names_unique(lst):
        """
        Make all strings in the input list unique
        by appending numbers to reoccuring strings

        Args:
            lst (list): List of strings. Intended for the _namelist

        """

        if not isinstance(lst, list):
            raise ValueError('_make_names_unique received a non-list input!'
                             ' Got {}'.format(lst))

        baselst = [BluePrint._basename(lstel) for lstel in lst]
        uns = np.unique(baselst)

        for un in uns:
            inds = [ii for ii, el in enumerate(baselst) if el == un]
            for ii, ind in enumerate(inds):
                # Do not append numbers to the first occurence
                if ii == 0:
                    lst[ind] = '{}'.format(un)
                else:
                    lst[ind] = '{}{}'.format(un, ii+1)

        return lst

    @property
    def length_segments(self):
        """
        Returns the number of segments in the blueprint
        """
        return len(self._namelist)

    @property
    def duration(self):
        """
        The total duration of the BluePrint. If necessary, all the arrays
        are built.
        """
        waits = 'waituntil' in self._funlist
        ensavgs = 'ensureaverage_fixed_level' in self._funlist

        if (not(waits) and not(ensavgs)):
            return sum(self._durslist)
        elif (waits and not(ensavgs)):
            waitdurations = self._makeWaitDurations()
            return sum(waitdurations)
        elif ensavgs:
            # TODO: call the forger
            raise NotImplementedError('ensureaverage_fixed_level does not'
                                      ' exist yet. Cannot proceed')

    @property
    def points(self):
        """
        The total number of points in the BluePrint. If necessary,
        all the arrays are built.
        """
        waits = 'waituntil' in self._funlist
        ensavgs = 'ensureaverage_fixed_level' in self._funlist
        SR = self.SR

        if SR is None:
            raise ValueError('No sample rate specified, can not '
                             'return the number of points.')

        if (not(waits) and not(ensavgs)):
            return int(np.round(sum(self._durslist)*SR))
        elif (waits and not(ensavgs)):
            waitdurations = self._makeWaitDurations()
            return int(np.round(sum(waitdurations)*SR))
        elif ensavgs:
            # TODO: call the forger
            raise NotImplementedError('ensureaverage_fixed_level does not'
                                      ' exist yet. Cannot proceed')

    @property
    def durations(self):
        """
        The list of durations
        """
        return self._durslist

    @property
    def SR(self):
        """
        Sample rate of the blueprint
        """
        return self._SR

    @property
    def description(self):
        """
        Returns a dict describing the blueprint.
        """
        desc = {}  # the dict to return

        no_segs = len(self._namelist)

        for sn in range(no_segs):
            segkey = 'segment_{:02d}'.format(sn+1)
            desc[segkey] = {}
            desc[segkey]['name'] = self._namelist[sn]
            if self._funlist[sn] == 'waituntil':
                desc[segkey]['function'] = self._funlist[sn]
            else:
                funname = str(self._funlist[sn])[1:]
                funname = funname[:funname.find(' at')]
                desc[segkey]['function'] = funname
            desc[segkey]['durations'] = self._durslist[sn]
            if desc[segkey]['function'] == 'waituntil':
                desc[segkey]['arguments'] = {'waittime': self._argslist[sn]}
            else:
                sig = signature(self._funlist[sn])
                desc[segkey]['arguments'] = dict(zip(sig.parameters,
                                                     self._argslist[sn]))

        desc['marker1_abs'] = self.marker1
        desc['marker2_abs'] = self.marker2
        desc['marker1_rel'] = self._segmark1
        desc['marker2_rel'] = self._segmark2

        return desc

    def _makeWaitDurations(self):
        """
        Translate waituntills into durations and return that list.
        """

        if 'ensureaverage_fixed_level' in self._funlist:
            raise NotImplementedError('There is an "ensureaverage_fixed_level"'
                                      ' in this BluePrint. Cannot compute.')

        funlist = self._funlist.copy()
        durations = self._durslist.copy()
        argslist = self._argslist

        no_of_waits = funlist.count('waituntil')

        waitpositions = [ii for ii, el in enumerate(funlist)
                         if el == 'waituntil']

        # Calculate elapsed times

        for nw in range(no_of_waits):
            pos = waitpositions[nw]
            funlist[pos] = PulseAtoms.waituntil
            elapsed_time = sum(durations[:pos])
            wait_time = argslist[pos][0]
            dur = wait_time - elapsed_time
            if dur < 0:
                raise ValueError('Inconsistent timing. Can not wait until ' +
                                 '{} at position {}.'.format(wait_time, pos) +
                                 ' {} elapsed already'.format(elapsed_time))
            else:
                durations[pos] = dur

        return durations

    def showPrint(self):
        """
        Pretty-print the contents of the BluePrint. Not finished.
        """
        # TODO: tidy up this method and make it use the description property

        if self._durslist is None:
            dl = [None]*len(self._namelist)
        else:
            dl = self._durslist

        datalists = [self._namelist, self._funlist, self._argslist,
                     dl]

        lzip = zip(*datalists)

        print('Legend: Name, function, arguments, timesteps, durations')

        for ind, (name, fun, args, dur) in enumerate(lzip):
            ind_p = ind+1
            if fun == 'waituntil':
                fun_p = fun
            else:
                fun_p = fun.__str__().split(' ')[1]

            list_p = [ind_p, name, fun_p, args, dur]
            print('Segment {}: "{}", {}, {}, {}'.format(*list_p))
        print('-'*10)

    def changeArg(self, name, arg, value, replaceeverywhere=False):
        """
        Change an argument of one or more of the functions in the blueprint.

        Args:
            name (str): The name of the segment in which to change an argument
            arg (Union[int, str]): Either the position (int) or name (str) of
                the argument to change
            value (Union[int, float]): The new value of the argument
            replaceeverywhere (bool): If True, the same argument is overwritten
                in ALL segments where the name matches. E.g. 'gaussian1' will
                match 'gaussian', 'gaussian2', etc. If False, only the segment
                with exact name match gets a replacement.

        Raises:
            ValueError: If the argument can not be matched (either the argument
                name does not match or the argument number is wrong).
            ValueError: If the name can not be matched.

        """
        # TODO: is there any reason to use tuples internally?

        if replaceeverywhere:
            basename = BluePrint._basename
            name = basename(name)
            nmlst = self._namelist
            replacelist = [nm for nm in nmlst if basename(nm) == name]
        else:
            replacelist = [name]

        # Validation
        if name not in self._namelist:
            raise ValueError('No segment of that name in blueprint.'
                             ' Contains segments: {}'.format(self._namelist))

        for name in replacelist:

            position = self._namelist.index(name)
            function = self._funlist[position]
            sig = signature(function)

            # Validation
            if isinstance(arg, str):
                if arg not in sig.parameters:
                    raise ValueError('No such argument of function '
                                     '{}.'.format(function.__name__) +
                                     'Has arguments '
                                     '{}.'.format(sig.parameters.keys()))
            # Each function has two 'secret' arguments, SR and dur
            user_params = len(sig.parameters)-2
            if isinstance(arg, int) and (arg not in range(user_params)):
                raise ValueError('No argument {} '.format(arg) +
                                 'of function {}.'.format(function.__name__) +
                                 ' Has {} '.format(user_params) +
                                 'arguments.')

            # allow the user to input single values instead of (val,)
            no_of_args = len(self._argslist[position])
            if not isinstance(value, tuple) and no_of_args == 1:
                value = (value,)

            if isinstance(arg, str):
                for ii, param in enumerate(sig.parameters):
                    if arg == param:
                        arg = ii
                        break

            # Mutating the immutable...
            larg = list(self._argslist[position])
            larg[arg] = value
            self._argslist[position] = tuple(larg)

    def changeDuration(self, name, dur, replaceeverywhere=False):
        """
        Change the duration of one or more segments in the blueprint

        Args:
            name (str): The name of the segment in which to change duration
            dur (Union[float, int]): The new duration.
            replaceeverywhere (Optional[bool]): If True, the duration(s)
                is(are) overwritten in ALL segments where the name matches.
                E.g. 'gaussian1' will match 'gaussian', 'gaussian2',
                etc. If False, only the segment with exact name match
                gets a replacement.

        Raises:
            ValueError: If durations are not specified for the blueprint
            ValueError: If too many or too few durations are given.
            ValueError: If no segment matches the name.
            ValueError: If dur is not positive
            ValueError: If SR is given for the blueprint and dur is less than
                1/SR.
        """

        if (not(isinstance(dur, float)) and not(isinstance(dur, int))):
            raise ValueError('New duration must be an int or a float. '
                             'Received {}'.format(type(dur)))

        if replaceeverywhere:
            basename = BluePrint._basename
            name = basename(name)
            nmlst = self._namelist
            replacelist = [nm for nm in nmlst if basename(nm) == name]
        else:
            replacelist = [name]

        # Validation
        if name not in self._namelist:
            raise ValueError('No segment of that name in blueprint.'
                             ' Contains segments: {}'.format(self._namelist))

        for name in replacelist:
            position = self._namelist.index(name)

            if dur <= 0:
                raise ValueError('Duration must be strictly greater '
                                 'than zero.')

            if self.SR is not None:
                if dur*self.SR < 1:
                    raise ValueError('Duration too short! Must be at'
                                     ' least 1/sample rate.')

            self._durslist[position] = dur

    def setSR(self, SR):
        """
        Set the associated sample rate

        Args:
            SR (Union[int, float]): The sample rate in Sa/s.
        """
        self._SR = SR

    def setSegmentMarker(self, name, specs, markerID):
        """
        Bind a marker to a specific segment.

        Args:
            name (str): Name of the segment
            specs (tuple): Marker specification tuple, (delay, duration),
                where the delay is relative to the segment start
            markerID (int): Which marker channel to output on. Must be 1 or 2.
        """
        if markerID not in [1, 2]:
            raise ValueError('MarkerID must be either 1 or 2.'
                             ' Received {}.'.format(markerID))

        markerselect = {1: self._segmark1, 2: self._segmark2}
        position = self._namelist.index(name)

        # TODO: Do we need more than one bound marker per segment?
        markerselect[markerID][position] = specs

    def removeSegmentMarker(self, name: str, markerID: int) -> None:
        """
        Remove all bound markers from a specific segment

        Args:
            name (str): Name of the segment
            markerID (int): Which marker channel to remove from (1 or 2).
            number (int): The number of the marker, in case several markers are
                bound to one element. Default: 1 (the first marker).
        """
        if markerID not in [1, 2]:
            raise ValueError('MarkerID must be either 1 or 2.'
                             ' Received {}.'.format(markerID))

        markerselect = {1: self._segmark1, 2: self._segmark2}
        try:
            position = self._namelist.index(name)
        except ValueError:
            raise KeyError('No segment named {} in this BluePrint.'
                           ''.format(name))
        markerselect[markerID][position] = (0, 0)

    def copy(self):
        """
        Returns a copy of the BluePrint
        """

        # Needed because of input validation in __init__
        namelist = [self._basename(name) for name in self._namelist.copy()]

        return BluePrint(self._funlist.copy(),
                         self._argslist.copy(),
                         namelist,
                         self.marker1.copy(),
                         self.marker2.copy(),
                         self._segmark1.copy(),
                         self._segmark2.copy(),
                         self._SR,
                         self._durslist)

    def insertSegment(self, pos, func, args=(), dur=None, name=None,
                      durs=None):
        """
        Insert a segment into the bluePrint.

        Args:
            pos (int): The position at which to add the segment. Counts like
                a python list; 0 is first, -1 is last. Values below -1 are
                not allowed, though.
            func (function): Function describing the segment. Must have its
               duration as the last argument (unless its a special function).
            args (Optional[Tuple[Any]]): Tuple of arguments BESIDES duration.
                Default: ()
            dur (Optional[Union[int, float]]): The duration of the
                segment. Must be given UNLESS the segment is
                'waituntil' or 'ensureaverage_fixed_level'
            name Optional[str]: Name of the segment. If none is given,
                the segment will receive the name of its function,
                possibly with a number appended.

        Raises:
            ValueError: If the position is negative
            ValueError: If the name ends in a number
        """

        # Validation
        has_ensureavg = ('ensureaverage_fixed_level' in self._funlist or
                         'ensureaverage_fixed_dur' in self._funlist)
        if func == 'ensureaverage_fixed_level' and has_ensureavg:
            raise ValueError('Can not have more than one "ensureaverage"'
                             ' segment in a blueprint.')

        if durs is not None:
            warnings.warn('Deprecation warning: please specify "dur" rather '
                          'than "durs" when inserting a segment')
            if dur is None:
                dur = durs
            else:
                raise ValueError('You can not specify "durs" AND "dur"!')
        # Take care of 'waituntil'

        # allow users to input single values
        if not isinstance(args, tuple):
            args = (args,)

        if pos < -1:
            raise ValueError('Position must be strictly larger than -1')

        if name is None or name == '':
            if func == 'waituntil':
                name = 'waituntil'
            else:
                name = func.__name__
        elif isinstance(name, str):
            if len(name) > 0:
                if name[-1].isdigit():
                    raise ValueError('Segment name must not end in a number')

        if pos == -1:
            self._namelist.append(name)
            self._namelist = self._make_names_unique(self._namelist)
            self._funlist.append(func)
            self._argslist.append(args)
            self._segmark1.append((0, 0))
            self._segmark2.append((0, 0))
            self._durslist.append(dur)
        else:
            self._namelist.insert(pos, name)
            self._namelist = self._make_names_unique(self._namelist)
            self._funlist.insert(pos, func)
            self._argslist.insert(pos, args)
            self._segmark1.insert(pos, (0, 0))
            self._segmark2.insert(pos, (0, 0))
            self._durslist.insert(pos, dur)

    def removeSegment(self, name):
        """
        Remove the specified segment from the blueprint.

        Args:
            name (str): The name of the segment to remove.
        """
        try:
            position = self._namelist.index(name)
        except ValueError:
            raise KeyError('No segment called {} in blueprint.'.format(name))

        del self._funlist[position]
        del self._argslist[position]
        del self._namelist[position]
        del self._segmark1[position]
        del self._segmark2[position]
        del self._durslist[position]

        self._namelist = self._make_names_unique(self._namelist)

    @marked_for_deletion(replaced_by='broadbean.plotting.plotter')
    def plot(self, SR=None):
        pass

    def __add__(self, other):
        """
        Add two BluePrints. The second argument is appended to the first
        and a new BluePrint is returned.

        Args:
            other (BluePrint): A BluePrint instance

        Returns:
            BluePrint: A new blueprint.

        Raises:
            ValueError: If the input is not a BluePrint instance
        """
        if not isinstance(other, BluePrint):
            raise ValueError("""
                             BluePrint can only be added to another Blueprint.
                             Received an object of type {}
                             """.format(type(other)))

        nl = [self._basename(name) for name in self._namelist]
        nl += [self._basename(name) for name in other._namelist]
        al = self._argslist + other._argslist
        fl = self._funlist + other._funlist
        m1 = self.marker1 + other.marker1
        m2 = self.marker2 + other.marker2
        sm1 = self._segmark1 + other._segmark1
        sm2 = self._segmark2 + other._segmark2
        dl = self._durslist + other._durslist

        new_bp = BluePrint()

        new_bp._namelist = new_bp._make_names_unique(nl.copy())
        new_bp._funlist = fl.copy()
        new_bp._argslist = al.copy()
        new_bp.marker1 = m1.copy()
        new_bp.marker2 = m2.copy()
        new_bp._segmark1 = sm1.copy()
        new_bp._segmark2 = sm2.copy()
        new_bp._durslist = dl.copy()

        if self.SR is not None:
            new_bp.setSR(self.SR)

        return new_bp

    def __eq__(self, other):
        """
        Compare two blueprints. They are the same iff all
        lists are identical.

        Args:
            other (BluePrint): A BluePrint instance

        Returns:
            bool: whether the two blueprints are identical

        Raises:
            ValueError: If the input is not a BluePrint instance
        """
        if not isinstance(other, BluePrint):
            raise ValueError("""
                             Blueprint can only be compared to another
                             Blueprint.
                             Received an object of type {}
                             """.format(type(other)))

        if not self._namelist == other._namelist:
            return False
        if not self._funlist == other._funlist:
            return False
        if not self._argslist == other._argslist:
            return False
        if not self.marker1 == other.marker1:
            return False
        if not self.marker2 == other.marker2:
            return False
        if not self._segmark1 == other._segmark1:
            return False
        if not self._segmark2 == other._segmark2:
            return False
        return True

def _subelementBuilder(blueprint: BluePrint, SR: int,
                       durs: List[float]) -> Dict[str, np.ndarray]:
    """
    The function building a blueprint, returning a numpy array.

    This is the core translater from description of pulse to actual data points
    All arrays must be made with this function
    """

    # Important: building the element must NOT modify any of the mutable
    # inputs, therefore all lists are copied
    funlist = blueprint._funlist.copy()
    argslist = blueprint._argslist.copy()
    namelist = blueprint._namelist.copy()
    marker1 = blueprint.marker1.copy()
    marker2 = blueprint.marker2.copy()
    segmark1 = blueprint._segmark1.copy()
    segmark2 = blueprint._segmark2.copy()

    durations = durs.copy()

    no_of_waits = funlist.count('waituntil')

    # handle waituntil by translating it into a normal function
    waitpositions = [ii for ii, el in enumerate(funlist) if el == 'waituntil']

    # Calculate elapsed times

    for nw in range(no_of_waits):
        pos = waitpositions[nw]
        funlist[pos] = PulseAtoms.waituntil
        elapsed_time = sum(durations[:pos])
        wait_time = argslist[pos][0]
        dur = wait_time - elapsed_time
        if dur < 0:
            raise ValueError('Inconsistent timing. Can not wait until ' +
                             '{} at position {}.'.format(wait_time, pos) +
                             ' {} elapsed already'.format(elapsed_time))
        else:
            durations[pos] = dur

    # When special segments like 'waituntil' and 'ensureaverage' get
    # evaluated, the list of durations gets updated. That new list
    # is newdurations

    newdurations = np.array(durations)

    # All waveforms must ultimately have an integer number of samples
    # Now figure out from the durations what these integers are
    #
    # The most honest thing to do is to simply round off dur*SR
    # and raise an exception if the segment ends up with less than
    # two points

    intdurations = np.zeros(len(newdurations))

    for ii, dur in enumerate(newdurations):
        int_dur = round(dur*SR)
        if int_dur < 2:
            raise SegmentDurationError('Too short segment detected! '
                                       'Segment "{}" at position {} '
                                       'has a duration of {} which at '
                                       'an SR of {:.3E} leads to just {} '
                                       'point(s). There must be at least '
                                       '2 points in each segment.'
                                       ''.format(namelist[ii],
                                                 ii,
                                                 newdurations[ii],
                                                 SR,
                                                 int_dur))
        else:
            intdurations[ii] = int_dur
            newdurations[ii] = int_dur/SR

    # The actual forging of the waveform
    parts = [ft.partial(fun, *args) for (fun, args) in zip(funlist, argslist)]
    blocks = [list(p(SR, d)) for (p, d) in zip(parts, intdurations)]
    output = [block for sl in blocks for block in sl]

    # now make the markers
    time = np.linspace(0, sum(newdurations), len(output), endpoint=False)
    m1 = np.zeros_like(time)
    m2 = m1.copy()

    # update the 'absolute time' marker list with 'relative time'
    # (segment bound) markers converted to absolute time
    elapsed_times = np.cumsum([0.0] + list(newdurations))

    for pos, spec in enumerate(segmark1):
        if spec[1] is not 0:
            ontime = elapsed_times[pos] + spec[0]  # spec is (delay, duration)
            marker1.append((ontime, spec[1]))
    for pos, spec in enumerate(segmark2):
        if spec[1] is not 0:
            ontime = elapsed_times[pos] + spec[0]  # spec is (delay, duration)
            marker2.append((ontime, spec[1]))
    msettings = [marker1, marker2]
    marks = [m1, m2]
    for marker, setting in zip(marks, msettings):
        for (t, dur) in setting:
            ind = np.abs(time-t).argmin()
            chunk = int(np.round(dur*SR))
            marker[ind:ind+chunk] = 1

    output = np.array(output)  # TODO: Why is this sometimes needed?

    outdict = {'wfm': output, 'm1': m1, 'm2': m2, 'time': time,
               'newdurations': newdurations}

    return outdict


text:
//
//  Copyright (c) SRG SSR. All rights reserved.
//
//  License information is available from the LICENSE file.
//

#import <TargetConditionals.h>

#if TARGET_OS_IOS
@import CoreMotion;
#endif

@import Foundation;
@import UIKit;

NS_ASSUME_NONNULL_BEGIN

/**
 *  @name Supported view modes.
 */
typedef NS_ENUM(NSInteger, SRGMediaPlayerViewMode) {
    SRGMediaPlayerViewModeFlat = 0,                                 // Standard "flat" playback.
    SRGMediaPlayerViewModeMonoscopic,                               // 360 monoscopic playback.
    SRGMediaPlayerViewModeStereoscopic API_UNAVAILABLE(tvos)        // 360 stereoscopic playback (cardboard).
};

/**
 *  The view used by the player to display its media. You can instantiate such views in storyboards or xib files
 *  and bind them to the `view` property of an `SRGMediaPlayerController` instance.
 */
@interface SRGMediaPlayerView : UIView

/**
 *  Retrieve or change the current view mode, if any.
 */
@property (nonatomic) SRGMediaPlayerViewMode viewMode;

/**
 *  `YES` iff the view is ready to be displayed. Key-value observable.
 */
@property (nonatomic, readonly, getter=isReadyForDisplay) BOOL readyForDisplay;

@end

#if TARGET_OS_IOS

@interface SRGMediaPlayerView (CoreMotion)

/**
 *  Set the motion manager to use for device tracking when playing 360° videos. At most one motion manager should
 *  exist per app (see https://developer.apple.com/documentation/coremotion/cmmotionmanager). If your application
 *  already uses its own core motion manager, you can set it using this class method (not that you are then
 *  responsible of starting and stopping tracking, though). Data refresh rate should be at least 1/60 for an optimal
 *  experience.
 *
 *  If no motion manager is provided at the time a media player view requires it, an internal motion manager will
 *  be used. You should set a motion manager before any playback occurs and not change it afterwards, otherwise the
 *  behavior is undefined.
 */
+ (void)setMotionManager:(nullable CMMotionManager *)motionManager;

@end

#endif

NS_ASSUME_NONNULL_END


text:
package ch.ethz.scu.obit.readers;

import java.util.List;

/**
 * Abstract base class for file readers. Actual implementations must
 * extend this class.
 * @author Aaron Ponti
 */
abstract public class AbstractReader {

    /**
     * In case of error, put an explanation in errorMessage.
     */
    protected String errorMessage = "";

    /**
     * Parses the file to extract data and metadata.
     *
     * @return true if parsing was successful, false otherwise.
     * @throws Exception if parsing failed.
     */
    abstract public boolean parse() throws Exception;

    /**
     * Information regarding the file format handled by the Reader.
     * @return descriptive String for the Reader.
     */
    abstract public String info();

    /**
     * Type of the reader
     * @return String type of the reader.
     */
    abstract public String getType();

    /**
     * Returns last errorMessage.
     *
     * After every operation, the state must be updated. In case
     * something goes wrong, the state is set to false and the
     * errorMessage String is set property.
     *
     *  This function returns last error message.
     * @return last error message.
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * Implement an 'implode' function as in PHP.
     * @param values Array of doubles
     * @return Comma-separated list of values as string.
     */
    protected String implode(double [] values) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < values.length; i++) {
            sb.append(values[i]);
            if (i != values.length - 1) {
                sb.append(", ");
            }
        }
        String joined = sb.toString();
        return joined;
    }

    /**
     * Implement an 'implode' function as in PHP.
     * @param values List of Strings.
     * @return Comma-separated list of values as string.
     */
    protected String implode(List<String> values) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < values.size(); i++) {
            sb.append(values.get(i));
            if (i != values.size() - 1) {
                sb.append(", ");
            }
        }
        String joined = sb.toString();
        return joined;
    }
}


text:
package com.citelic.utility.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class WebPage {

	private URL url;
	private ArrayList<String> lines;

	public WebPage(String url) throws MalformedURLException {
		if (!url.startsWith("http://"))
			url = "http://" + url;
		this.url = new URL(url);
	}

	public ArrayList<String> getLines() {
		return lines;
	}

	public void load() throws IOException {
		lines = new ArrayList<String>();
		URLConnection c = url.openConnection();
		c.setReadTimeout(3000);
		BufferedReader stream = new BufferedReader(new InputStreamReader(
				c.getInputStream()));
		String line;
		while ((line = stream.readLine()) != null) {
			lines.add(line);
		}
		stream.close();

	}

	public void setLines(ArrayList<String> lines) {
		this.lines = lines;
	}
}


text:
package com.linecorp.bot.model;

import java.util.Collections;
import java.util.List;

import com.linecorp.bot.model.message.Message;

import lombok.AllArgsConstructor;
import lombok.Value;

/**
 * Send messages to users, groups, and rooms at any time.
 */
@Value
@AllArgsConstructor
public class PushMessage {
    /**
     * ID of the receiver
     */
    private final String to;

    /**
     * List of Message objects.<br>
     * Max: 5
     */
    private final List<Message> messages;

    public PushMessage(String to, Message message) {
        this.to = to;
        this.messages = Collections.singletonList(message);
    }
}


text:
from __future__ import unicode_literals
from __future__ import absolute_import

from .base_task import BaseTask
from .deploy import Deploy
from .http_get import HttpGet
from .http_get import MWProfilerGet
from .process_results import ProcessResponses


text:
<!-- Context: What is the broad context of the work? What is the importance of the general research area? -->
**Context:**
- HTML elements are nested in deep composition hierarchies

<!-- Inquiry: What problem or question does the paper address? How has this problem or question been addressed by others (if at all)? -->
**Inquiry:**
- gab between displayed elements and element structure is often to wide and can only be explored for individual elements

<!-- Approach: What was done that unveiled new knowledge? -->
**Approach:**
- make underlying element composition visible in the UI

<!-- Knowledge: What new facts were uncovered? If the research was not results oriented, what new capabilities are enabled by the work? -->
**Knowledge:**

- structure is interesting but slicing is needed, because total structure information is overwhelming

<!-- Grounding: What argument, feasibility proof, artifacts, or results and evaluation support this work? -->
**Grounding:**

- build prototype

<!-- Importance: Why does this work matter? -->
**Importance:**

- can be applied to all HTML content


text:
'use strict';

import * as q from 'q';

import { Profile } from 'passport-facebook';

import { inject, injectable } from 'inversify';

import { ICustomerService } from './interfaces/customer.service.interface';
import { ISavedOrder } from './interfaces/order.service.interface';

import { IDENTIFIERS } from '../constants/indentifiers';

import { BaseService } from './base.service';
import { ProductService } from './products.service';

import { Server } from '../server';

import { Customer } from '../models/customers.model';

import { Order } from '../models/orders.model';

import { TO_OBJECT_ID } from '../models/schemas/helpers/types.helpers';

@injectable()
export class CustomerService extends BaseService implements ICustomerService {

  constructor (
    @inject(IDENTIFIERS.Server) private server: Server,
    @inject(IDENTIFIERS.ProductService) private product: ProductService
  ) {

    super();

    return this;

  }

  public buildCustomerFromFacebook (
    accessToken: string,
    refreshToken: string,
    profile: Profile,
    cb: Function
  ): void {

    Customer.findOrCreate({

      'facebookId': profile.id

    }, {

      'name': profile.displayName

    })
      .then((
        doc: any
      ): void => {

        console.log(doc);

      }, (err: any) => {

        console.log(err);

      });

    return cb (null, profile);

  }

  public static async getCustomerFromProfile (user: Profile) {

    let deferred: q.Deferred<any> = q.defer<any>(),

      customer = await Customer.findOne({ 'facebookId': user.id }).lean();

    deferred.resolve(customer);

    return deferred.promise;

  }

  public static async getCustomerFromId (id: string) {

    let deferred: q.Deferred<any> = q.defer<any>(),

      customer = await Customer.findOne({ 'customerId': TO_OBJECT_ID(id) }).lean();

    deferred.resolve(customer);

    return deferred.promise;

  }

  public static async saveCustomerById (id: string, upsert: any) {

    let deferred: q.Deferred<boolean> = q.defer<boolean>();

    Customer.findOneAndUpdate({

      'customerId': TO_OBJECT_ID(id)

    }, upsert, {

      'upsert': true

    })
      .exec((err: any, doc: any): void => {

        deferred.resolve(!!(!err && doc));

      });

    return deferred.promise;

  }

  public async getPastOrders (user: Profile) {

    let deferred: q.Deferred<any> = q.defer<any>();

    if (!user) {

      deferred.reject('Not authorized to access this resource!');

    } else {

      let customer: any = await CustomerService.getCustomerFromProfile(user),

        orders: ISavedOrder[] = (<ISavedOrder[]>await Order
          .find({ 'customer.customerId': TO_OBJECT_ID(customer.customerId) })
          .sort({ '_id': -1 })
          .lean()),

        resolvedOrders = await this.product.resolveIdentifiers(orders);

      deferred.resolve({

        'customer': customer,

        'orders': resolvedOrders

      });

    }

    return deferred.promise;

  }

}


text:
#ifndef EXT_HEARTBEAT_H
#define EXT_HEARTBEAT_H

#include <gnutls_extensions.h>

#define HEARTBEAT_REQUEST 1
#define HEARTBEAT_RESPONSE 2

#define MAX_HEARTBEAT_LENGTH DEFAULT_MAX_RECORD_SIZE

#define LOCAL_ALLOWED_TO_SEND (1<<2)
#define LOCAL_NOT_ALLOWED_TO_SEND (1<<3)

#define HEARTBEAT_DEFAULT_POLICY PEER_NOT_ALLOWED_TO_SEND

extern extension_entry_st ext_mod_heartbeat;

int _gnutls_heartbeat_handle(gnutls_session_t session, mbuffer_st * bufel);
int _gnutls_heartbeat_enabled(gnutls_session_t session, int local);
#endif


text:
/*
 * MinIO Cloud Storage, (C) 2016 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

import (
	"context"
	"sort"
	"sync"

	"github.com/minio/minio-go/v6/pkg/s3utils"
	"github.com/minio/minio/cmd/logger"
	"github.com/minio/minio/pkg/policy"
)

// list all errors that can be ignore in a bucket operation.
var bucketOpIgnoredErrs = append(baseIgnoredErrs, errDiskAccessDenied)

// list all errors that can be ignored in a bucket metadata operation.
var bucketMetadataOpIgnoredErrs = append(bucketOpIgnoredErrs, errVolumeNotFound)

/// Bucket operations

// MakeBucket - make a bucket.
func (xl xlObjects) MakeBucketWithLocation(ctx context.Context, bucket, location string) error {
	// Verify if bucket is valid.
	if err := s3utils.CheckValidBucketNameStrict(bucket); err != nil {
		return BucketNameInvalid{Bucket: bucket}
	}

	// Initialize sync waitgroup.
	var wg = &sync.WaitGroup{}

	// Initialize list of errors.
	var dErrs = make([]error, len(xl.getDisks()))

	// Make a volume entry on all underlying storage disks.
	for index, disk := range xl.getDisks() {
		if disk == nil {
			dErrs[index] = errDiskNotFound
			continue
		}
		wg.Add(1)
		// Make a volume inside a go-routine.
		go func(index int, disk StorageAPI) {
			defer wg.Done()
			err := disk.MakeVol(bucket)
			if err != nil {
				if err != errVolumeExists {
					logger.LogIf(ctx, err)
				}
				dErrs[index] = err
			}
		}(index, disk)
	}

	// Wait for all make vol to finish.
	wg.Wait()

	writeQuorum := len(xl.getDisks())/2 + 1
	err := reduceWriteQuorumErrs(ctx, dErrs, bucketOpIgnoredErrs, writeQuorum)
	if err == errXLWriteQuorum {
		// Purge successfully created buckets if we don't have writeQuorum.
		undoMakeBucket(xl.getDisks(), bucket)
	}
	return toObjectErr(err, bucket)
}

func (xl xlObjects) undoDeleteBucket(bucket string) {
	// Initialize sync waitgroup.
	var wg = &sync.WaitGroup{}
	// Undo previous make bucket entry on all underlying storage disks.
	for index, disk := range xl.getDisks() {
		if disk == nil {
			continue
		}
		wg.Add(1)
		// Delete a bucket inside a go-routine.
		go func(index int, disk StorageAPI) {
			defer wg.Done()
			_ = disk.MakeVol(bucket)
		}(index, disk)
	}

	// Wait for all make vol to finish.
	wg.Wait()
}

// undo make bucket operation upon quorum failure.
func undoMakeBucket(storageDisks []StorageAPI, bucket string) {
	// Initialize sync waitgroup.
	var wg = &sync.WaitGroup{}
	// Undo previous make bucket entry on all underlying storage disks.
	for index, disk := range storageDisks {
		if disk == nil {
			continue
		}
		wg.Add(1)
		// Delete a bucket inside a go-routine.
		go func(index int, disk StorageAPI) {
			defer wg.Done()
			_ = disk.DeleteVol(bucket)
		}(index, disk)
	}

	// Wait for all make vol to finish.
	wg.Wait()
}

// getBucketInfo - returns the BucketInfo from one of the load balanced disks.
func (xl xlObjects) getBucketInfo(ctx context.Context, bucketName string) (bucketInfo BucketInfo, err error) {
	var bucketErrs []error
	for _, disk := range xl.getLoadBalancedDisks() {
		if disk == nil {
			bucketErrs = append(bucketErrs, errDiskNotFound)
			continue
		}
		volInfo, serr := disk.StatVol(bucketName)
		if serr == nil {
			return BucketInfo(volInfo), nil
		}
		err = serr
		// For any reason disk went offline continue and pick the next one.
		if IsErrIgnored(err, bucketMetadataOpIgnoredErrs...) {
			bucketErrs = append(bucketErrs, err)
			continue
		}
		// Any error which cannot be ignored, we return quickly.
		return BucketInfo{}, err
	}
	// If all our errors were ignored, then we try to
	// reduce to one error based on read quorum.
	// `nil` is deliberately passed for ignoredErrs
	// because these errors were already ignored.
	readQuorum := len(xl.getDisks()) / 2
	return BucketInfo{}, reduceReadQuorumErrs(ctx, bucketErrs, nil, readQuorum)
}

// GetBucketInfo - returns BucketInfo for a bucket.
func (xl xlObjects) GetBucketInfo(ctx context.Context, bucket string) (bi BucketInfo, e error) {
	bucketLock := xl.nsMutex.NewNSLock(bucket, "")
	if e := bucketLock.GetRLock(globalObjectTimeout); e != nil {
		return bi, e
	}
	defer bucketLock.RUnlock()
	bucketInfo, err := xl.getBucketInfo(ctx, bucket)
	if err != nil {
		return bi, toObjectErr(err, bucket)
	}
	return bucketInfo, nil
}

// listBuckets - returns list of all buckets from a disk picked at random.
func (xl xlObjects) listBuckets(ctx context.Context) (bucketsInfo []BucketInfo, err error) {
	for _, disk := range xl.getLoadBalancedDisks() {
		if disk == nil {
			continue
		}
		var volsInfo []VolInfo
		volsInfo, err = disk.ListVols()
		if err == nil {
			// NOTE: The assumption here is that volumes across all disks in
			// readQuorum have consistent view i.e they all have same number
			// of buckets. This is essentially not verified since healing
			// should take care of this.
			var bucketsInfo []BucketInfo
			for _, volInfo := range volsInfo {
				if isReservedOrInvalidBucket(volInfo.Name, true) {
					continue
				}
				bucketsInfo = append(bucketsInfo, BucketInfo(volInfo))
			}
			// For buckets info empty, loop once again to check
			// if we have, can happen if disks were down.
			if len(bucketsInfo) == 0 {
				continue
			}
			return bucketsInfo, nil
		}
		logger.LogIf(ctx, err)
		// Ignore any disks not found.
		if IsErrIgnored(err, bucketMetadataOpIgnoredErrs...) {
			continue
		}
		break
	}
	return nil, err
}

// ListBuckets - lists all the buckets, sorted by its name.
func (xl xlObjects) ListBuckets(ctx context.Context) ([]BucketInfo, error) {
	bucketInfos, err := xl.listBuckets(ctx)
	if err != nil {
		return nil, toObjectErr(err)
	}
	// Sort by bucket name before returning.
	sort.Sort(byBucketName(bucketInfos))
	return bucketInfos, nil
}

// Dangling buckets should be handled appropriately, in this following situation
// we actually have quorum error to be `nil` but we have some disks where
// the bucket delete returned `errVolumeNotEmpty` but this is not correct
// can only happen if there are dangling objects in a bucket. Under such
// a situation we simply attempt a full delete of the bucket including
// the dangling objects. All of this happens under a lock and there
// is no way a user can create buckets and sneak in objects into namespace,
// so it is safer to do.
func deleteDanglingBucket(ctx context.Context, storageDisks []StorageAPI, dErrs []error, bucket string) {
	for index, err := range dErrs {
		if err == errVolumeNotEmpty {
			// Attempt to delete bucket again.
			if derr := storageDisks[index].DeleteVol(bucket); derr == errVolumeNotEmpty {
				_ = cleanupDir(ctx, storageDisks[index], bucket, "")

				_ = storageDisks[index].DeleteVol(bucket)

				// Cleanup all the previously incomplete multiparts.
				_ = cleanupDir(ctx, storageDisks[index], minioMetaMultipartBucket, bucket)
			}
		}
	}
}

// DeleteBucket - deletes a bucket.
func (xl xlObjects) DeleteBucket(ctx context.Context, bucket string) error {
	bucketLock := xl.nsMutex.NewNSLock(bucket, "")
	if err := bucketLock.GetLock(globalObjectTimeout); err != nil {
		return err
	}
	defer bucketLock.Unlock()

	// Collect if all disks report volume not found.
	var wg = &sync.WaitGroup{}
	var dErrs = make([]error, len(xl.getDisks()))

	// Remove a volume entry on all underlying storage disks.
	storageDisks := xl.getDisks()
	for index, disk := range storageDisks {
		if disk == nil {
			dErrs[index] = errDiskNotFound
			continue
		}
		wg.Add(1)
		// Delete volume inside a go-routine.
		go func(index int, disk StorageAPI) {
			defer wg.Done()
			// Attempt to delete bucket.
			err := disk.DeleteVol(bucket)
			if err != nil {
				dErrs[index] = err
				return
			}

			// Cleanup all the previously incomplete multiparts.
			err = cleanupDir(ctx, disk, minioMetaMultipartBucket, bucket)
			if err != nil && err != errVolumeNotFound {
				dErrs[index] = err
			}
		}(index, disk)
	}

	// Wait for all the delete vols to finish.
	wg.Wait()

	writeQuorum := len(xl.getDisks())/2 + 1
	err := reduceWriteQuorumErrs(ctx, dErrs, bucketOpIgnoredErrs, writeQuorum)
	if err == errXLWriteQuorum {
		xl.undoDeleteBucket(bucket)
	}
	if err != nil {
		return toObjectErr(err, bucket)
	}

	// If we reduce quorum to nil, means we have deleted buckets properly
	// on some servers in quorum, we should look for volumeNotEmpty errors
	// and delete those buckets as well.
	deleteDanglingBucket(ctx, storageDisks, dErrs, bucket)

	return nil
}

// SetBucketPolicy sets policy on bucket
func (xl xlObjects) SetBucketPolicy(ctx context.Context, bucket string, policy *policy.Policy) error {
	return savePolicyConfig(ctx, xl, bucket, policy)
}

// GetBucketPolicy will get policy on bucket
func (xl xlObjects) GetBucketPolicy(ctx context.Context, bucket string) (*policy.Policy, error) {
	return getPolicyConfig(xl, bucket)
}

// DeleteBucketPolicy deletes all policies on bucket
func (xl xlObjects) DeleteBucketPolicy(ctx context.Context, bucket string) error {
	return removePolicyConfig(ctx, xl, bucket)
}

// IsNotificationSupported returns whether bucket notification is applicable for this layer.
func (xl xlObjects) IsNotificationSupported() bool {
	return true
}

// IsListenBucketSupported returns whether listen bucket notification is applicable for this layer.
func (xl xlObjects) IsListenBucketSupported() bool {
	return true
}

// IsEncryptionSupported returns whether server side encryption is implemented for this layer.
func (xl xlObjects) IsEncryptionSupported() bool {
	return true
}

// IsCompressionSupported returns whether compression is applicable for this layer.
func (xl xlObjects) IsCompressionSupported() bool {
	return true
}


text:
@interface NSDictionary (EncodeURLParams)

-(NSData *)encodedURLParams;

@end