text:
package org.jkiss.dbeaver.ui.dialogs.connection;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.DBPTransactionIsolation;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.connection.DBPConnectionBootstrap;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.connection.DBPConnectionType;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.rdb.DBSCatalog;
import org.jkiss.dbeaver.model.struct.rdb.DBSSchema;
import org.jkiss.dbeaver.registry.DataSourceDescriptor;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.utils.CommonUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Initialization connection page (common for all connection types)
 */
class ConnectionPageInitialization extends ConnectionWizardPage implements IDataSourceConnectionTester {
    static final String PAGE_NAME = ConnectionPageInitialization.class.getSimpleName();

    private static final Log log = Log.getLog(ConnectionPageInitialization.class);

    private DataSourceDescriptor dataSourceDescriptor;

    private Button autocommit;
    private Combo isolationLevel;
    private Combo defaultCatalog;
    private Combo defaultSchema;
    private Spinner keepAliveInterval;

    private Spinner autoCloseIdleConnectionsText;

    private Font boldFont;

    private boolean activated = false;
    private final List<DBPTransactionIsolation> supportedLevels = new ArrayList<>();
    private List<String> bootstrapQueries;
    private boolean ignoreBootstrapErrors;

    private boolean txnOptionsLoaded = false;

    private ConnectionPageInitialization() {
        super(PAGE_NAME); //$NON-NLS-1$
        setTitle(CoreMessages.dialog_connection_wizard_connection_init);
        setDescription(CoreMessages.dialog_connection_wizard_connection_init_description);

        bootstrapQueries = new ArrayList<>();
    }

    ConnectionPageInitialization(DataSourceDescriptor dataSourceDescriptor) {
        this();
        this.dataSourceDescriptor = dataSourceDescriptor;

        bootstrapQueries = new ArrayList<>(dataSourceDescriptor.getConnectionConfiguration().getBootstrap().getInitQueries());
        ignoreBootstrapErrors = dataSourceDescriptor.getConnectionConfiguration().getBootstrap().isIgnoreErrors();
    }

    @Override
    public void dispose() {
        UIUtils.dispose(boldFont);
        super.dispose();
    }

    @Override
    public void activatePage() {
        if (dataSourceDescriptor != null) {
            if (!activated) {
                // Get settings from data source descriptor
                final DBPConnectionConfiguration conConfig = dataSourceDescriptor.getConnectionConfiguration();
                autocommit.setSelection(dataSourceDescriptor.isDefaultAutoCommit());
                isolationLevel.add("");

                DataSourceDescriptor originalDataSource = getWizard().getOriginalDataSource();
                if (originalDataSource != null && originalDataSource.isConnected()) {
                    DBPDataSource dataSource = originalDataSource.getDataSource();
                    loadDatabaseSettings(dataSource);
                }
                defaultCatalog.setText(CommonUtils.notEmpty(conConfig.getBootstrap().getDefaultCatalogName()));
                defaultSchema.setText(CommonUtils.notEmpty(conConfig.getBootstrap().getDefaultSchemaName()));
                keepAliveInterval.setSelection(conConfig.getKeepAliveInterval());
                autoCloseIdleConnectionsText.setSelection(conConfig.getCloseIdleInterval());
                activated = true;
            }
        } else {
            // Default settings
            isolationLevel.setEnabled(false);
            defaultCatalog.setText("");
            defaultSchema.setText("");
        }
    }

    private void loadDatabaseSettings(DBPDataSource dataSource) {
        try {
            getWizard().getRunnableContext().run(true, true, monitor -> {
                loadDatabaseSettings(monitor, dataSource);
            });
        } catch (InvocationTargetException e) {
            DBWorkbench.getPlatformUI().showError("Database info reading", "Error reading information from database", e.getTargetException());
        } catch (InterruptedException e) {
            //
        }
    }

    private void loadDatabaseSettings(DBRProgressMonitor monitor, DBPDataSource dataSource)  {
        DBPDataSourceContainer dataSourceContainer = dataSource.getContainer();
        Collection<DBPTransactionIsolation> txnLevels = CommonUtils.safeCollection(dataSource.getInfo().getSupportedTransactionsIsolation());
        Integer levelCode = dataSourceContainer.getDefaultTransactionsIsolation();

        UIUtils.syncExec(() -> {
            autocommit.setSelection(dataSourceContainer.isDefaultAutoCommit());
            //isolationLevel.setEnabled(!autocommit.getSelection());
            supportedLevels.clear();

            DBPTransactionIsolation defaultLevel = null;
                {
                if (levelCode != null && !CommonUtils.isEmpty(txnLevels)) {
                    for (DBPTransactionIsolation level : txnLevels) {
                        if (level.getCode() == levelCode) {
                            defaultLevel = level;
                            break;
                        }
                    }

                }
            }

            isolationLevel.removeAll();
            supportedLevels.clear();
            for (DBPTransactionIsolation level : txnLevels) {
                if (!level.isEnabled()) {
                    continue;
                }

                isolationLevel.add(level.getTitle());
                supportedLevels.add(level);

                if (level.equals(defaultLevel)) {
                    isolationLevel.select(isolationLevel.getItemCount() - 1);
                }
            }
        });

        if (dataSource instanceof DBSObjectContainer) {
            DBCExecutionContext executionContext = DBUtils.getDefaultContext(dataSource, true);
            DBCExecutionContextDefaults contextDefaults = executionContext.getContextDefaults();
            DBSObjectContainer catalogContainer = DBUtils.getChangeableObjectContainer(contextDefaults, (DBSObjectContainer) dataSource, DBSCatalog.class);
            if (catalogContainer != null) {
                loadSelectableObject(monitor, catalogContainer, defaultCatalog, contextDefaults, true);
            }
            DBSObjectContainer schemaContainer = DBUtils.getChangeableObjectContainer(contextDefaults, (DBSObjectContainer) dataSource, DBSSchema.class);
            loadSelectableObject(monitor, schemaContainer, defaultSchema, contextDefaults, false);
        }

        txnOptionsLoaded = true;
    }

    private void loadSelectableObject(DBRProgressMonitor monitor, DBSObjectContainer objectContainer, Combo objectCombo, DBCExecutionContextDefaults contextDefaults, boolean isCatalogs) {
        if (objectContainer != null) {
            try {
                final List<String> objectNames = new ArrayList<>();
                Collection<? extends DBSObject> children = objectContainer.getChildren(monitor);
                if (children != null) {
                    for (DBSObject child : children) {
                        if (child instanceof DBSObjectContainer) {
                            objectNames.add(child.getName());
                        }
                    }
                }
                if (!objectNames.isEmpty()) {
                    UIUtils.syncExec(() -> {
                        if (!objectCombo.isDisposed()) {
                            String oldText = objectCombo.getText();
                            objectCombo.removeAll();
                            for (String name : objectNames) {
                                objectCombo.add(name);
                            }
                            if (!CommonUtils.isEmpty(oldText)) {
                                objectCombo.setText(oldText);
                            }
                            if (contextDefaults != null) {
                                DBSObject defaultObject = isCatalogs ? contextDefaults.getDefaultCatalog() : contextDefaults.getDefaultSchema();
                                if (defaultObject != null) {
                                    objectCombo.setText(defaultObject.getName());
                                }
                            }
                        }
                    });
                }
            } catch (DBException e) {
                log.warn("Can't read schema list", e);
            }
        }
    }

    @Override
    public void deactivatePage() {
    }

    @Override
    public void createControl(Composite parent) {
        boldFont = UIUtils.makeBoldFont(parent.getFont());
        Composite group = UIUtils.createPlaceholder(parent, 1, 5);

        {
            Group txnGroup = UIUtils.createControlGroup(group, CoreMessages.dialog_connection_wizard_final_label_connection, 2, GridData.VERTICAL_ALIGN_BEGINNING, 0);
            autocommit = UIUtils.createLabelCheckbox(
                txnGroup,
                CoreMessages.dialog_connection_wizard_final_checkbox_auto_commit,
                "Sets auto-commit mode for all connections",
                dataSourceDescriptor != null && dataSourceDescriptor.isDefaultAutoCommit());
            autocommit.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
            autocommit.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    isolationLevel.setEnabled(!autocommit.getSelection());
                }
            });

            isolationLevel = UIUtils.createLabelCombo(txnGroup, CoreMessages.dialog_connection_wizard_final_label_isolation_level,
                CoreMessages.dialog_connection_wizard_final_label_isolation_level_tooltip, SWT.DROP_DOWN | SWT.READ_ONLY);
            defaultCatalog = UIUtils.createLabelCombo(txnGroup, CoreMessages.dialog_connection_wizard_final_label_default_database,
                    CoreMessages.dialog_connection_wizard_final_label_default_database_tooltip, SWT.DROP_DOWN);
            ((GridData)defaultCatalog.getLayoutData()).widthHint = UIUtils.getFontHeight(defaultCatalog) * 20;
            defaultSchema = UIUtils.createLabelCombo(txnGroup, CoreMessages.dialog_connection_wizard_final_label_default_schema,
                CoreMessages.dialog_connection_wizard_final_label_default_schema_tooltip, SWT.DROP_DOWN);
            ((GridData)defaultSchema.getLayoutData()).widthHint = UIUtils.getFontHeight(defaultSchema) * 20;
            keepAliveInterval = UIUtils.createLabelSpinner(txnGroup, CoreMessages.dialog_connection_wizard_final_label_keepalive,
                CoreMessages.dialog_connection_wizard_final_label_keepalive_tooltip, 0, 0, Short.MAX_VALUE);

            autoCloseIdleConnectionsText = UIUtils.createLabelSpinner(txnGroup, CoreMessages.dialog_connection_wizard_final_label_close_idle_connections,
                CoreMessages.dialog_connection_wizard_final_label_close_idle_connections_tooltip, 0, 0, Short.MAX_VALUE);

            {
                String bootstrapTooltip = CoreMessages.dialog_connection_wizard_final_label_bootstrap_tooltip;
                UIUtils.createControlLabel(txnGroup, CoreMessages.dialog_connection_wizard_final_label_bootstrap_query).setToolTipText(bootstrapTooltip);
                final Button queriesConfigButton = UIUtils.createPushButton(txnGroup, CoreMessages.dialog_connection_wizard_configure, DBeaverIcons.getImage(UIIcon.SQL_SCRIPT));
                queriesConfigButton.setToolTipText(bootstrapTooltip);
                if (dataSourceDescriptor != null && !CommonUtils.isEmpty(dataSourceDescriptor.getConnectionConfiguration().getBootstrap().getInitQueries())) {
                    queriesConfigButton.setFont(boldFont);
                }
                queriesConfigButton.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        EditBootstrapQueriesDialog dialog = new EditBootstrapQueriesDialog(
                            getShell(),
                            dataSourceDescriptor,
                            bootstrapQueries,
                            ignoreBootstrapErrors);
                        if (dialog.open() == IDialogConstants.OK_ID) {
                            bootstrapQueries = dialog.getQueries();
                            ignoreBootstrapErrors = dialog.isIgnoreErrors();
                        }
                    }
                });
            }
        }

        CLabel infoLabel = UIUtils.createInfoLabel(group, CoreMessages.dialog_connection_wizard_connection_init_hint);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_END);
        gd.grabExcessHorizontalSpace = true;
        infoLabel.setLayoutData(gd);
        infoLabel.setToolTipText(CoreMessages.dialog_connection_wizard_connection_init_hint_tip);

        setControl(group);

        UIUtils.setHelp(group, IHelpContextIds.CTX_CON_WIZARD_FINAL);
    }

    @Override
    public boolean isPageComplete() {
        return true;
    }

    @Override
    public void saveSettings(DBPDataSourceContainer dataSource) {
        if (dataSourceDescriptor != null && !activated) {
            // No changes anyway
            return;
        }
        dataSource.setDefaultAutoCommit(autocommit.getSelection());
        if (txnOptionsLoaded) {
            if (CommonUtils.isEmpty(isolationLevel.getText())) {
                dataSource.setDefaultTransactionsIsolation(null);
            } else {
                int levelIndex = isolationLevel.getSelectionIndex();
                if (levelIndex >= 0) {
                    dataSource.setDefaultTransactionsIsolation(supportedLevels.get(levelIndex));
                }
            }
        }
        final DBPConnectionConfiguration confConfig = dataSource.getConnectionConfiguration();
        DBPConnectionBootstrap bootstrap = confConfig.getBootstrap();
        bootstrap.setDefaultCatalogName(defaultCatalog.getText());
        bootstrap.setDefaultSchemaName(defaultSchema.getText());

        bootstrap.setIgnoreErrors(ignoreBootstrapErrors);
        bootstrap.setInitQueries(bootstrapQueries);

        confConfig.setKeepAliveInterval(keepAliveInterval.getSelection());
        confConfig.setCloseIdleInterval(autoCloseIdleConnectionsText.getSelection());
    }

    @Override
    public void setWizard(IWizard newWizard) {
        super.setWizard(newWizard);
        if (newWizard instanceof ConnectionWizard && !((ConnectionWizard) newWizard).isNew()) {
            // Listen for connection type change
            ((ConnectionWizard) newWizard).addPropertyChangeListener(event -> {
                if (ConnectionWizard.PROP_CONNECTION_TYPE.equals(event.getProperty())) {
                    DBPConnectionType type = (DBPConnectionType) event.getNewValue();
                    if (autocommit != null) {
                        autocommit.setSelection(type.isAutocommit());
                    }
                }
            });
        }
    }

    @Override
    public void testConnection(DBCSession session) {
        // We load settings to fill txn isolation levels and schema names (#6794)
        loadDatabaseSettings(session.getProgressMonitor(), session.getDataSource());
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wangzhe.test.ui.fxml;

/**
 *
 * @author ocq
 */
import java.util.HashMap;
import java.util.Map;

public class User {

    private static final Map<String, User> USERS = new HashMap<String, User>();

    public static User of(String id) {
        User user = USERS.get(id);
        if (user == null) {
            user = new User(id);
            USERS.put(id, user);
        }
        return user;
    }

    private User(String id) {
        this.id = id;
    }
    private String id;

    public String getId() {
        return id;
    }
    private String email = "";
    private String phone = "";
    private boolean subscribed;
    private String address = "";

    /**
     */
    public String getEmail() {
        return email;
    }

    /**
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     */
    public String getPhone() {
        return phone;
    }

    /**
     */
    public void setPhone(String phone) {
        this.phone = phone;
    }

    /**
     */
    public boolean isSubscribed() {
        return subscribed;
    }

    /**
     */
    public void setSubscribed(boolean subscribed) {
        this.subscribed = subscribed;
    }

    /**
     */
    public String getAddress() {
        return address;
    }

    /**
     */
    public void setAddress(String address) {
        this.address = address;
    }
}


text:
package ch.ethz.inf.vs.californium.dtls;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import ch.ethz.inf.vs.californium.coap.Message;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertDescription;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertLevel;
import ch.ethz.inf.vs.californium.dtls.CipherSuite.KeyExchangeAlgorithm;
import ch.ethz.inf.vs.californium.layers.DTLSLayer;
import ch.ethz.inf.vs.californium.util.ByteArrayUtils;
import ch.ethz.inf.vs.californium.util.DatagramReader;
import ch.ethz.inf.vs.californium.util.DatagramWriter;

public class Record {

	// Logging ////////////////////////////////////////////////////////

	protected static final Logger LOG = Logger.getLogger(Record.class.getName());

	// CoAP-specific constants/////////////////////////////////////////

	private static final int CONTENT_TYPE_BITS = 8;

	private static final int VERSION_BITS = 8; // for major and minor each

	private static final int EPOCH_BITS = 16;

	private static final int SEQUENCE_NUMBER_BITS = 48;

	private static final int LENGHT_BITS = 16;

	// Members ////////////////////////////////////////////////////////

	/** The higher-level protocol used to process the enclosed fragment */
	private ContentType type = null;

	/**
	 * The version of the protocol being employed. DTLS version 1.2 uses { 254,
	 * 253 }
	 */
	private ProtocolVersion version = new ProtocolVersion();

	/** A counter value that is incremented on every cipher state change */
	private int epoch = -1;

	/** The sequence number for this record */
	private long sequenceNumber;

	/** The length (in bytes) of the following {@link DTLSMessage}. */
	private int length = 0;

	/**
	 * The application data. This data is transparent and treated as an
	 * independent block to be dealt with by the higher-level protocol specified
	 * by the type field.
	 */
	private DTLSMessage fragment = null;

	/** The raw byte representation of the fragment. */
	private byte[] fragmentBytes = null;

	/** The DTLS session. */
	private DTLSSession session;

	// Constructors ///////////////////////////////////////////////////

	/**
	 * Called when reconstructing the record from a byte array. The fragment
	 * will remain in its binary representation up to the {@link DTLSLayer}.
	 *
	 * @param type
	 * @param version
	 * @param epoch
	 * @param sequenceNumber
	 * @param length
	 * @param fragmentBytes
	 */
	public Record(ContentType type, ProtocolVersion version, int epoch, long sequenceNumber, int length, byte[] fragmentBytes) {
		this.type = type;
		this.version = version;
		this.epoch = epoch;
		this.sequenceNumber = sequenceNumber;
		this.length = length;
		this.fragmentBytes = fragmentBytes;
	}

	/**
	 * Called when creating a record after receiving a {@link Message}.
	 *
	 * @param type
	 *            the type
	 * @param epoch
	 *            the epoch
	 * @param sequenceNumber
	 *            the sequence number
	 * @param fragment
	 *            the fragment
	 * @param session
	 *            the session
	 */

	public Record(ContentType type, int epoch, int sequenceNumber, DTLSMessage fragment, DTLSSession session) {
		this.type = type;
		this.epoch = epoch;
		this.sequenceNumber = sequenceNumber;
		this.session = session;
		setFragment(fragment);
	}

	// Serialization //////////////////////////////////////////////////

	/**
	 * Encodes the DTLS Record into its raw binary structure as defined in the
	 * DTLS v.1.2 specification.
	 *
	 * @return the encoded byte array
	 */
	public byte[] toByteArray() {
		DatagramWriter writer = new DatagramWriter();

		writer.write(type.getCode(), CONTENT_TYPE_BITS);

		writer.write(version.getMajor(), VERSION_BITS);
		writer.write(version.getMinor(), VERSION_BITS);

		writer.write(epoch, EPOCH_BITS);
		writer.writeLong(sequenceNumber, SEQUENCE_NUMBER_BITS);

		length = fragmentBytes.length;
		writer.write(length, LENGHT_BITS);

		writer.writeBytes(fragmentBytes);

		return writer.toByteArray();
	}

	/**
	 * Decodes the DTLS Record from its raw binary representation. Potentially
	 * multiple Records are stored in 1 datagram.
	 *
	 * @param byteArray
	 *            the byte array
	 * @return the list of decoded records
	 */
	public static List<Record> fromByteArray(byte[] byteArray) {
		List<Record> records = new ArrayList<Record>();

		DatagramReader reader = new DatagramReader(byteArray);

		while (reader.bytesAvailable()) {

			ContentType contentType = ContentType.getTypeByValue(reader.read(CONTENT_TYPE_BITS));

			int major = reader.read(VERSION_BITS);
			int minor = reader.read(VERSION_BITS);
			ProtocolVersion version = new ProtocolVersion(major, minor);

			int epoch = reader.read(EPOCH_BITS);
			long sequenceNumber = reader.readLong(SEQUENCE_NUMBER_BITS);

			int length = reader.read(LENGHT_BITS);

			// delay decryption/interpretation of fragment
			byte[] fragmentBytes = reader.readBytes(length);

			records.add(new Record(contentType, version, epoch, sequenceNumber, length, fragmentBytes));
		}

		return records;
	}

	// Cryptography /////////////////////////////////////////////////////////

	/**
	 * Encrypts the fragment, if a ciphersuite is available that supports
	 * encryption.
	 *
	 * @param byteArray
	 * @return
	 */
	private byte[] encryptFragment(byte[] byteArray) {
		if (session == null) {
			return byteArray;
		}

		byte[] encryptedFragment = byteArray;

		CipherSuite cipherSuite = session.getWriteState().getCipherSuite();

		switch (cipherSuite.getCipherType()) {
		case NULL:
			// do nothing
			break;

		case AEAD:
			encryptedFragment = encryptAEAD(byteArray);
			break;

		case BLOCK:
			// TODO implement block cipher
			break;

		case STREAM:
			// Not used in DTLS, see http://tools.ietf.org/html/rfc6347#section-4.1.2.2
			break;

		default:
			break;
		}

		return encryptedFragment;
	}

	/**
	 * Decrypts the byte array according to the current connection state. So,
	 * potentially no decryption takes place. Returns null if the
	 * message can't be authenticated.
	 *
	 * @param byteArray
	 *            the potentially encrypted fragment.
	 * @return the decrypted fragment.
	 * @throws HandshakeException
	 *             if the decryption fails.
	 */
	private byte[] decryptFragment(byte[] byteArray) throws HandshakeException {
		if (session == null) {
			return byteArray;
		}

		byte[] fragment = byteArray;

		CipherSuite cipherSuite = session.getReadState().getCipherSuite();

		switch (cipherSuite.getCipherType()) {
		case NULL:
			// do nothing
			break;

		case AEAD:
			fragment = decryptAEAD(byteArray);
			break;

		case BLOCK:
			// TODO implement block cipher
			break;

		case STREAM:
			// Not used in DTLS, see http://tools.ietf.org/html/rfc6347#section-4.1.2.2
			break;

		default:
			break;
		}

		return fragment;
	}

	// AEAD Cryptography //////////////////////////////////////////////

	private byte[] encryptAEAD(byte[] byteArray) {
		/*
		 * See http://tools.ietf.org/html/rfc5246#section-6.2.3.3 for
		 * explanation of additional data or
		 * http://tools.ietf.org/html/rfc5116#section-2.1
		 */
		byte[] iv = session.getWriteState().getIv().getIV();
		byte[] nonce = generateNonce(iv);
		byte[] key = session.getWriteState().getEncryptionKey().getEncoded();
		byte[] additionalData = generateAdditionalData(getLength());

		byte[] encryptedFragment = CCMBlockCipher.encrypt(key, nonce, additionalData, byteArray, 8);

		/*
		 * Prepend the explicit nonce as specified in
		 * http://tools.ietf.org/html/rfc5246#section-6.2.3.3 and
		 * http://tools.ietf.org/html/draft-mcgrew-tls-aes-ccm-04#section-3
		 */
		byte[] explicitNonce = generateExplicitNonce();
		encryptedFragment = ByteArrayUtils.concatenate(explicitNonce, encryptedFragment);

		return encryptedFragment;
	}

	/**
	 * Decrypts the given byte array using a AEAD cipher.
	 *
	 * @param byteArray
	 *            the encrypted message.
	 * @return the decrypted message.
	 * @throws HandshakeException
	 *             if the decryption fails.
	 */
	private byte[] decryptAEAD(byte[] byteArray) throws HandshakeException {
		/*
		 * See http://tools.ietf.org/html/rfc5246#section-6.2.3.3 for
		 * explanation of additional data or
		 * http://tools.ietf.org/html/rfc5116#section-2.2
		 */
		byte[] iv = session.getReadState().getIv().getIV();
		byte[] nonce = generateNonce(iv);
		byte[] key = session.getReadState().getEncryptionKey().getEncoded();
		/*
		 * The decrypted message is always 16 bytes shorter than the cipher (8
		 * for the authentication tag and 8 for the explicit nonce).
		 */
		byte[] additionalData = generateAdditionalData(getLength() - 16);

		DatagramReader reader = new DatagramReader(byteArray);
		byte[] explicitNonce = generateExplicitNonce();
		// The explicit nonce is 8 bytes long
		byte[] explicitNonceReceived = reader.readBytes(8);
		if (!Arrays.equals(explicitNonce, explicitNonceReceived)) {
			LOG.info("The received explicit nonce did not match the expected explicit nonce: \nReceived: " + ByteArrayUtils.toHexString(explicitNonceReceived) + "\nExpected: " + ByteArrayUtils.toHexString(explicitNonce));
		}

		byte[] decrypted = CCMBlockCipher.decrypt(key, nonce, additionalData, reader.readBytesLeft(), 8);

		return decrypted;
	}

	// Cryptography Helper Methods ////////////////////////////////////

	/**
	 * http://tools.ietf.org/html/draft-mcgrew-tls-aes-ccm-ecc-03#section-2:
	 *
	 *

	 * struct {
	 *   case client:
	 *     uint32 client_write_IV;  // low order 32-bits
	 *   case server:
	 *     uint32 server_write_IV;  // low order 32-bits
	 *  uint64 seq_num;
	 * } CCMNonce.
	 *

	 *
	 * @param iv
	 *            the write IV (either client or server).
	 * @return the 12 bytes nonce.
	 */
	private byte[] generateNonce(byte[] iv) {
		DatagramWriter writer = new DatagramWriter();

		writer.writeBytes(iv);
		writer.writeBytes(generateExplicitNonce());

		return writer.toByteArray();
	}

	/**
	 * Generates the explicit part of the nonce used by the AEAD Cipher type. In
	 * this case it is the 2 bytes epoch concatenated with the 6 bytes sequence
	 * number.
	 *
	 * @return the explicit nonce.
	 */
	private byte[] generateExplicitNonce() {
		DatagramWriter writer = new DatagramWriter();

		writer.write(epoch, EPOCH_BITS);
		writer.writeLong(sequenceNumber, SEQUENCE_NUMBER_BITS);

		return writer.toByteArray();
	}

	/**
	 * See RFC
	 * 5246:
	 *
	 *

	 * additional_data = seq_num + TLSCompressed.type +
	 * TLSCompressed.version + TLSCompressed.length;
	 *

	 *
	 * where "+" denotes concatenation.
	 *
	 * @return the additional authentication data.
	 */
	private byte[] generateAdditionalData(int length) {
		DatagramWriter writer = new DatagramWriter();

		writer.write(epoch, EPOCH_BITS);
		writer.writeLong(sequenceNumber, SEQUENCE_NUMBER_BITS);

		writer.write(type.getCode(), CONTENT_TYPE_BITS);

		writer.write(version.getMajor(), VERSION_BITS);
		writer.write(version.getMinor(), VERSION_BITS);

		writer.write(length, LENGHT_BITS);

		return writer.toByteArray();
	}

	// Getters and Setters ////////////////////////////////////////////

	public ContentType getType() {
		return type;
	}

	public void setType(ContentType type) {
		this.type = type;
	}

	public ProtocolVersion getVersion() {
		return version;
	}

	public void setVersion(ProtocolVersion version) {
		this.version = version;
	}

	public int getEpoch() {
		return epoch;
	}

	public void setEpoch(int epoch) {
		this.epoch = epoch;
	}

	public long getSequenceNumber() {
		return sequenceNumber;
	}

	public void setSequenceNumber(int sequenceNumber) {
		this.sequenceNumber = sequenceNumber;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public DTLSSession getSession() {
		return session;
	}

	public void setSession(DTLSSession session) {
		this.session = session;
	}

	public byte[] getFragmentBytes() {
		return fragmentBytes;
	}

	/**
	 * So far, the fragment is in its raw binary format. Decrypt (if necessary)
	 * under current read state and serialize it.
	 *
	 * @return the fragment
	 * @throws HandshakeException
	 *             if the decryption fails.
	 */
	public DTLSMessage getFragment() throws HandshakeException {
		if (fragment == null) {
			// decide, which type of fragment need decryption
			switch (type) {
			case ALERT:
				byte[] decryptedMessage = decryptFragment(fragmentBytes);
				if (decryptedMessage != null) {
					fragment = AlertMessage.fromByteArray(decryptedMessage);
				}
				break;

			case APPLICATION_DATA:
				decryptedMessage = decryptFragment(fragmentBytes);
				if (decryptedMessage != null) {
					fragment = ApplicationMessage.fromByteArray(decryptedMessage);
				}
				break;

			case CHANGE_CIPHER_SPEC:
				// http://tools.ietf.org/html/rfc5246#section-7.1: "is
				// encrypted and compressed under the current (not the pending)
				// connection state"
				decryptedMessage = decryptFragment(fragmentBytes);
				if (decryptedMessage != null) {
					fragment =  ChangeCipherSpecMessage.fromByteArray(decryptedMessage);
				}
				break;

			case HANDSHAKE:
				decryptedMessage = decryptFragment(fragmentBytes);

				KeyExchangeAlgorithm keyExchangeAlgorithm = KeyExchangeAlgorithm.NULL;
				boolean receiveRawPublicKey = false;
				if (session != null) {
					keyExchangeAlgorithm = session.getKeyExchange();
					receiveRawPublicKey = session.receiveRawPublicKey();
				}
				if (decryptedMessage != null) {
					fragment = HandshakeMessage.fromByteArray(decryptedMessage, keyExchangeAlgorithm, receiveRawPublicKey);
				}
				break;

			default:
				LOG.severe("Unknown content type: " + type);
				break;
			}
		}

		/*
		 * If at this point the fragment is still null, the decryption must have
		 * failed (e.g. not possible to authenticate). Send alert.
		 *
		 * http://tools.ietf.org/html/rfc5246#section-6.2.3.3: "If the
		 * decryption fails, a fatal bad_record_mac alert MUST be generated."
		 */
		if (fragment == null) {
			AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_RECORD_MAC);
			throw new HandshakeException("The decryption failed.", alert);
		}
		return fragment;
	}

	/**
	 * Sets the DTLS fragment. At the same time, it creates the corresponding
	 * raw binary representation and encrypts it if necessary (depending on
	 * current connection state).
	 *
	 * @param fragment
	 *            the DTLS fragment.
	 */
	public void setFragment(DTLSMessage fragment) {

		if (fragmentBytes == null) {
			// serialize fragment and if necessary encrypt byte array

			byte[] byteArray = fragment.toByteArray();
			// the current length of the unprotected message
			// this value is needed to generate the additional data when using AEAD
			length = byteArray.length;

			switch (type) {
			case ALERT:
			case APPLICATION_DATA:
			case HANDSHAKE:
			case CHANGE_CIPHER_SPEC:
				byteArray = encryptFragment(byteArray);
				break;

			default:
				LOG.severe("Unknown content type: " + type.toString());
				break;
			}
			this.fragmentBytes = byteArray;

		}
		this.fragment = fragment;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("==[ DTLS Message  ]============================================\n");
		sb.append("Content Type: " + type.toString() + "\n");
		sb.append("Version: " + version.getMajor() + ", " + version.getMinor() + "\n");
		sb.append("Epoch: " + epoch + "\n");
		sb.append("Sequence Number: " + sequenceNumber + "\n");
		sb.append("Length: " + length + "\n");
		sb.append(fragment.toString());
		sb.append("===============================================================");

		return sb.toString();
	}

}


text:
% ExaParam_Musle file for initialization of muscle models
%
% This function loads muscle parameters and calculates the initial
% conditions for the internal degree of freedom l_CE.
%
% If you use this model for scientific purposes, please cite our article:
% D.F.B. Haeufle, M. Günther, A. Bayer, S. Schmitt (2014) Hill-type muscle
% model with serial daParam_Musing and eccentric force-velocity relation Journal
% of Biomechanics http://dx.doi.org/10.1016/j.jbiomech.2014.02.009

% Copyright (c) 2014 belongs to D. Haeufle, M. Guenther, A. Bayer, and S.
% Schmitt
% All rights reserved.
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
%  1 Redistributions of source code must retain the above copyright notice,
%    this list of conditions and the following disclaimer.
%  2 Redistributions in binary form must reproduce the above copyright
%    notice, this list of conditions and the following disclaimer in the
%    documentation and/or other materials provided with the distribution.
%  3 Neither the name of the owner nor the names of its contributors may be
%    used to endorse or promote products derived from this software without
%    specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
% IS" AND ANY EXPRESS OR IParam_MusLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
% THE IParam_MusLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEParam_MusLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

%% Load muscle parameters
%=================================================
% define muscle specific parameters

% contractile element (CE)
%===========================
Param_Mus.CE.F_max = 1420;                 % F_max in [N] %source: Kistemaker2006,
Param_Mus.CE.l_CEopt = 0.092;              % optimal length of CE in [m] %source: Kistemaker2006,

% serial elastic element (SEE)
% ============================
Param_Mus.SEE.l_SEE0        = 0.182;       % rest length of SEE in [m]

% load standard parameter set
Param_Mus = Library_mtu_simulink_mtu_standard_parameters(Param_Mus);

Param_Mus = Library_mtu_simulink_mtu_standard_parameters(Param_Mus);

%% load parameters for the activation dynamics
Param_Mus.ActDyn = Library_mtu_simulink_actdyn_standard_parameters;

%% Specify initial conditions
%==============================
% Before the muscle model can be initialized, the length of the MTC at t=0
% and the initial muscle activity have to be defined:

Param_Mus.l_MTC_init = 0.092+0.182;  % [m] initial MTC length
Param_Mus.ActDyn.u_init  = 0;          % [] initial muscle activity 0...1

% initial condition for internal degree of freedom (l_CE)
%=========================================================
% the initial condition Param_Mus.l_CE_init is found under the assumtion that
% all velocities are zero at the beginning of the simulation and that the
% force-equilibrium is F_SEE - F_CE - F_PEE = 0. The root is found with
% fzero

fhandle         = @(l_CE)init_muscle_force_equilib_with_Hatze_ActDyn(l_CE, Param_Mus.l_MTC_init, Param_Mus.ActDyn.u_init, Param_Mus, Param_Mus.ActDyn);
                         %init_muscle_force_equilib_with_Hatze_ActDyn(l_CE, l_MTC, u, MusParam, ActParam)
Param_Mus.CE.l_CE_init = fzero(fhandle, [0 Param_Mus.l_MTC_init]);
clear fhandle

% Several muscles can be stored in an array of structs,
% e.g., Param_Mus(2) = muscle_param_mus02;
% Repeat Steps 1-2 for each muscle


text:
cask 'aptanastudio' do
  version '3.6.1'
  sha256 '1eed9a94ce9b9bf03743f0bfdc5efd752b3470842170ba571ee25d2810c3c8f0'

  # github.com/aptana/studio3 was verified as official when first introduced to the cask
  url "https://github.com/aptana/studio3/releases/download/v#{version}/Aptana_Studio_3_Setup_#{version}.dmg"
  appcast "https://github.com/aptana/studio#{version.major}/releases.atom",
          checkpoint: 'cc90ca0284dca1d1f8b17ed4b3afd300154eda6c1648e7d9cd1a797f984fd32d'
  name 'Aptana Studio'
  homepage 'http://www.aptana.com/'
  license :gpl

  app "Aptana Studio #{version.major}/AptanaStudio#{version.major}.app"
end


text:
- concept is equal to the video route:
  - add a preprocessor that converts an md string to an image stream
- means we can extend the image route in the same way video does (`class MarkdownRoute extends MarkdownPreprocess(Image) {}`)

## Example usage:

```html
<img src="http://localhost:3000/md/preview-image/%23%20headline%0A%0Awasd?size=500" alt="headline wasd">
```

## Implementation

- route url `/md/{profile}/{md}`
- input extraction resolves `md` request param
- reader returns `{markdown: <MardownString>}` object
- use [markdown-it](https://github.com/markdown-it/markdown-it) to generate html from markdown
- use [node-webshot](https://github.com/brenden/node-webshot) to generate image stream from html
(__Note:__ node-webshot is currently not compatible with node@6 until [node-webshot/#150](https://github.com/brenden/node-webshot/pull/150) is merged. Use `npm i "github:brenden/node-webshot#pull/150/head"`)

### Route mixin

```js
function MarkdownPreprocess(SuperClass) {
  return class MarkdownPreprocessor extends SuperClass {
    extractInput(operation) {
      return Promise.resolve(decodeURIComponent(operation.request.params.md));
    }

    extractReader(input) {
      return Promise.resolve((operation) => ({markdown: input}));
    }

    preprocess(operation) {
      return markdownPreprocessor(operation);
    }
  };
}
```

### Markdown preprocessor function

```js
function markdownPreprocessor() {
  return (readerResult) =>
    Promise.resolve(webshot(`<html><body>${md.render(readerResult.markdown)}</body></html>`, {siteType: 'html'}));
}
```

### Route

```js
class MarkdownRoute extends MarkdownPreprocess(Image) {
  constructor(conf, method = 'GET', path = '/md/{profile}/{md}', description = 'Profile markdown conversion') {
    super(conf, method, path, description);
  }
}
```

### starting the server

```js
Config.fromEnv().then(config => new Server(config, new AddonLoader(__dirname, {}).load())
    .withProfiles([require('../src/profiles/examples')])
    .withRoutes([new MarkdownRoute(config)])
    .start()
    .then(server => logger.info(`server running at ${server.hapi.info.uri}`)));
```


text:
package dtl

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"net/http"
)

// VirtualNetworksClient is the the DevTest Labs Client.
type VirtualNetworksClient struct {
	BaseClient
}

// NewVirtualNetworksClient creates an instance of the VirtualNetworksClient client.
func NewVirtualNetworksClient(subscriptionID string) VirtualNetworksClient {
	return NewVirtualNetworksClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewVirtualNetworksClientWithBaseURI creates an instance of the VirtualNetworksClient client.
func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworksClient {
	return VirtualNetworksClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate create or replace an existing virtual network. This operation can take a while to complete.
// Parameters:
// resourceGroupName - the name of the resource group.
// labName - the name of the lab.
// name - the name of the virtual network.
// virtualNetwork - a virtual network.
func (client VirtualNetworksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetwork) (result VirtualNetworksCreateOrUpdateFuture, err error) {
	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, virtualNetwork)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	result, err = client.CreateOrUpdateSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "CreateOrUpdate", result.Response(), "Failure sending request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client VirtualNetworksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetwork) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"labName":           autorest.Encode("path", labName),
		"name":              autorest.Encode("path", name),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-05-15"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters),
		autorest.WithJSON(virtualNetwork),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworksCreateOrUpdateFuture, err error) {
	var resp *http.Response
	resp, err = autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
	if err != nil {
		return
	}
	future.Future, err = azure.NewFutureFromResponse(resp)
	return
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete delete virtual network. This operation can take a while to complete.
// Parameters:
// resourceGroupName - the name of the resource group.
// labName - the name of the lab.
// name - the name of the virtual network.
func (client VirtualNetworksClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualNetworksDeleteFuture, err error) {
	req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Delete", nil, "Failure preparing request")
		return
	}

	result, err = client.DeleteSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Delete", result.Response(), "Failure sending request")
		return
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client VirtualNetworksClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"labName":           autorest.Encode("path", labName),
		"name":              autorest.Encode("path", name),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-05-15"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworksClient) DeleteSender(req *http.Request) (future VirtualNetworksDeleteFuture, err error) {
	var resp *http.Response
	resp, err = autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
	if err != nil {
		return
	}
	future.Future, err = azure.NewFutureFromResponse(resp)
	return
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get get virtual network.
// Parameters:
// resourceGroupName - the name of the resource group.
// labName - the name of the lab.
// name - the name of the virtual network.
// expand - specify the $expand query. Example: 'properties($expand=externalSubnets)'
func (client VirtualNetworksClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result VirtualNetwork, err error) {
	req, err := client.GetPreparer(ctx, resourceGroupName, labName, name, expand)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client VirtualNetworksClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"labName":           autorest.Encode("path", labName),
		"name":              autorest.Encode("path", name),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-05-15"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(expand) > 0 {
		queryParameters["$expand"] = autorest.Encode("query", expand)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result VirtualNetwork, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List list virtual networks in a given lab.
// Parameters:
// resourceGroupName - the name of the resource group.
// labName - the name of the lab.
// expand - specify the $expand query. Example: 'properties($expand=externalSubnets)'
// filter - the filter to apply to the operation.
// top - the maximum number of resources to return from the operation.
// orderby - the ordering expression for the results, using OData notation.
func (client VirtualNetworksClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ResponseWithContinuationVirtualNetworkPage, err error) {
	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListSender(req)
	if err != nil {
		result.rwcvn.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", resp, "Failure sending request")
		return
	}

	result.rwcvn, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", resp, "Failure responding to request")
	}

	return
}

// ListPreparer prepares the List request.
func (client VirtualNetworksClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"labName":           autorest.Encode("path", labName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-05-15"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(expand) > 0 {
		queryParameters["$expand"] = autorest.Encode("query", expand)
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = autorest.Encode("query", filter)
	}
	if top != nil {
		queryParameters["$top"] = autorest.Encode("query", *top)
	}
	if len(orderby) > 0 {
		queryParameters["$orderby"] = autorest.Encode("query", orderby)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result ResponseWithContinuationVirtualNetwork, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listNextResults retrieves the next set of results, if any.
func (client VirtualNetworksClient) listNextResults(lastResults ResponseWithContinuationVirtualNetwork) (result ResponseWithContinuationVirtualNetwork, err error) {
	req, err := lastResults.responseWithContinuationVirtualNetworkPreparer()
	if err != nil {
		return result, autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "listNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client VirtualNetworksClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ResponseWithContinuationVirtualNetworkIterator, err error) {
	result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby)
	return
}

// Update modify properties of virtual networks.
// Parameters:
// resourceGroupName - the name of the resource group.
// labName - the name of the lab.
// name - the name of the virtual network.
// virtualNetwork - a virtual network.
func (client VirtualNetworksClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetworkFragment) (result VirtualNetwork, err error) {
	req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, virtualNetwork)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", resp, "Failure responding to request")
	}

	return
}

// UpdatePreparer prepares the Update request.
func (client VirtualNetworksClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetworkFragment) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"labName":           autorest.Encode("path", labName),
		"name":              autorest.Encode("path", name),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2016-05-15"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPatch(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters),
		autorest.WithJSON(virtualNetwork),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client VirtualNetworksClient) UpdateSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client VirtualNetworksClient) UpdateResponder(resp *http.Response) (result VirtualNetwork, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using SlimDX.Direct2D;
using SlimDX.DXGI;

namespace DirectCanvas.Imaging.WIC
{
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("2cd90691-12e2-11dc-9fed-001143a055f9")]
    interface ID2D1Resource
    {
        [PreserveSig]
        int GetFactory(out IntPtr factory);
    }

    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("2cd90694-12e2-11dc-9fed-001143a055f9")]
    interface ID2D1RenderTarget : ID2D1Resource
    {
        [PreserveSig]
        new int GetFactory(out IntPtr factory);
        [PreserveSig]
        int CreateBitmap( /*stub*/);
        [PreserveSig]
        int CreateBitmapFromWicBitmap(IWICBitmapSource source, ref BitmapProperties pProps, out IntPtr bitmap);
    }

    static class D2DRenderTargetEx
    {
        public static SlimDX.Direct2D.Bitmap CreateBitmapFromWicBitmap(IWICBitmapSource source, BitmapProperties bitmapProperties, RenderTarget renderTarget)
        {
            var pBitmap = IntPtr.Zero;
            SlimDX.Direct2D.Bitmap bmp = null;

            var pRenderTarget = Marshal.GetObjectForIUnknown(renderTarget.ComPointer) as ID2D1RenderTarget;

            int hr = pRenderTarget.CreateBitmapFromWicBitmap(source, ref bitmapProperties, out pBitmap);

            if (hr != 0)
                goto cleanup;

            bmp = SlimDX.Direct2D.Bitmap.FromPointer(pBitmap);

cleanup:
            Marshal.Release(pBitmap);
            Marshal.ReleaseComObject(pRenderTarget);

            return bmp;
        }
    }
}


text:
<?php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class GameType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder
                ->add('name','text', ['attr' => ['class' => 'form-control']])
                ->add('logo','text', ['attr' => ['class' => 'form-control']])
                ->add('save', 'submit', ['attr' => ['class' => 'btn btn-primary']]);
    }

    public function getName()
    {
        return 'game';
    }
}


text:
package org.kiji.mapreduce.kvstore.lib;

import java.io.IOException;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.hadoop.io.AvroKeyValue;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;

import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.ApiStability;
import org.kiji.mapreduce.kvstore.KeyValueStore;
import org.kiji.mapreduce.kvstore.KeyValueStoreReader;
import org.kiji.mapreduce.kvstore.framework.KeyValueStoreConfiguration;

/**
 * An interface for providing read access to Avro container files of (key, value)
 * records.
 *
 *
This KeyValueStore provides lookup access to an Avro container file by reading
 * the entire file into memory. The Avro file is assumed to contain records with (at
 * least) two fields, named "key" and "value." This store will decompose the top-level
 * record into its two fields, and index the "value" field by the key.

 *
 *
XML Configuration

 *
 *
A kvstores XML file may contain the following properties when specifying the
 * behavior of this class:

 *

 *
<tt>dcache</tt> - True if files should be accessed by jobs through the DistributedCache.
 *
<tt>paths</tt> - A comma-separated list of HDFS paths to files backing this store.
 *
<tt>avro.reader.schema</tt> - The reader schema to apply to records in the
 *       input file(s).

 *

 *
 *
Default values

 *
 *

 *
By default, use of the DistributedCache is enabled.

 *
You must specify the paths to read. It is an error to leave this unconfigured.

 *
Files will be read using a new <tt>Configuration</tt> object if you do not specify
 *       your own.

 *
If you do not specify an Avro reader schema, the writer schema from each
 *       file will be used.  (In this case, it is expected that these files have the same writer
 *       schema.) The schema of each datum in your Avro files must be a record that
 *       contains at least two fields, called <tt>key</tt> and <tt>value</tt>.
 *       The schema of these two fields is up to you.
 *       Any additional fields in a top-level record will be ignored. It is an error for your
 *       schema to not include these fields; see the {@link AvroRecordKeyValueStore} for a more
 *       free-form record-based Avro KeyValueStore.

 *

 *
 * @param <K> The type of the key field.
 * @param <V> The type of the value field.
 */
@ApiAudience.Public
@ApiStability.Evolving
public final class AvroKVRecordKeyValueStore<K, V> implements Configurable, KeyValueStore<K, V> {
  /** The configuration variable for the name of the field to use as the lookup key. */
  private static final String KEY_FIELD = "key";

  /** A wrapped store for looking up an Avro record by its 'key' field. */
  private final AvroRecordKeyValueStore<K, GenericRecord> mStore;

  /** true if the user has called open(); cannot call initFromConf() after that. */
  private boolean mOpened;

  /**
   * A Builder-pattern class that configures and creates new AvroKVRecordKeyValueStore
   * instances. You should use this to specify the input to this KeyValueStore.
   * Call the build() method to return a new, configured AvroKVRecordKeyValueStore instance.
   */
  @ApiAudience.Public
  @ApiStability.Evolving
  public static final class Builder {
    private AvroRecordKeyValueStore.Builder mAvroRecordStoreBuilder;

    /**
     * Private, default constructor. Call the builder() method of this KeyValueStore
     * to get a new builder instance.
     */
    private Builder() {
      mAvroRecordStoreBuilder = AvroRecordKeyValueStore.builder();
      mAvroRecordStoreBuilder.withKeyFieldName(AvroKeyValue.KEY_FIELD);
    }

    /**
     * Sets the schema to read the records with.
     * This may be null; the schema used when writing the input files will be used directly.
     *
     * @param schema The reader schema.
     * @return This builder instance.
     */
    public Builder withReaderSchema(Schema schema) {
      mAvroRecordStoreBuilder.withReaderSchema(schema);
      return this;
    }

    /**
     * Sets the Hadoop configuration instance to use.
     *
     * @param conf The configuration.
     * @return This builder instance.
     */
    public Builder withConfiguration(Configuration conf) {
      mAvroRecordStoreBuilder.withConfiguration(conf);
      return this;
    }

    /**
     * Adds a path to the list of files to load.
     *
     * @param path The input file/directory path.
     * @return This builder instance.
     */
    public Builder withInputPath(Path path) {
      mAvroRecordStoreBuilder.withInputPath(path);
      return this;
    }

    /**
     * Replaces the current list of files to load with the set of files
     * specified as an argument.
     *
     * @param paths The input file/directory paths.
     * @return This builder instance.
     */
    public Builder withInputPaths(List<Path> paths) {
      mAvroRecordStoreBuilder.withInputPaths(paths);
      return this;
    }

    /**
     * Sets a flag indicating the use of the DistributedCache to distribute
     * input files.
     *
     * @param enabled true if the DistributedCache should be used, false otherwise.
     * @return This builder instance.
     */
    public Builder withDistributedCache(boolean enabled) {
      mAvroRecordStoreBuilder.withDistributedCache(enabled);
      return this;
    }

    /**
     * Build a new AvroKVRecordKeyValueStore instance.
     *
     * @param <K> the key type used to look up each record.
     * @param <V> the value type returned by each record.
     * @return the initialized KeyValueStore.
     */
    public <K, V> AvroKVRecordKeyValueStore<K, V> build() {
      return new AvroKVRecordKeyValueStore<K, V>(this);
    }
  }

  /**
   * Creates a new AvroKVRecordKeyValueStore.Builder instance that can be used
   * to configure and create a new KeyValueStore.
   *
   * @return a new Builder instance.
   */
  public static Builder builder() {
    return new Builder();
  }

  /**
   * Constructs an AvroKVRecordKeyValueStore from a builder.
   *
   * @param builder the builder instance to configure from.
   */
  private AvroKVRecordKeyValueStore(Builder builder) {
    mStore = builder.mAvroRecordStoreBuilder.build();
  }

  /**
   * Reflection-only constructor. Used only for reflection. You should create and configure
   * AvroKVRecordKeyValueStore instances by using a builder;
   * call AvroKVRecordKeyValueStore.builder() to get a new builder instance.
   */
  public AvroKVRecordKeyValueStore() {
    this(builder());
  }

  /** {@inheritDoc} */
  @Override
  public void setConf(Configuration conf) {
    if (mOpened) {
      // Don't allow mutation after we start using this store for reads.
      throw new IllegalStateException(
          "Cannot set the configuration after a reader has been opened");
    }

    mStore.setConf(conf);
  }

  /** {@inheritDoc} */
  @Override
  public Configuration getConf() {
    return mStore.getConf(); // This creates a new Configuration for return.
  }

  /** {@inheritDoc} */
  @Override
  public void storeToConf(KeyValueStoreConfiguration conf) throws IOException {
    mStore.storeToConf(conf);
  }

  /** {@inheritDoc} */
  @Override
  public void initFromConf(KeyValueStoreConfiguration conf) throws IOException {
    if (mOpened) {
      throw new IllegalStateException("Cannot reinitialize; already opened a reader.");
    }

    // By convention, we always use "key" as the field to access in an AvroKVRecord-based store.
    // When initializing the underlying AvroRecordKeyValueStore from our kvstores.xml,
    // ensure that this field is set as such.
    conf.set(AvroRecordKeyValueStore.CONF_KEY_FIELD_KEY, KEY_FIELD);
    mStore.initFromConf(conf);
  }

  /** {@inheritDoc} */
  @Override
  public KeyValueStoreReader<K, V> open() throws IOException {
    mOpened = true;
    return new Reader<K, V>(mStore);
  }

  /**
   * Reads an entire Avro container file of (key, value) records into memory, indexed
   * by "key."
   *
   *
Lookups for a key K will return the "value" field of the first record
   * in the file where the key field has value K.

   */
  @ApiAudience.Private
  static final class Reader<K, V> implements KeyValueStoreReader<K, V> {
    /** A wrapped Avro store reader for looking up a record by its 'key' field. */
    private final KeyValueStoreReader<K, GenericRecord> mReader;

    /**
     * Constructs a key value reader over an Avro file.
     *
     * @param store An Avro file store that uses the 'key' field as the key, and
     *     the entire record as the value.
     * @throws IOException If there is an error.
     */
    public Reader(AvroRecordKeyValueStore<K, GenericRecord> store) throws IOException {
      mReader = store.open();
    }

    /** {@inheritDoc} */
    @Override
    public boolean isOpen() {
      return mReader.isOpen();
    }

    /** {@inheritDoc} */
    @Override
    @SuppressWarnings("unchecked")
    public V get(K key) throws IOException {
      GenericRecord record = mReader.get(key);
      if (null == record) {
        // No match;
        return null;
      }

      return (V) record.get(AvroKeyValue.VALUE_FIELD);
    }

    /** {@inheritDoc} */
    @Override
    public boolean containsKey(K key) throws IOException {
      return mReader.containsKey(key);
    }

    /** {@inheritDoc} */
    @Override
    public void close() throws IOException {
      mReader.close();
    }
  }
}


text:
"""Support to check for available updates."""
import asyncio
from datetime import timedelta
import logging

import async_timeout
from awesomeversion import AwesomeVersion
from distro import linux_distribution  # pylint: disable=import-error
import voluptuous as vol

from homeassistant.const import __version__ as current_version
from homeassistant.helpers import discovery, update_coordinator
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

ATTR_RELEASE_NOTES = "release_notes"
ATTR_NEWEST_VERSION = "newest_version"

CONF_REPORTING = "reporting"
CONF_COMPONENT_REPORTING = "include_used_components"

DOMAIN = "updater"

UPDATER_URL = "https://updater.home-assistant.io/"

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: {
            vol.Optional(CONF_REPORTING, default=True): cv.boolean,
            vol.Optional(CONF_COMPONENT_REPORTING, default=False): cv.boolean,
        }
    },
    extra=vol.ALLOW_EXTRA,
)

RESPONSE_SCHEMA = vol.Schema(
    {vol.Required("version"): cv.string, vol.Required("release-notes"): cv.url}
)

class Updater:
    """Updater class for data exchange."""

    def __init__(self, update_available: bool, newest_version: str, release_notes: str):
        """Initialize attributes."""
        self.update_available = update_available
        self.release_notes = release_notes
        self.newest_version = newest_version

async def async_setup(hass, config):
    """Set up the updater component."""
    if "dev" in current_version:
        # This component only makes sense in release versions
        _LOGGER.info("Running on 'dev', only analytics will be submitted")

    conf = config.get(DOMAIN, {})
    if conf.get(CONF_REPORTING):
        huuid = await hass.helpers.instance_id.async_get()
    else:
        huuid = None

    include_components = conf.get(CONF_COMPONENT_REPORTING)

    async def check_new_version() -> Updater:
        """Check if a new version is available and report if one is."""
        newest, release_notes = await get_newest_version(
            hass, huuid, include_components
        )

        _LOGGER.debug("Fetched version %s: %s", newest, release_notes)

        # Skip on dev
        if "dev" in current_version:
            return Updater(False, "", "")

        # Load data from Supervisor
        if hass.components.hassio.is_hassio():
            core_info = hass.components.hassio.get_core_info()
            newest = core_info["version_latest"]

        # Validate version
        update_available = False
        if AwesomeVersion(newest) > AwesomeVersion(current_version):
            _LOGGER.debug(
                "The latest available version of Home Assistant is %s", newest
            )
            update_available = True
        elif AwesomeVersion(newest) == AwesomeVersion(current_version):
            _LOGGER.debug(
                "You are on the latest version (%s) of Home Assistant", newest
            )
        elif AwesomeVersion(newest) < AwesomeVersion(current_version):
            _LOGGER.debug(
                "Local version (%s) is newer than the latest available version (%s)",
                current_version,
                newest,
            )

        _LOGGER.debug("Update available: %s", update_available)

        return Updater(update_available, newest, release_notes)

    coordinator = hass.data[DOMAIN] = update_coordinator.DataUpdateCoordinator[Updater](
        hass,
        _LOGGER,
        name="Home Assistant update",
        update_method=check_new_version,
        update_interval=timedelta(days=1),
    )

    # This can take up to 15s which can delay startup
    asyncio.create_task(coordinator.async_refresh())

    hass.async_create_task(
        discovery.async_load_platform(hass, "binary_sensor", DOMAIN, {}, config)
    )

    return True

async def get_newest_version(hass, huuid, include_components):
    """Get the newest Home Assistant version."""
    if huuid:
        info_object = await hass.helpers.system_info.async_get_system_info()

        if include_components:
            info_object["components"] = list(hass.config.components)

        linux_dist = await hass.async_add_executor_job(linux_distribution, False)
        info_object["distribution"] = linux_dist[0]
        info_object["os_version"] = linux_dist[1]

        info_object["huuid"] = huuid
    else:
        info_object = {}

    session = async_get_clientsession(hass)

    with async_timeout.timeout(30):
        req = await session.post(UPDATER_URL, json=info_object)

    _LOGGER.info(
        (
            "Submitted analytics to Home Assistant servers. "
            "Information submitted includes %s"
        ),
        info_object,
    )

    try:
        res = await req.json()
    except ValueError as err:
        raise update_coordinator.UpdateFailed(
            "Received invalid JSON from Home Assistant Update"
        ) from err

    try:
        res = RESPONSE_SCHEMA(res)
        return res["version"], res["release-notes"]
    except vol.Invalid as err:
        raise update_coordinator.UpdateFailed(
            f"Got unexpected response: {err}"
        ) from err


text:
package com.xiaozan.web.xiaozan.service;

import com.xiaozan.web.xiaozan.pojo.User;

public interface IUserService {
	User getUserById(String id);
}


text:
try:
    from unittest.mock import Mock
except ImportError:
    from mock import Mock

from django_db_sanitizer.fetchers import BaseFetcher

from test_app.models import Profile
from test_app.tests.utils import FetcherTestCase

class BaseFetcherTest(FetcherTestCase):
    fixtures = ("profiles",)

    model_class = Profile
    fetcher_class = BaseFetcher

    def test_str(self):
        self.assertEqual(str(self.fetcher), "BaseFetcher")

    def test_get_queryset_manager(self):
        manager = self.fetcher.get_queryset_manager()
        self.assertEqual(manager, Profile.objects)

    def test_get_filtered_queryset(self):
        queryset = self.fetcher.get_filtered_queryset()
        expected_queryset = Profile.objects.all()
        self.assertEqual(list(queryset), list(expected_queryset))

    def test_get_filtered_queryset_with_filtering(self):

        class MyFilteredFetcher(BaseFetcher):
            filters_for_fetching = {"importance_rank__lte": 5}
            excludes_for_fetching = {"pk": 2}

        self.fetcher = MyFilteredFetcher(self.model_class)
        expected_queryset = Profile.objects.filter(pk__in=[1, 3, 4, 5])

        queryset = self.fetcher.get_filtered_queryset()
        self.assertEqual(list(queryset), list(expected_queryset))

    def test_get_filtered_queryset_values(self):
        queryset = self.fetcher.get_filtered_queryset_values(
            ["card_number"], include_pk_field=True)
        # Actual field name is used instead of Django's "pk" shortcut
        # although it can be requested by adding it to the field_names param
        expected_queryset = Profile.objects.values("id", "card_number")
        self.assertEqual(list(queryset), list(expected_queryset))

    def test_get_filtered_queryset_values_with_pk_keyword_retrieval(self):
        queryset = self.fetcher.get_filtered_queryset_values(
            ["pk", "card_number"], include_pk_field=True)
        expected_queryset = Profile.objects.values("pk", "id", "card_number")
        self.assertEqual(list(queryset), list(expected_queryset))

    def test_get_filtered_queryset_values_no_pk_field(self):
        queryset = self.fetcher.get_filtered_queryset_values(
            ["card_number"], include_pk_field=False)
        expected_queryset = Profile.objects.values("card_number")
        self.assertEqual(list(queryset), list(expected_queryset))

    def test_get_model_class(self):
        model_class = self.fetcher.get_model_class()
        self.assertEqual(model_class, Profile)

    def test_get_model_pk_field_name(self):
        pk_field_name = self.fetcher.get_model_pk_field_name()
        self.assertEqual(pk_field_name, "id")


text: cat today.sql| sqlite3 ~/Library/Safari/History.db


text:
package com.dianping.cat.consumer.build;

import com.dianping.cat.analysis.MessageAnalyzer;
import com.dianping.cat.config.content.ContentFetcher;
import com.dianping.cat.config.content.DefaultContentFetcher;
import com.dianping.cat.config.server.ServerConfigManager;
import com.dianping.cat.config.server.ServerFilterConfigManager;
import com.dianping.cat.consumer.CatConsumerModule;
import com.dianping.cat.consumer.config.AllReportConfigManager;
import com.dianping.cat.consumer.config.ProductLineConfigManager;
import com.dianping.cat.consumer.cross.CrossAnalyzer;
import com.dianping.cat.consumer.cross.CrossDelegate;
import com.dianping.cat.consumer.cross.IpConvertManager;
import com.dianping.cat.consumer.dal.BusinessReportDao;
import com.dianping.cat.consumer.dependency.DatabaseParser;
import com.dianping.cat.consumer.dependency.DependencyAnalyzer;
import com.dianping.cat.consumer.dependency.DependencyDelegate;
import com.dianping.cat.consumer.dump.DumpAnalyzer;
import com.dianping.cat.consumer.dump.LocalMessageBucketManager;
import com.dianping.cat.consumer.heartbeat.HeartbeatAnalyzer;
import com.dianping.cat.consumer.heartbeat.HeartbeatDelegate;
import com.dianping.cat.consumer.matrix.MatrixAnalyzer;
import com.dianping.cat.consumer.matrix.MatrixDelegate;
import com.dianping.cat.consumer.metric.MetricAnalyzer;
import com.dianping.cat.consumer.metric.MetricConfigManager;
import com.dianping.cat.consumer.state.StateAnalyzer;
import com.dianping.cat.consumer.state.StateDelegate;
import com.dianping.cat.consumer.storage.StorageAnalyzer;
import com.dianping.cat.consumer.storage.StorageDelegate;
import com.dianping.cat.consumer.storage.StorageReportUpdater;
import com.dianping.cat.consumer.top.TopAnalyzer;
import com.dianping.cat.consumer.top.TopDelegate;
import com.dianping.cat.core.config.ConfigDao;
import com.dianping.cat.core.dal.HourlyReportContentDao;
import com.dianping.cat.core.dal.HourlyReportDao;
import com.dianping.cat.core.dal.ProjectDao;
import com.dianping.cat.hadoop.hdfs.HdfsUploader;
import com.dianping.cat.message.PathBuilder;
import com.dianping.cat.message.storage.MessageBucketManager;
import com.dianping.cat.report.DefaultReportManager;
import com.dianping.cat.report.DomainValidator;
import com.dianping.cat.report.ReportBucketManager;
import com.dianping.cat.report.ReportDelegate;
import com.dianping.cat.report.ReportManager;
import com.dianping.cat.service.ProjectService;
import com.dianping.cat.statistic.ServerStatisticManager;
import com.dianping.cat.task.TaskManager;
import org.unidal.initialization.Module;
import org.unidal.lookup.configuration.AbstractResourceConfigurator;
import org.unidal.lookup.configuration.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ComponentsConfigurator extends AbstractResourceConfigurator {
   public static void main(String[] args) {
      generatePlexusComponentsXmlFile(new ComponentsConfigurator());
   }

   @Override
   public List<Component> defineComponents() {
      List<Component> all = new ArrayList<Component>();

      all.addAll(defineHeartbeatComponents());
      all.addAll(defineTopComponents());
      all.addAll(defineDumpComponents());
      all.addAll(defineStateComponents());
      all.addAll(defineCrossComponents());
      all.addAll(defineMatrixComponents());
      all.addAll(defineDependencyComponents());
      all.addAll(defineMetricComponents());
      all.addAll(defineStorageComponents());

      all.add(C(AllReportConfigManager.class).req(ConfigDao.class, ContentFetcher.class));
      all.add(C(Module.class, CatConsumerModule.ID, CatConsumerModule.class));
      all.addAll(new CatDatabaseConfigurator().defineComponents());

      return all;
   }

   private Collection<Component> defineCrossComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = CrossAnalyzer.ID;

      all.add(C(IpConvertManager.class));
      all.add(C(MessageAnalyzer.class, ID, CrossAnalyzer.class).is(PER_LOOKUP)
            //
            .req(ReportManager.class, ID).req(ServerConfigManager.class, IpConvertManager.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, CrossDelegate.class).req(TaskManager.class, ServerFilterConfigManager.class));

      return all;
   }

   private Collection<Component> defineDependencyComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = DependencyAnalyzer.ID;

      all.add(C(DatabaseParser.class));
      all.add(C(MessageAnalyzer.class, ID, DependencyAnalyzer.class).is(PER_LOOKUP).req(ReportManager.class, ID)
            .req(ServerConfigManager.class, ServerFilterConfigManager.class, DatabaseParser.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, DependencyDelegate.class).req(TaskManager.class));

      return all;
   }

   private Collection<Component> defineDumpComponents() {
      final List<Component> all = new ArrayList<Component>();

      all.add(A(DumpAnalyzer.class));

      all.add(C(MessageBucketManager.class, LocalMessageBucketManager.ID, LocalMessageBucketManager.class) //
            .req(ServerConfigManager.class, PathBuilder.class, ServerStatisticManager.class)//
            .req(HdfsUploader.class));

      return all;
   }

   private Collection<Component> defineHeartbeatComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = HeartbeatAnalyzer.ID;

      all.add(C(MessageAnalyzer.class, ID, HeartbeatAnalyzer.class).is(PER_LOOKUP)
            //
            .req(ReportManager.class, ID).req(ServerConfigManager.class, ServerFilterConfigManager.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, HeartbeatDelegate.class).req(TaskManager.class,
            ServerFilterConfigManager.class));

      return all;
   }

   private Collection<Component> defineMatrixComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = MatrixAnalyzer.ID;

      all.add(C(MessageAnalyzer.class, ID, MatrixAnalyzer.class).is(PER_LOOKUP) //
            .req(ReportManager.class, ID).req(ServerConfigManager.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, MatrixDelegate.class).req(TaskManager.class, ServerFilterConfigManager.class));

      return all;
   }

   private Collection<Component> defineMetricComponents() {
      final List<Component> all = new ArrayList<Component>();

      all.add(C(ContentFetcher.class, DefaultContentFetcher.class));
      all.add(C(ProductLineConfigManager.class).req(ConfigDao.class, ContentFetcher.class));
      all.add(C(MetricConfigManager.class).req(ConfigDao.class, ContentFetcher.class, ProductLineConfigManager.class));
      all.add(C(MessageAnalyzer.class, MetricAnalyzer.ID, MetricAnalyzer.class).is(PER_LOOKUP)
            //
            .req(ReportBucketManager.class, BusinessReportDao.class, MetricConfigManager.class)//
            .req(ProductLineConfigManager.class, TaskManager.class, ServerConfigManager.class));

      return all;
   }

   private Collection<Component> defineStateComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = StateAnalyzer.ID;

      all.add(C(ProjectService.class).req(ProjectDao.class, ServerConfigManager.class));
      all.add(C(MessageAnalyzer.class, ID, StateAnalyzer.class).is(PER_LOOKUP).req(ReportManager.class, ID)
            .req(ServerStatisticManager.class, ServerConfigManager.class, ServerFilterConfigManager.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, StateDelegate.class) //
            .req(TaskManager.class, ReportBucketManager.class));

      return all;
   }

   private Collection<Component> defineStorageComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = StorageAnalyzer.ID;
      all.add(C(com.dianping.cat.consumer.storage.DatabaseParser.class));
      all.add(C(StorageReportUpdater.class));
      all.add(C(MessageAnalyzer.class, ID, StorageAnalyzer.class).is(PER_LOOKUP).req(ReportManager.class, ID)
            .req(ReportDelegate.class, ID).req(ServerConfigManager.class)
            .req(com.dianping.cat.consumer.storage.DatabaseParser.class).req(StorageReportUpdater.class));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, StorageDelegate.class).req(TaskManager.class,
            ServerFilterConfigManager.class, StorageReportUpdater.class));

      // database
      // all.add(C(JdbcDataSourceDescriptorManager.class) //
      // .config(E("datasourceFile").value("/data/appdatas/cat/datasources.xml")));

      return all;
   }

   private Collection<Component> defineTopComponents() {
      final List<Component> all = new ArrayList<Component>();
      final String ID = TopAnalyzer.ID;

      all.add(C(MessageAnalyzer.class, ID, TopAnalyzer.class).is(PER_LOOKUP).req(ReportManager.class, ID)
            .req(ServerConfigManager.class, ServerFilterConfigManager.class)
            .config(E("errorType").value("Error,RuntimeException,Exception")));
      all.add(C(ReportManager.class, ID, DefaultReportManager.class).is(PER_LOOKUP)
            //
            .req(ReportDelegate.class, ID)
            //
            .req(ReportBucketManager.class, HourlyReportDao.class, HourlyReportContentDao.class, DomainValidator.class) //
            .config(E("name").value(ID)));
      all.add(C(ReportDelegate.class, ID, TopDelegate.class));

      return all;
   }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ReniUI
{
    public abstract class MainView : View, IApplication
    {
        readonly ApplicationContext Context;

        protected MainView(string name, string configFileName = null)
            : base(configFileName)
        {
            Context = new ApplicationContext(Frame);
            Title = name;
            Frame.FormClosing += (a, b) => Application.Exit();
        }

        void IApplication.Register(Form child)
        {
            Frame.Closing += (a, s) => child.Close();
        }

        internal void Run() => Application.Run(Context);
    }
}


text:
package pl.jakubchmura.snmp.mib.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import pl.jakubchmura.snmp.mib.reference.SmiReference;

public interface SmiModuleIdentifier extends SmiIdentifiableElement {

  @NotNull
  List<SmiNameAndNumber> getNameAndNumberList();

  @NotNull
  List<SmiNameValueIndex> getNameValueIndexList();

  @NotNull
  List<SmiNameValueString> getNameValueStringList();

  @NotNull
  PsiElement getIdentifierString();

  @NotNull
  String getName();

  PsiElement setName(String name);

  SmiReference getReference();

}


text:
require('jquery');
require('bootstrap');

var ko = require('knockout');
var MoodFormViewModel = require('viewModels/MoodFormViewModel').MoodFormViewModel;

ko.applyBindings(new MoodFormViewModel());


text:
goog.addDependency("../../../../../test/web-config.js", ['config'], []);
goog.addDependency("../../../../../src/0_queue.js", ['task_queue'], []);
goog.addDependency("../../../../../src/1_utils.js", ['utils'], ['goog.json', 'config']);
goog.addDependency("../../../../../src/2_resources.js", ['resources'], ['utils', 'config']);
goog.addDependency("../../../../../src/2_session.js", ['session'], ['goog.json', 'utils']);
goog.addDependency("../../../../../src/2_storage.js", ['storage'], ['goog.json', 'utils']);
goog.addDependency("../../../../../src/3_api.js", ['Server'], ['utils', 'goog.json', 'storage']);
goog.addDependency("../../../../../src/3_banner_utils.js", ['banner_utils'], ['storage', 'utils']);
goog.addDependency("../../../../../src/4_banner_css.js", ['banner_css'], ['banner_utils', 'utils']);
goog.addDependency("../../../../../src/4_banner_html.js", ['banner_html'], ['banner_utils', 'utils', 'session', 'storage']);
goog.addDependency("../../../../../src/5_banner.js", ['banner'], ['utils', 'banner_utils', 'banner_css', 'banner_html']);
goog.addDependency("../../../../../src/6_branch.js", ['Branch'], ['goog.json', 'utils', 'resources', 'Server', 'banner', 'task_queue', 'storage', 'session', 'config']);
goog.addDependency("../../../../../src/7_initialization.js", ['branch_instance'], ['Branch', 'config']);
goog.addDependency("../../../../../src/extern.js", [], []);
goog.addDependency("../../../../../src/onpage.js", [], []);
goog.addDependency("../../../../../test/0_queue.js", [], ['task_queue']);
goog.addDependency("../../../../../test/1_utils.js", [], ['utils']);
goog.addDependency("../../../../../test/2_storage.js", [], ['storage']);
goog.addDependency("../../../../../test/3_api.js", [], ['utils', 'Server', 'resources', 'storage', 'config']);
goog.addDependency("../../../../../test/6_branch.js", [], ['utils', 'Branch', 'resources', 'config', 'storage', 'session', 'goog.json']);
goog.addDependency("../../../../../test/7_integration.js", [], ['config', 'goog.json']);
goog.addDependency("../../../../../test/saucelabs.js", [], []);
goog.addDependency("../../../../../test/test-utils.js", [], []);
goog.addDependency("../../../../../test/web-config.js", ['config'], []);


text:
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , bcrypt = require('bcrypt')

  , InviteCode = require('./invite')

var UserSchema = new Schema({
    email: { type: String, required: true, index: true }
  , salt: { type: String, required: true }
  , hash: { type: String, required: true }
  // 0 = normal user, 1 = strider admin
  , account_level: Number
  // defined by provider plugins
  , accounts: [{
      provider: String, // name of the provider plugin
      id: String,       // account id, defined by the provider
      title: String,    // human readable account name
      display_url: String, // url to view your account on the hosted site
      // cache for provided repos
      cache: [{
        id: String,          // unique ID, saved as "repo_id" in the provider section of the created project
        name: String,        // human readable, displayed to the user
        display_name: String,
        config: {},
        display_url: String, // a url where the user can view the repo in a browser
        group: String        // a string for grouping the repos. In github, this would be the "organization"
      }],
      last_updated: Date,
      config: {},
    }]
  // user-level config
  , jobplugins: {}
  // array of objects {name: "projectname", access_level: (int), display_name: (string)}
  , projects: [
        {
          name: {type: String, index: true}, // lower-case canonical name
          display_name: String, // could be mixed case
          access_level: Number  // 0 - view jobs, 1 - start jobs, 2 - configure/admin
        }
    ]
  , jobs: [{type: Schema.ObjectId, ref: 'Job'}]
  , created: Date
});

// removed:
// findCollaborators
// get_repo_config

UserSchema.virtual('password')
.get(function () {
  return this._password;
})
.set(function (password) {
  this._password = password;
  var salt = this.salt = bcrypt.genSaltSync(10);
  this.hash = bcrypt.hashSync(password, salt);
});

// User.collaborators(project, [accessLevel,] done(err, [user, ...]))
//
// project: String name of the project
// accessLevel: int minimum access level. Defaults to 1
UserSchema.static('collaborators', function (project, accessLevel, done) {
  if (arguments.length === 2) {
    done = accessLevel
    accessLevel = 1
  }
  var query = {
    'projects': {
      '$elemMatch': {
        'name': project.toLowerCase(),
        'access_level': {$gte: accessLevel}
      }
    },
  }
  this.find(query, done)
})

// User.admins(done(err, [user, ...]))
UserSchema.static('admins', function (done) {
  var query = { 'account_level': 1 }
  this.find(query, done)
})

// User.account(providerconfig)
// User.account(providerid, accountid)
// --> the account config that matches
// Throws an error if the account cannot be found.
UserSchema.method('account', function (provider, account) {
  if (arguments.length === 1) {
    account = provider.account
    provider = provider.id
  }
  for (var i=0; i<this.accounts.length; i++) {
    if (this.accounts[i].provider == provider &&
        this.accounts[i].id == account) {
      return this.accounts[i]
    }
  }
  return false
})

UserSchema.method('verifyPassword', function(password, callback) {
  bcrypt.compare(password, this.get('hash'), callback);
});

UserSchema.method('jobPluginData', function (name, config, done) {
  if (!this.jobplugins) {
    this.jobplugins = {}
  }
  if (arguments.length === 1) {
    return this.jobplugins[name]
  }
  this.jobplugins[name] = config
  this.markModified('jobplugins')
  this.save(done)
});

UserSchema.static('authenticate', function(email, password, callback) {
  this.findOne({ email: email }, function(err, user) {
    if (err) { return callback(err); }
    if (!user) { return callback("No User", false); }

    user.verifyPassword(password, function(err, passwordCorrect) {
      if (err) { return callback(err); }
      if (!passwordCorrect) { return callback("Incorrect PWD", false); }
      return callback(null, user);
    });
  });
})

UserSchema.static('findByEmail', function(email, cb){
  this.find({ email : email }, cb)
})

UserSchema.static('registerWithInvite', function(inviteCode, email, password, cb) {
  // Check Invite Code
  InviteCode.findOne({code:inviteCode, consumed_timestamp:null}, function(err, invite){

    if (err || !invite ){
      return cb("Invalid Invite")
    }

    // Create User
    var user = new User()
    user.email = email
    user.created = new Date()
    user.set('password', password)
    user.projects = []
    // For each collaboration in the invite, add permissions to the repo_config
    if (invite.collaborations !== undefined && invite.collaborations.length > 0) {
      invite.collaborations.forEach(function(item) {
        user.projects.push({name: item.project.toLowerCase(), access_level:item.access_level, display_name: item.project.toLowerCase()})
      })
    }
    user.save(function (e, user) {
      if (e) return cb("Error Creating User:" + e)

      // Mark Invite Code as used.
      InviteCode.update(
          {code:inviteCode}
        , {"$set": {consumed_timestamp:new Date(), consumed_by_user:user._id}}
        , {}
        , function(err, num) {
          if (err)
            return cb("Error updating invite code, user was created: " + err)
          else
            return cb(null, user)
        }
      )
    })
  })
})

var User = module.exports = mongoose.model('user', UserSchema)