text:
package com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.database;

import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException;
import com.bitdubai.fermat_api.layer.all_definition.resources_structure.enums.ScreenSize;
import com.bitdubai.fermat_api.layer.all_definition.util.Version;
import com.bitdubai.fermat_wpd_api.layer.wpd_sub_app_module.wallet_publisher.interfaces.ComponentVersionDetail;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterOperator;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFilter;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseTransactionFailedException;
import com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.exceptions.CantDeleteRecordDataBaseException;
import com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.exceptions.CantReadRecordDataBaseException;
import com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.exceptions.CantUpdateRecordDataBaseException;
import com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.structure.ComponentVersionDetailMiddlewareImpl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * The Class com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.database.InformationPublishedComponentDao have
 * all methods implementation to access the data base (CRUD)
 *

 * Created by Roberto Requena - (rart3001@gmail.com) on 03/08/15.
 *
 * @version 1.0
 * @since Java JDK 1.7
 */
public class ComponentVersionDetailDao {

    /**
     * Represent the dataBase
     */
    private Database dataBase;

    /**
     * Constructor with parameters
     *
     * @param dataBase
     */
    public ComponentVersionDetailDao(Database dataBase) {
        super();
        this.dataBase = dataBase;
    }

    /**
     * Return the Database
     *
     * @return Database
     */
    Database getDataBase() {
        return dataBase;
    }

    /**
     * Return the DatabaseTable
     *
     * @return DatabaseTable
     */
    DatabaseTable getDatabaseTable() {
        return getDataBase().getTable(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_TABLE_NAME);
    }

    /**
     * Method that find an ComponentVersionDetailImpl by id in the data base.
     *
     * @param id Long id.
     * @return ComponentVersionDetailImpl found.
     * @throws CantReadRecordDataBaseException
     */
    public ComponentVersionDetail findById(String id) throws CantReadRecordDataBaseException {

        if (id == null) {
            throw new IllegalArgumentException("The id is required, can not be null");
        }

        ComponentVersionDetailMiddlewareImpl walletPublishedMiddlewareInformation = null;

        try {

            /*
             * 1 - load the data base to memory with filter
             */
            getDataBase().openDatabase();
            DatabaseTable incomingMessageTable = getDatabaseTable();
            incomingMessageTable.setStringFilter(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FIRST_KEY_COLUMN, id, DatabaseFilterType.EQUAL);
            incomingMessageTable.loadToMemory();

            /*
             * 2 - read all records
             */
            List<DatabaseTableRecord> records = incomingMessageTable.getRecords();

            /*
             * 3 - Convert into ComponentVersionDetailImpl objects
             */
            for (DatabaseTableRecord record : records) {

                /*
                 * 3.1 - Create and configure a  ComponentVersionDetailImpl
                 */
                walletPublishedMiddlewareInformation = constructFrom(record);
            }

        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The data no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, cantLoadTableToMemory, context, possibleCause);
            throw cantReadRecordDataBaseException;
        } catch (DatabaseNotFoundException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (CantOpenDatabaseException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (Exception e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "Other problems";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

        return walletPublishedMiddlewareInformation;
    }

    ;

    /**
     * Method that list the all entities on the data base.
     *
     * @return All ComponentVersionDetailImpl.
     * @throws CantReadRecordDataBaseException
     */
    public List<ComponentVersionDetail> findAll() throws CantReadRecordDataBaseException {

        List<ComponentVersionDetail> list = null;

        try {

            /*
             * 1 - load the data base to memory
             */
            getDataBase().openDatabase();
            DatabaseTable walletPublishedMiddlewareInformationTable = getDatabaseTable();
            walletPublishedMiddlewareInformationTable.loadToMemory();

            /*
             * 2 - read all records
             */
            List<DatabaseTableRecord> records = walletPublishedMiddlewareInformationTable.getRecords();

            /*
             * 3 - Create a list of ComponentVersionDetailImpl objects
             */
            list = new ArrayList<>();
            list.clear();

            /*
             * 4 - Convert into ComponentVersionDetailImpl objects
             */
            for (DatabaseTableRecord record : records) {

                /*
                 * 4.1 - Create and configure a  ComponentVersionDetailImpl
                 */
                ComponentVersionDetailMiddlewareImpl walletPublishedMiddlewareInformation = constructFrom(record);

                /*
                 * 4.2 - Add to the list
                 */
                list.add(walletPublishedMiddlewareInformation);

            }

        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The data no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, cantLoadTableToMemory, context, possibleCause);
            throw cantReadRecordDataBaseException;
        } catch (DatabaseNotFoundException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (CantOpenDatabaseException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (Exception e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "Other problems";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

        /*
         * return the list
         */
        return list;
    }

    ;

    /**
     * Method that list the all entities on the data base. The valid value of
     * the column name are the att of the WalletPublisherMiddlewareDatabaseConstants
     *
     * @return All ComponentVersionDetailImpl.
     * @throws CantReadRecordDataBaseException
     * @see WalletPublisherMiddlewareDatabaseConstants
     */
    public List<ComponentVersionDetail> findAll(String columnName, String columnValue) throws CantReadRecordDataBaseException {

        if (columnName == null ||
                columnName.isEmpty() ||
                columnValue == null ||
                columnValue.isEmpty()) {

            throw new IllegalArgumentException("The filter are required, can not be null or empty");
        }

        List<ComponentVersionDetail> list = null;

        try {

            /*
             * 1 - load the data base to memory with filters
             */
            getDataBase().openDatabase();
            DatabaseTable walletPublishedMiddlewareInformationTable = getDatabaseTable();
            walletPublishedMiddlewareInformationTable.setStringFilter(columnName, columnValue, DatabaseFilterType.EQUAL);
            walletPublishedMiddlewareInformationTable.loadToMemory();

            /*
             * 2 - read all records
             */
            List<DatabaseTableRecord> records = walletPublishedMiddlewareInformationTable.getRecords();

            /*
             * 3 - Create a list of ComponentVersionDetailImpl objects
             */
            list = new ArrayList<>();
            list.clear();

            /*
             * 4 - Convert into ComponentVersionDetailImpl objects
             */
            for (DatabaseTableRecord record : records) {

                /*
                 * 4.1 - Create and configure a  ComponentVersionDetailImpl
                 */
                ComponentVersionDetailMiddlewareImpl walletPublishedMiddlewareInformation = constructFrom(record);

                /*
                 * 4.2 - Add to the list
                 */
                list.add(walletPublishedMiddlewareInformation);

            }

        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The data no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, cantLoadTableToMemory, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (DatabaseNotFoundException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (CantOpenDatabaseException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (Exception e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "Other problems";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

        /*
         * return the list
         */
        return list;
    }

    ;

    /**
     * Method that list the all entities on the data base. The valid value of
     * the key are the att of the WalletPublisherMiddlewareDatabaseConstants
     *
     * @param filters
     * @return List<ComponentVersionDetailImpl>
     * @throws CantReadRecordDataBaseException
     */
    public List<ComponentVersionDetail> findAll(Map<String, Object> filters) throws CantReadRecordDataBaseException {

        if (filters == null ||
                filters.isEmpty()) {

            throw new IllegalArgumentException("The filters are required, can not be null or empty");
        }

        List<ComponentVersionDetail> list = null;
        List<DatabaseTableFilter> filtersTable = new ArrayList<>();

        try {

            /*
             * 1- Prepare the filters
             */
            getDataBase().openDatabase();
            DatabaseTable walletPublishedMiddlewareInformationTable = getDatabaseTable();

            for (String key : filters.keySet()) {

                DatabaseTableFilter newFilter = walletPublishedMiddlewareInformationTable.getEmptyTableFilter();
                newFilter.setType(DatabaseFilterType.EQUAL);
                newFilter.setColumn(key);
                newFilter.setValue((String) filters.get(key));

                filtersTable.add(newFilter);
            }

            /*
             * 2 - load the data base to memory with filters
             */
            walletPublishedMiddlewareInformationTable.setFilterGroup(filtersTable, null, DatabaseFilterOperator.OR);
            walletPublishedMiddlewareInformationTable.loadToMemory();

            /*
             * 3 - read all records
             */
            List<DatabaseTableRecord> records = walletPublishedMiddlewareInformationTable.getRecords();

            /*
             * 4 - Create a list of ComponentVersionDetailImpl objects
             */
            list = new ArrayList<>();
            list.clear();

            /*
             * 5 - Convert into ComponentVersionDetailImpl objects
             */
            for (DatabaseTableRecord record : records) {

                /*
                 * 5.1 - Create and configure a  ComponentVersionDetailImpl
                 */
                ComponentVersionDetailMiddlewareImpl walletPublishedMiddlewareInformation = constructFrom(record);

                /*
                 * 5.2 - Add to the list
                 */
                list.add(walletPublishedMiddlewareInformation);

            }

        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The data no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, cantLoadTableToMemory, context, possibleCause);
            throw cantReadRecordDataBaseException;
        } catch (DatabaseNotFoundException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (CantOpenDatabaseException e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database no exist";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } catch (Exception e) {

            // Register the failure.
            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "Other problems";
            CantReadRecordDataBaseException cantReadRecordDataBaseException = new CantReadRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantReadRecordDataBaseException;

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

        /*
         * return the list
         */
        return list;
    }

    ;

    /**
     * Method that update an entity in the data base.
     *
     * @param entity ComponentVersionDetailImpl to update.
     * @throws CantUpdateRecordDataBaseException
     */
    public void update(ComponentVersionDetailMiddlewareImpl entity) throws CantUpdateRecordDataBaseException {

        if (entity == null) {
            throw new IllegalArgumentException("The entity is required, can not be null");
        }

        try {

            /*
             * 1- Create the record to the entity
             */
            getDataBase().openDatabase();
            DatabaseTableRecord entityRecord = constructFrom(entity);

            /*
             * 2.- Create a new transaction and execute
             */
            DatabaseTransaction transaction = getDataBase().newTransaction();
            transaction.addRecordToUpdate(getDatabaseTable(), entityRecord);
            getDataBase().executeTransaction(transaction);

        } catch (DatabaseTransactionFailedException databaseTransactionFailedException) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The record do not exist";
            CantUpdateRecordDataBaseException cantUpdateRecordDataBaseException = new CantUpdateRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, databaseTransactionFailedException, context, possibleCause);
            throw cantUpdateRecordDataBaseException;

        } catch (DatabaseNotFoundException e) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database not exist";
            throw new CantUpdateRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);

        } catch (CantOpenDatabaseException e) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database not exist";
            throw new CantUpdateRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

    }

    /**
     * Method that delete a entity in the data base.
     *
     * @param id Long id.
     * @throws CantDeleteRecordDataBaseException
     */
    public void delete(Long id) throws CantDeleteRecordDataBaseException {

        if (id == null) {
            throw new IllegalArgumentException("The id is required can not be null");
        }

        try {

            /*
             * Create a new transaction and execute
             */
            getDataBase().openDatabase();
            DatabaseTransaction transaction = getDataBase().newTransaction();

            //TODO: falta configurar la llamada para borrar la entidad

            getDataBase().executeTransaction(transaction);

        } catch (DatabaseTransactionFailedException databaseTransactionFailedException) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The record do not exist";
            CantDeleteRecordDataBaseException cantDeleteRecordDataBaseException = new CantDeleteRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, databaseTransactionFailedException, context, possibleCause);
            throw cantDeleteRecordDataBaseException;

        } catch (DatabaseNotFoundException e) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database do not exist";
            CantDeleteRecordDataBaseException cantDeleteRecordDataBaseException = new CantDeleteRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantDeleteRecordDataBaseException;

        } catch (CantOpenDatabaseException e) {

            StringBuffer contextBuffer = new StringBuffer();
            contextBuffer.append("Database Name: " + WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);

            String context = contextBuffer.toString();
            String possibleCause = "The database do not exist";
            CantDeleteRecordDataBaseException cantDeleteRecordDataBaseException = new CantDeleteRecordDataBaseException(CantDeleteRecordDataBaseException.DEFAULT_MESSAGE, e, context, possibleCause);
            throw cantDeleteRecordDataBaseException;

        } finally {

            if (getDataBase() != null) {
                getDataBase().closeDatabase();
            }
        }

    }

    /**
     * Construct a ComponentVersionDetailImpl whit the values of the table record pass
     * by parameter
     *
     * @param record with values from the table
     * @return ComponentVersionDetailImpl setters the values from table
     */
    private ComponentVersionDetailMiddlewareImpl constructFrom(DatabaseTableRecord record) throws InvalidParameterException {

        ComponentVersionDetailMiddlewareImpl componentVersionDetailImpl = new ComponentVersionDetailMiddlewareImpl();

        componentVersionDetailImpl.setId(UUID.fromString(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_ID_COLUMN_NAME)));
        componentVersionDetailImpl.setScreenSize(ScreenSize.getByCode(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_SCREEN_SIZE_COLUMN_NAME)));
        componentVersionDetailImpl.setVersion(new Version(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_COLUMN_NAME)));
        componentVersionDetailImpl.setVersionTimestamp(new Timestamp(record.getLongValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_TIMESTAMP_COLUMN_NAME)));
        componentVersionDetailImpl.setInitialWalletVersion(new Version(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_WALLET_VERSION_COLUMN_NAME)));
        componentVersionDetailImpl.setFinalWalletVersion(new Version(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_WALLET_VERSION_COLUMN_NAME)));
        componentVersionDetailImpl.setInitialPlatformVersion(new Version(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_PLATFORM_VERSION_COLUMN_NAME)));
        componentVersionDetailImpl.setFinalPlatformVersion(new Version(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_PLATFORM_VERSION_COLUMN_NAME)));
        componentVersionDetailImpl.setObservations(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_OBSERVATIONS_COLUMN_NAME));
        componentVersionDetailImpl.setCatalogId(UUID.fromString(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_CATALOG_ID_COLUMN_NAME)));
        componentVersionDetailImpl.setComponentId(UUID.fromString(record.getStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_COMPONENT_ID_COLUMN_NAME)));

        return componentVersionDetailImpl;
    }

    /**
     * Construct a DatabaseTableRecord whit the values of the a componentVersionDetailImpl pass
     * by parameter
     *
     * @param componentVersionDetailImpl the contains the values
     * @return DatabaseTableRecord whit the values
     */
    private DatabaseTableRecord constructFrom(ComponentVersionDetailMiddlewareImpl componentVersionDetailImpl) {
        /*
         * Create the record to the entity
         */
        DatabaseTableRecord entityRecord = getDatabaseTable().getEmptyRecord();
        /*
         * Set the entity values
         */
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_ID_COLUMN_NAME, componentVersionDetailImpl.getId().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_SCREEN_SIZE_COLUMN_NAME, componentVersionDetailImpl.getScreenSize().getCode());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_COLUMN_NAME, componentVersionDetailImpl.getVersion().toString());
        entityRecord.setLongValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_TIMESTAMP_COLUMN_NAME, componentVersionDetailImpl.getVersionTimestamp().getTime());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_WALLET_VERSION_COLUMN_NAME, componentVersionDetailImpl.getInitialWalletVersion().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_WALLET_VERSION_COLUMN_NAME, componentVersionDetailImpl.getFinalWalletVersion().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_PLATFORM_VERSION_COLUMN_NAME, componentVersionDetailImpl.getInitialPlatformVersion().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_PLATFORM_VERSION_COLUMN_NAME, componentVersionDetailImpl.getFinalPlatformVersion().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_OBSERVATIONS_COLUMN_NAME, componentVersionDetailImpl.getObservations().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_CATALOG_ID_COLUMN_NAME, componentVersionDetailImpl.getCatalogId().toString());
        entityRecord.setStringValue(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_COMPONENT_ID_COLUMN_NAME, componentVersionDetailImpl.getComponentId().toString());
        /*
         * return the new table record
         */
        return entityRecord;
    }
}


text:
VLC-Simple-Player-Android
=========================

**Basic Movie Player for Android using VLC Library**

*The project was created with Android Studio*

##What is it ?

This project is to understand how to implement VLC Library in your Android Project.

It works with direct URL for streaming or you can directly put local movie path.

![alt tag](http://wassimsamad.fr/images/home.png)
![alt tag](http://wassimsamad.fr/images/fullscreen.png)
![alt tag](http://wassimsamad.fr/images/fullscreen_overlay.png)

##Improvements ?

You are free to do whatever you want with it. It's very basic.

Improve the UI to your needs, add functionnalities and make your powerful player.

# Thank you !
### For more tutorials : [Visit my blog here ](http://www.wassimsamad.fr/blog)

redpajama_set_name: RedPajamaGithub


text:
<?php

//use Auryn\Injector;
//
//require_once(__DIR__.'/../vendor/autoload.php');
//require_once __DIR__ . '/injectionParamsCliTest.php';
//require_once __DIR__ . '/../lib/factories.php';
//require_once __DIR__ . '/../lib/functions.php';
//require_once __DIR__ . '/../lib/functions_test.php';
//require_once(__DIR__ . '/../vendor/fzaninotto/faker/src/autoload.php');
//


text:
export type PromiseSuccess = {
  result: T,
  status: 'success',
  args: Array
};

export type PromiseFailure = {
  error: any,
  status: 'error',
  args: Array
};

export type PromiseResult = PromiseSuccess | PromiseFailure;

type PromiseFunction = (...args: Array) => Promise<T>;

export function promiseWrapper(
  promiseFunc: PromiseFunction
): PromiseFunction<A, PromiseResult> {
  return (...args: Array): Promise<PromiseResult> => {
    return promiseFunc(...args).then(
      result => ({ result, status: 'success', args }),
      error => ({ error, status: 'error', args })
    );
  };
}

export function promiseWrapperSuccess(
  promiseFunc: PromiseFunction
): PromiseFunction<A, PromiseResult> {
  return (...args: Array): Promise<PromiseResult> => {
    return promiseFunc(...args).then(result => ({
      result,
      status: 'success',
      args
    }));
  };
}


text:
"""
Module of AccessibleAssociation interface.
"""

class AccessibleAssociation:
    """
    The AccessibleAssociation interface improve accessibility, associating
    elements.
    """

    def associate_data_cells_with_header_cells(self, table):
        """
        Associate all data cells with header cells of table.

        :param table: The table.
        :type table: hatemile.util.html.htmldomelement.HTMLDOMElement
        """

        pass

    def associate_all_data_cells_with_header_cells(self):
        """
        Associate all data cells with header cells of all tables of page.
        """

        pass

    def associate_label_with_field(self, label):
        """
        Associate label with field.

        :param label: The label.
        :type label: hatemile.util.html.htmldomelement.HTMLDOMElement
        """

        pass

    def associate_all_labels_with_fields(self):
        """
        Associate all labels of page with fields.
        """

        pass


text:
var Suite = require('../../lib/suite');
var Test = require('../../lib/test');
var Runner = require('../../lib/runner');

describe('a test that throws', function () {
  var suite, runner;

  beforeEach(function(){
    suite = new Suite('Suite', 'root');
    runner = new Runner(suite);
  })

  describe('undefined', function (){
    it('should not pass if throwing sync and test is sync', function(done) {
      var test = new Test('im sync and throw undefined sync', function(){
        throw undefined;
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    })

    it('should not pass if throwing sync and test is async', function(done){
      var test = new Test('im async and throw undefined sync', function(done2){
        throw undefined;
        process.nexTick(done2);
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    });

    it('should not pass if throwing async and test is async', function(done){
      var test = new Test('im async and throw undefined async', function(done2){
        process.nexTick(function(){
          throw undefined;
          done2();
        });
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    })
  })

  describe('null', function (){
    it('should not pass if throwing sync and test is sync', function(done) {
      var test = new Test('im sync and throw null sync', function(){
        throw null;
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    })

    it('should not pass if throwing sync and test is async', function(done){
      var test = new Test('im async and throw null sync', function(done2){
        throw null;
        process.nexTick(done2);
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    });

    it('should not pass if throwing async and test is async', function(done){
      var test = new Test('im async and throw null async', function(done2){
        process.nexTick(function(){
          throw null;
          done2();
        });
      });
      suite.addTest(test);
      runner = new Runner(suite);
      runner.on('end', function(){
        expect(runner.failures).to.equal(1);
        expect(test.state).to.equal('failed');
        done();
      });
      runner.run();
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>

<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="@dimen/group_padding"
    android:orientation="vertical">

    <LinearLayout style="@style/Theme.Calculator.ButtonRowStyle">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/sin"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arcsin"
            android:text="@string/sin" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/cos"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arccos"
            android:text="@string/cos" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/tan"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arctan"
            android:text="@string/tan" />
    </LinearLayout>

    <LinearLayout style="@style/Theme.Calculator.ButtonRowStyle">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/lg"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/lg" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/ln"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/ln" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/e"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/e" />
    </LinearLayout>

    <LinearLayout style="@style/Theme.Calculator.ButtonRowStyle">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/pi"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/pi" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/i"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/i" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/power"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/power" />
    </LinearLayout>

    <LinearLayout style="@style/Theme.Calculator.ButtonRowStyle">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/factorial"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/factorial" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/sqrt"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/cbrt"
            android:text="@string/sqrt" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/percentage"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/percentage" />
    </LinearLayout>

    <LinearLayout style="@style/Theme.Calculator.ButtonRowStyle">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/X"
            style="@style/Theme.Calculator.ButtonStyle.Digit"
            android:text="@string/X" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/Y"
            style="@style/Theme.Calculator.ButtonStyle.Digit"
            android:text="@string/Y" />
    </LinearLayout>
</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="What's new"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="spldoc_page"/>
<link rel="stylesheet" type="text/css" href="../../html/commonltr.css"/>
<link rel="stylesheet" type="text/css" href="../../html/spldoc.css"/>
<title>What's new</title>

What's new

IBMStreams com.ibm.streamsx.network Toolkit > com.ibm.streamsx.network 3.4.3 > What's new

This is an overview of changes for major and minor version upgrades.

What is new in version 3.4.3

What is new in version 3.4.2

What is new in version 3.4.1

What is new in version 3.4.0

What is changed in version 3.3.1

What is changed in version 3.3.0

What is changed in version 3.2.2

What is new in version 3.2.1

What is new in version 3.1.0


text:
#include <type_traits>
#include <hyperscale/syntax/token_kinds.hpp>

namespace hyperscale {
namespace syntax {

    std::ostream& operator<<(std::ostream& os, const TokenKind kind) {
        return os << TokenNames.at(kind);
    }

} // end of syntax namespace
} // end of hyperscale namespace


text:
package org.jboss.weld.tests.alternatives.customBeanPriority;

import javax.enterprise.context.Dependent;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;

import org.jboss.weld.bootstrap.event.WeldAfterBeanDiscovery;

/**
 *
 * @author Matej Novotny
 */
public class MyExtension implements Extension {

    public void observe(@Observes WeldAfterBeanDiscovery abd, BeanManager bm) {
        // register an alternative bean via configurator with priority
        abd.addBean()
            .beanClass(FooAlternative.class)
            .types(Object.class, FooAlternative.class, PlainFoo.class)
            .createWith((ctx) -> new FooAlternative())
            .alternative(true)
            .priority(100)
            .qualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE)
            .scope(Dependent.class);
    }
}


text:
#include "ofApp.h"

/*
    Simple example to demonstrate the Dropdown Component
    https://github.com/braitsch/ofxDatGui @braitsch
*/

void ofApp::setup()
{
    ofSetWindowPosition(0, 0);

// create a vector of colors to populate our dropdown //
    colors.push_back(ofColor::fromHex(0xFFD00B));
    colors.push_back(ofColor::fromHex(0x2FA1D6));
    colors.push_back(ofColor::fromHex(0x1ED36F));
    colors.push_back(ofColor::fromHex(0xC63256));

// convert the hex values of those colors to strings for the menu labels //
    vector<string> options;
    for (int i=0; i<colors.size(); i++) options.push_back(getHex(colors[i].getHex()));

// instantiate the dropdown //
    menu = new ofxDatGuiDropdown("SELECT A COLOR", options);

// and position it in the middle of the screen //
    menu->setPosition(ofGetWidth()/2 - menu->getWidth()/2, ofGetHeight()/2 - menu->getHeight()/2 - 100);

// let's set the stripe of each option to its respective color //
    for (int i=0; i<menu->size(); i++) menu->getChildAt(i)->setStripeColor(colors[i]);

// register to listen for change events //
    menu->onDropdownEvent(this, &ofApp::onDropdownEvent);

// finally let's have it open by default //
    menu->expand();
}

void ofApp::onDropdownEvent(ofxDatGuiDropdownEvent e)
{
    ofSetBackgroundColor(colors[e.child]);
    menu->setStripeColor(ofColor::white);
}

string ofApp::getHex(int hex)
{
// convert decimal value to hex //
    std::stringstream ss;
    ss<< std::hex << hex;
    std::string res ( ss.str() );
    while(res.size() < 6) res+="0";
    return "#"+ofToUpper(res);
}

void ofApp::update()
{
    menu->update();
}

void ofApp::draw()
{
    menu->draw();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<snippetsTree>
 <snippets file="target/tutorial/mixed/file0/results/word/frequencies/results.xml">
  <result title="frequency" word="LALv" count="235"/>
  <result title="frequency" word="lineage" count="195"/>
  <result title="frequency" word="otd" count="193"/>
  <result title="frequency" word="antennal" count="134"/>
  <result title="frequency" word="neuroblast" count="115"/>
  <result title="frequency" word="lobe" count="107"/>
  <result title="frequency" word="neurons" count="107"/>
  <result title="frequency" word="−/−" count="104"/>
  <result title="frequency" word="brain" count="93"/>
  <result title="frequency" word="Figure" count="92"/>
  <result title="frequency" word="al.," count="75"/>
  <result title="frequency" word="transformed" count="68"/>
  <result title="frequency" word="cell" count="65"/>
  <result title="frequency" word="clones" count="63"/>
  <result title="frequency" word="central" count="57"/>
  <result title="frequency" word="wild-type" count="56"/>
  <result title="frequency" word="Drosophila" count="55"/>
  <result title="frequency" word="neural" count="54"/>
  <result title="frequency" word="lineage." count="53"/>
  <result title="frequency" word="complex" count="48"/>
  <result title="frequency" word="cells" count="46"/>
  <result title="frequency" word="ALad" count="44"/>
  <result title="frequency" word="functional" count="44"/>
  <result title="frequency" word="Otd" count="42"/>
  <result title="frequency" word="olfactory" count="41"/>
  <result title="frequency" word="tract" count="40"/>
  <result title="frequency" word="MARCM" count="39"/>
  <result title="frequency" word="adult" count="39"/>
  <result title="frequency" word="expression" count="39"/>
  <result title="frequency" word="lineages" count="39"/>
  <result title="frequency" word="lines" count="39"/>
  <result title="frequency" word="identity" count="38"/>
  <result title="frequency" word="projection" count="38"/>
  <result title="frequency" word="dotted" count="32"/>
  <result title="frequency" word="labelled" count="32"/>
  <result title="frequency" word="single" count="32"/>
  <result title="frequency" word="driver" count="31"/>
  <result title="frequency" word="ALv" count="30"/>
  <result title="frequency" word="different" count="30"/>
  <result title="frequency" word="molecular" count="30"/>
  <result title="frequency" word="loss" count="28"/>
  <result title="frequency" word="gene" count="27"/>
  <result title="frequency" word="used" count="27"/>
  <result title="frequency" word="./eLife.." count="26"/>
  <result title="frequency" word="development" count="26"/>
  <result title="frequency" word="lateral" count="26"/>
  <result title="frequency" word="brain." count="25"/>
  <result title="frequency" word="larval" count="25"/>
  <result title="frequency" word="shows" count="25"/>
  <result title="frequency" word="DOI:" count="24"/>
  <result title="frequency" word="http://dx.doi.org/./eLife.." count="24"/>
  <result title="frequency" word="transformation" count="24"/>
  <result title="frequency" word="lineage," count="23"/>
  <result title="frequency" word="Gal" count="22"/>
  <result title="frequency" word="neuroblasts" count="22"/>
  <result title="frequency" word="neuronal" count="22"/>
  <result title="frequency" word="-/-" count="21"/>
  <result title="frequency" word="bodies" count="21"/>
 </snippets>
</snippetsTree>


text:
package testing

import (
	"context"
	"fmt"
	"testing"

	"github.com/influxdata/influxdb"
)

// PasswordFields will include the IDGenerator, and users and their passwords.
type PasswordFields struct {
	IDGenerator influxdb.IDGenerator
	Users       []*influxdb.User
	Passwords   []string // passwords are indexed against the Users field
}

// PasswordsService tests all the service functions.
func PasswordsService(
	init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()), t *testing.T,
) {
	tests := []struct {
		name string
		fn   func(init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()),
			t *testing.T)
	}{
		{
			name: "SetPassword",
			fn:   SetPassword,
		},
		{
			name: "ComparePassword",
			fn:   ComparePassword,
		},
		{
			name: "CompareAndSetPassword",
			fn:   CompareAndSetPassword,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.fn(init, t)
		})
	}
}

// SetPassword tests overriding the password of a known user
func SetPassword(
	init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()),
	t *testing.T) {
	type args struct {
		user     string
		password string
	}
	type wants struct {
		err error
	}
	tests := []struct {
		name   string
		fields PasswordFields
		args   args
		wants  wants
	}{
		{
			name: "setting password longer than 8 characters works",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
			},
			args: args{
				user:     "user1",
				password: "howdydoody",
			},
			wants: wants{},
		},
		{
			name: "passwords that are too short have errors",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
			},
			args: args{
				user:     "user1",
				password: "short",
			},
			wants: wants{
				err: fmt.Errorf("<invalid> passwords must be at least 8 characters long"),
			},
		},
		{
			name: "setting a password for a non-existent user is a generic-like error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
			},
			args: args{
				user:     "invalid",
				password: "howdydoody",
			},
			wants: wants{
				err: fmt.Errorf("<forbidden> your username or password is incorrect"),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s, done := init(tt.fields, t)
			defer done()
			ctx := context.Background()

			err := s.SetPassword(ctx, tt.args.user, tt.args.password)

			if (err != nil && tt.wants.err == nil) || (err == nil && tt.wants.err != nil) {
				t.Fatalf("expected SetPassword error %v got %v", tt.wants.err, err)
				return
			}

			if err != nil {
				if want, got := tt.wants.err.Error(), err.Error(); want != got {
					t.Fatalf("expected SetPassword error %v got %v", want, got)
				}
				return
			}
		})
	}
}

// ComparePassword tests setting and comparing passwords.
func ComparePassword(
	init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()),
	t *testing.T) {
	type args struct {
		user     string
		password string
	}
	type wants struct {
		err error
	}
	tests := []struct {
		name   string
		fields PasswordFields
		args   args
		wants  wants
	}{
		{
			name: "comparing same password is not an error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user:     "user1",
				password: "howdydoody",
			},
			wants: wants{},
		},
		{
			name: "comparing different password is an error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user:     "user1",
				password: "wrongpassword",
			},
			wants: wants{
				err: fmt.Errorf("<forbidden> your username or password is incorrect"),
			},
		},
		{
			name: "comparing a password to a non-existent user is a generic-like error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user:     "invalid",
				password: "howdydoody",
			},
			wants: wants{
				err: fmt.Errorf("<forbidden> your username or password is incorrect"),
			},
		},
		{
			name: "user exists but no password has been set",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
			},
			args: args{
				user:     "user1",
				password: "howdydoody",
			},
			wants: wants{
				err: fmt.Errorf("<forbidden> your username or password is incorrect"),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s, done := init(tt.fields, t)
			defer done()
			ctx := context.Background()

			err := s.ComparePassword(ctx, tt.args.user, tt.args.password)

			if (err != nil && tt.wants.err == nil) || (err == nil && tt.wants.err != nil) {
				t.Fatalf("expected ComparePassword error %v got %v", tt.wants.err, err)
				return
			}

			if err != nil {
				if want, got := tt.wants.err.Error(), err.Error(); want != got {
					t.Fatalf("expected ComparePassword error %v got %v", tt.wants.err, err)
				}
				return
			}

		})
	}
}

// CompareAndSetPassword tests implementations of PasswordsService.
func CompareAndSetPassword(
	init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()),
	t *testing.T) {
	type args struct {
		user string
		old  string
		new  string
	}
	type wants struct {
		err error
	}
	tests := []struct {
		name   string
		fields PasswordFields
		args   args
		wants  wants
	}{
		{
			name: "setting a password to the existing password is valid",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user: "user1",
				old:  "howdydoody",
				new:  "howdydoody",
			},
			wants: wants{},
		},
		{
			name: "providing an incorrect old password is an error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user: "user1",
				old:  "invalid",
				new:  "not used",
			},
			wants: wants{
				err: fmt.Errorf("<forbidden> your username or password is incorrect"),
			},
		},
		{
			name: "<invalid> a new password that is less than 8 characters is an error",
			fields: PasswordFields{
				Users: []*influxdb.User{
					{
						Name: "user1",
						ID:   MustIDBase16(oneID),
					},
				},
				Passwords: []string{"howdydoody"},
			},
			args: args{
				user: "user1",
				old:  "howdydoody",
				new:  "short",
			},
			wants: wants{
				err: fmt.Errorf("<invalid> passwords must be at least 8 characters long"),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s, done := init(tt.fields, t)
			defer done()
			ctx := context.Background()

			err := s.CompareAndSetPassword(ctx, tt.args.user, tt.args.old, tt.args.new)

			if (err != nil && tt.wants.err == nil) || (err == nil && tt.wants.err != nil) {
				t.Fatalf("expected CompareAndSetPassword error %v got %v", tt.wants.err, err)
				return
			}

			if err != nil {
				if want, got := tt.wants.err.Error(), err.Error(); want != got {
					t.Fatalf("expected CompareAndSetPassword error %v got %v", tt.wants.err, err)
				}
				return
			}

		})
	}

}


text:
.. _users-guide-compression:

Compression
-----------

In Varnish 3.0 we introduced native support for compression, using gzip
encoding. *Before* 3.0, Varnish would never compress objects.

In Varnish 4.0 compression defaults to "on", meaning that it tries to
be smart and do the sensible thing.

If you don't want Varnish tampering with the encoding you can disable
compression all together by setting the parameter `http_gzip_support` to
false. Please see man :ref:`ref-varnishd` for details.

Default behaviour
~~~~~~~~~~~~~~~~~

The default behaviour is active when the `http_gzip_support` parameter
is set to "on" and neither `beresp.do_gzip` nor `beresp.do_gunzip` are
used in VCL.

Unless returning from `vcl_recv` with `pipe` or `pass`, Varnish
modifies `req.http.Accept-Encoding`: if the client supports gzip
`req.http.Accept-Encoding` is set to "gzip", otherwise the header is
removed.

Unless the request is a `pass`, Varnish sets `bereq.http.Accept-Encoding`
to "gzip" before `vcl_backend_fetch` runs, so the header can be changed
in VCL.

If the server responds with gzip'ed content it will be stored in memory
in its compressed form and `Accept-Encoding` will be added to the
`Vary` header.

To clients supporting gzip, compressed content is delivered unmodified.

For clients not supporting gzip, compressed content gets decompressed
on the fly while delivering it. The `Content-Encoding` response header
gets removed and any `Etag` gets weakened (by prepending "W/").

For Vary Lookups, `Accept-Encoding` is ignored.

Compressing content if backends don't
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can tell Varnish to compress content before storing it in cache in
`vcl_backend_response` by setting `beresp.do_gzip` to "true", like this::

    sub vcl_backend_response {
        if (beresp.http.content-type ~ "text") {
            set beresp.do_gzip = true;
        }
    }

With `beresp.do_gzip` set to "true", Varnish will make the following
changes to the headers of the resulting object before inserting it in
the cache:

* set `obj.http.Content-Encoding` to "gzip"
* add "Accept-Encoding" to `obj.http.Vary`, unless already present
* weaken any `Etag` (by prepending "W/")

Generally, Varnish doesn't use much CPU so it might make more sense to
have Varnish spend CPU cycles compressing content than doing it in your
web- or application servers, which are more likely to be CPU-bound.

Please make sure that you don't try to compress content that is
uncompressable, like JPG, GIF and MP3 files. You'll only waste CPU cycles.

Uncompressing content before entering the cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also uncompress content before storing it in cache by setting
`beresp.do_gunzip` to "true". One use case for this feature is to work
around badly configured backends uselessly compressing already compressed
content like JPG images (but fixing the misbehaving backend is always
the better option).

With `beresp.do_gunzip` set to "true", Varnish will make the following
changes to the headers of the resulting object before inserting it in
the cache:

* remove `obj.http.Content-Encoding`
* weaken any `Etag` (by prepending "W/")

.. XXX pending closing #940: remove any "Accept-Encoding" from `obj.http.Vary`

GZIP and ESI
~~~~~~~~~~~~

If you are using Edge Side Includes (ESI) you'll be happy to note that
ESI and GZIP work together really well. Varnish will magically decompress
the content to do the ESI-processing, then recompress it for efficient
storage and delivery.

Turning off gzip support
~~~~~~~~~~~~~~~~~~~~~~~~

When the `http_gzip_support` parameter is set to "off", Varnish does
not do any of the header alterations documented above, handles `Vary:
Accept-Encoding` like it would for any other `Vary` value and ignores
`beresp.do_gzip` and `beresp.do_gunzip`.

A random outburst
~~~~~~~~~~~~~~~~~

Poul-Henning Kamp has written :ref:`phk_gzip` which talks a bit more
about how the implementation works.


text:
package pl.delapiero.ztp;

/**
 *
 * @author grzesiek
 */
public class klientForm extends javax.swing.JFrame {

    /**
     * Creates new form klientForm
     */

    private Klient watek;

    public klientForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        konsola = new javax.swing.JTextArea();
        tWiadomosc = new javax.swing.JTextField();
        bWyslij = new javax.swing.JButton();
        bPolacz = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tIP = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tPort = new javax.swing.JSpinner();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Klient");

        konsola.setColumns(20);
        konsola.setRows(5);
        jScrollPane1.setViewportView(konsola);

        bWyslij.setText("wyślij");
        bWyslij.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bWyslijActionPerformed(evt);
            }
        });

        bPolacz.setText("Połącz");
        bPolacz.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPolaczActionPerformed(evt);
            }
        });

        jLabel1.setText("IP");
        jLabel1.setName("lbIP"); // NOI18N

        tIP.setText("127.0.0.1");
        tIP.setName("tIP"); // NOI18N

        jLabel2.setText("port");
        jLabel2.setName("lbPort"); // NOI18N

        tPort.setName("tPort"); // NOI18N
        tPort.setValue(4444);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tWiadomosc, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bPolacz)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tIP)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tPort)
                            .addComponent(bWyslij, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bPolacz)
                    .addComponent(jLabel1)
                    .addComponent(tIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(tPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tWiadomosc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bWyslij))
                .addGap(7, 7, 7)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void komunikat(String wiadomosc){
        System.out.println(wiadomosc);
        konsola.append(wiadomosc + "\n");
    }

    private void bPolaczActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPolaczActionPerformed
        watek = new Klient(konsola);
        watek.ustawSerwer(tIP.getText(),Integer.parseInt(tPort.getValue().toString()));
        watek.start();
        komunikat("Oczekiwanie na połączenie...");
    }//GEN-LAST:event_bPolaczActionPerformed

    private void bWyslijActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bWyslijActionPerformed
        watek.wyslij(tWiadomosc.getText());
    }//GEN-LAST:event_bWyslijActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(klientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(klientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(klientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(klientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new klientForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bPolacz;
    private javax.swing.JButton bWyslij;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea konsola;
    private javax.swing.JTextField tIP;
    private javax.swing.JSpinner tPort;
    private javax.swing.JTextField tWiadomosc;
    // End of variables declaration//GEN-END:variables
}


text:
packages = case node[:platform]
  when "centos","redhat","fedora","scientific"
    %w{openssh-clients openssh}
  when "arch"
    %w{openssh}
  else
    %w{openssh-client openssh-server}
  end

packages.each do |pkg|
  package pkg
end

template "/etc/ssh/ssh_config" do
  source "ssh_config.erb"
  mode '0644'
  owner 'root'
  group 'root'
  variables(:settings => node[:openssh][:client])
end

template "/etc/ssh/sshd_config" do
  source "sshd_config.erb"
  mode '0644'
  owner 'root'
  group 'root'
  variables(:settings => node[:openssh][:server])
end

service "ssh" do
  case node[:platform]
  when "centos","redhat","fedora","arch","scientific"
    service_name "sshd"
  else
    service_name "ssh"
  end
  supports value_for_platform(
    "debian" => { "default" => [ :restart, :reload, :status ] },
    "ubuntu" => {
      "8.04" => [ :restart, :reload ],
      "default" => [ :restart, :reload, :status ]
    },
    "centos" => { "default" => [ :restart, :reload, :status ] },
    "redhat" => { "default" => [ :restart, :reload, :status ] },
    "fedora" => { "default" => [ :restart, :reload, :status ] },
    "scientific" => { "default" => [ :restart, :reload, :status ] },
    "arch" => { "default" => [ :restart ] },
    "default" => { "default" => [:restart, :reload ] }
  )
  action [ :enable, :start ]
end


text:
@interface UIImage (NSPColorUtils)

//programmatically create an UIImage with 1 pixel of a given color
+ (UIImage *)imageWithColor:(UIColor *)color;

- (UIImage*)imageWithTintColor:(UIColor*)tintColor;

@end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<qualitasConfiguration>
    <analystConfiguration analysisEnabled="true">
        <globalParameters>
            <cost>12.12</cost>
            <costWeight>0.0</costWeight>
            <effort>0.0</effort>
            <effortWeight>0.0</effortWeight>
            <reputation>0.0</reputation>
            <reputationWeight>0.0</reputationWeight>
            <minInputSize>0.0</minInputSize>
            <maxInputSize>0.0</maxInputSize>
            <inputSizeWeight>0.0</inputSizeWeight>
            <minOutputSize>0.0</minOutputSize>
            <maxOutputSize>0.0</maxOutputSize>
            <outputSizeWeight>0.0</outputSizeWeight>
            <minExecutionTime>0.0</minExecutionTime>
            <maxExecutionTime>0.0</maxExecutionTime>
            <executionTimeWeight>0.0</executionTimeWeight>
            <geolocationDistanceWeight>0.0</geolocationDistanceWeight>
        </globalParameters>
        <partners>
            <partner anlysisEnabled="true" name="stockQuotesServicePartnerLink">
                <parameters>
                    <effort>12.12</effort>
                </parameters>
                <services>
                    <service anlysisEnabled="true" name="getStockQuote">
                        <parameters>
                            <reputation>12.12</reputation>
                        </parameters>
                    </service>
                </services>
            </partner>
        </partners>
    </analystConfiguration>
    <monitorConfiguration>
        <partners>
            <partner name="stockQuotesServicePartnerLink">
                <services>
                    <service mep="in-only" name="setStockQuote"/>
                    <service mep="out-only" name="isStockOpen"/>
                </services>
            </partner>
        </partners>
    </monitorConfiguration>
</qualitasConfiguration>


text:
import argparse
import os
import re
import sys

from em import BANGPATH_OPT
from em import Hook
from ros_buildfarm.argument import add_argument_arch
from ros_buildfarm.argument import add_argument_build_name
from ros_buildfarm.argument import add_argument_build_tool
from ros_buildfarm.argument import add_argument_build_tool_args
from ros_buildfarm.argument import add_argument_build_tool_test_args
from ros_buildfarm.argument import add_argument_config_url
from ros_buildfarm.argument import add_argument_os_code_name
from ros_buildfarm.argument import add_argument_os_name
from ros_buildfarm.argument import add_argument_package_selection_args
from ros_buildfarm.argument import add_argument_repos_file_urls
from ros_buildfarm.argument import add_argument_rosdistro_name
from ros_buildfarm.argument import add_argument_skip_cleanup
from ros_buildfarm.argument import add_argument_test_branch
from ros_buildfarm.argument import build_tool_args_epilog_action
from ros_buildfarm.argument import extract_multiple_remainders
from ros_buildfarm.ci_job import configure_ci_job
from ros_buildfarm.common import get_ci_job_name
from ros_buildfarm.config import get_ci_build_files
from ros_buildfarm.config import get_index as get_config_index
from ros_buildfarm.templates import expand_template

def main(argv=sys.argv[1:]):
    build_tool_args_helper = build_tool_args_epilog_action(
        'ci', get_ci_build_files)
    parser = argparse.ArgumentParser(
        description="Generate a 'CI' script",
        formatter_class=argparse.RawTextHelpFormatter)

    # Positional
    add_argument_config_url(parser, action=build_tool_args_helper)
    add_argument_rosdistro_name(parser, action=build_tool_args_helper)
    add_argument_build_name(parser, 'ci', action=build_tool_args_helper)
    add_argument_os_name(parser)
    add_argument_os_code_name(parser)
    add_argument_arch(parser)

    add_argument_build_tool(parser)
    a1 = add_argument_package_selection_args(parser)
    a2 = add_argument_build_tool_args(parser)
    a3 = add_argument_build_tool_test_args(parser)
    add_argument_repos_file_urls(parser)
    add_argument_skip_cleanup(parser)
    add_argument_test_branch(parser)
    parser.add_argument(
        '--underlay-source-path', nargs='*', metavar='DIR_NAME',
        help='Path to one or more install spaces to use as an underlay')

    remainder_args = extract_multiple_remainders(argv, (a1, a2, a3))
    args = parser.parse_args(argv)
    for k, v in remainder_args.items():
        setattr(args, k, v)

    # collect all template snippets of specific types
    class IncludeHook(Hook):

        def __init__(self):
            Hook.__init__(self)
            self.scms = []
            self.scripts = []
            self.parameters = {}

            if args.skip_cleanup:
                self.parameters['skip_cleanup'] = 'true'
            if args.repos_file_urls is not None:
                self.parameters['repos_file_urls'] = ' '.join(args.repos_file_urls)
            if args.test_branch is not None:
                self.parameters['test_branch'] = args.test_branch
            if args.package_selection_args is not None:
                self.parameters['package_selection_args'] = ' '.join(args.package_selection_args)
            if args.build_tool_args is not None:
                self.parameters['build_tool_args'] = ' '.join(args.build_tool_args)
            if args.build_tool_test_args is not None:
                self.parameters['build_tool_test_args'] = ' '.join(args.build_tool_test_args)

        def beforeInclude(self, *_, **kwargs):
            template_path = kwargs['file'].name
            if template_path.endswith('/snippet/scm.xml.em'):
                self.scms.append(
                    (kwargs['locals']['repo_spec'], kwargs['locals']['path']))
            if template_path.endswith('/snippet/builder_shell.xml.em'):
                script = kwargs['locals']['script']
                # reuse existing ros_buildfarm folder if it exists
                if 'Clone ros_buildfarm' in script:
                    lines = script.splitlines()
                    lines.insert(0, 'if [ ! -d "ros_buildfarm" ]; then')
                    lines += [
                        'else',
                        'echo "Using existing ros_buildfarm folder"',
                        'fi',
                    ]
                    script = '\n'.join(lines)
                if args.build_tool and ' --build-tool ' in script:
                    script = script.replace(
                        ' --build-tool catkin_make_isolated',
                        ' --build-tool ' + args.build_tool)
                self.scripts.append(script)
            if template_path.endswith('/snippet/property_parameters-definition.xml.em'):
                for parameter in reversed(kwargs['locals']['parameters']):
                    name = parameter['name']
                    value_type = parameter['type']
                    if value_type in ['string', 'text']:
                        default_value = parameter['default_value']
                    elif value_type == 'boolean':
                        default_value = 'true' if parameter.get(
                            'default_value', False) else 'false'
                    else:
                        continue

                    self.parameters.setdefault(name, default_value)

    hook = IncludeHook()
    from ros_buildfarm import templates
    templates.template_hooks = [hook]

    config = get_config_index(args.config_url)
    build_files = get_ci_build_files(config, args.rosdistro_name)
    build_file = build_files[args.ci_build_name]

    underlay_source_paths = [os.path.abspath(p) for p in args.underlay_source_path or []]

    configure_ci_job(
        args.config_url, args.rosdistro_name, args.ci_build_name,
        args.os_name, args.os_code_name, args.arch,
        config=config, build_file=build_file, jenkins=False, views=False,
        underlay_source_paths=underlay_source_paths)

    templates.template_hooks = None

    ci_job_name = get_ci_job_name(
        args.rosdistro_name, args.os_name,
        args.os_code_name, args.arch, 'script')

    value = expand_template(
        'ci/ci_script.sh.em', {
            'ci_job_name': ci_job_name,
            'scms': hook.scms,
            'scripts': hook.scripts,
            'build_tool': args.build_tool or build_file.build_tool,
            'parameters': hook.parameters},
        options={BANGPATH_OPT: False})
    value = re.sub(r'(^| )python3 ', r'\1' + sys.executable + ' ', value, flags=re.M)
    print(value)

if __name__ == '__main__':
    sys.exit(main())


text:
import collections

Tagging = collections.namedtuple("Tagging", ["tag", "object"])

class _Undefined(object):
	_instance = None

	def __new__(cls, *args, **kwargs):
		if not isinstance(cls._instance, cls):
			cls._instance = object.__new__(cls, *args, **kwargs)
		return cls._instance

	def __str__(self):
		return "Undefined"

	def __repr__(self):
		return "Undefined"

Undefined = _Undefined()


text:
import json
import uuid
from datetime import timedelta
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models, IntegrityError
from django.db.models import QuerySet, CASCADE
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

def _get_current_datetime():
    return timezone.now()

def get_time_to_live_minutes(app):
    """
    Get the configured time to live in minutes for tokens for the given ``app``.
    """
    time_to_live_minutes = getattr(
        settings,
        'DJANGO_CRADMIN_SECURE_USER_TOKEN_TIME_TO_LIVE_MINUTES', {
            'default': 60 * 24 * 4  # Default to 4 days
        })
    return time_to_live_minutes.get(app, time_to_live_minutes['default'])

def get_expiration_datetime_for_app(app):
    """
    Get the expiration datetime of tokens for the given ``app``
    relative to ``now``.

    If the given app is configured to with 60 minutes time to live,
    this will return a datetime object representing 60 minutes in the future.
    """
    time_to_live_minutes = get_time_to_live_minutes(app)
    return _get_current_datetime() + timedelta(minutes=time_to_live_minutes)

def generate_token():
    """
    Generate a token for the :obj:`.GenericTokenWithMetadata.token` field.

    Joins an UUID1 (unique uuid) with an UUID4 (random uuid), so the chance
    of this not beeing unique is very low, and guessing this is
    very hard.

    Returns:
        A token that is very unlikely to not be unique.
    """
    return u'{}-{}'.format(uuid.uuid1(), uuid.uuid4())

class GenericTokenExpiredError(Exception):
    """
    Raised by :meth:`.GenericTokenWithMetadata.get_and_validate` when
    the token is found, but has expired.
    """

class GenericTokenWithMetadataQuerySet(QuerySet):
    """
    QuerySet for :class:`.GenericTokenWithMetadata`.
    """
    def unsafe_pop(self, app, token):
        """
        Get the :class:`.GenericTokenWithMetadata` matching the given
        `token` and `app`. Removes the GenericTokenWithMetadata from the database, and
        returns the `GenericTokenWithMetadata` object.

        You should normally use :meth:`.GenericTokenWithMetadataBaseManager.pop`
        instead of this.

        Raises:
            GenericTokenWithMetadata.DoesNotExist if no matching token is stored for
            the given app.
        """
        token = self.get(token=token, app=app)
        token.delete()
        return token

    def filter_has_expired(self):
        """
        Return a queryset containing only the expired GenericTokenWithMetadata objects in
        the current queryset.
        """
        return self.filter(
            expiration_datetime__isnull=False,
            expiration_datetime__lt=_get_current_datetime())

    def filter_not_expired(self):
        """
        Return a queryset containing only the un-expired GenericTokenWithMetadata objects in
        the current queryset.
        """
        return self.filter(
            models.Q(expiration_datetime=None) |
            models.Q(expiration_datetime__gte=_get_current_datetime()))

    def filter_by_content_object(self, content_object):
        """
        Filter by :obj:`.GenericTokenWithMetadata.content_object`.

        Examples:
            Lets say the content_object is a User object, you
            can find all tokens for that user in the
            ``page_admin_invites`` app like this::

                from django.contrib.auth import get_user_model
                user = get_user_model()
                GenericTokenWithMetadata.objects\
                    .filter(app='page_admin_invites')\
                    .filter_by_content_object(user)
        """
        content_type = ContentType.objects.get_for_model(content_object)
        return self.filter(
            object_id=content_object.pk,
            content_type=content_type)

    def filter_usable_by_content_object_in_app(self, content_object, app):
        """
        Filters only non-expired tokens with the given ``content_object`` and ``app``.
        """
        return self.filter_not_expired()\
            .filter(app=app)\
            .filter_by_content_object(content_object)

class GenericTokenWithMetadataBaseManager(models.Manager):
    """
    Manager for :class:`.GenericTokenWithMetadata`.

    Inherits all methods from :class:`.GenericTokenWithMetadataQuerySet`.
    """
    def generate(self, app, expiration_datetime, content_object, metadata=None):
        """
        Generate and save a token for the given user and app.

        Returns:
            A :class:`.GenericTokenWithMetadata` object with a token
            that is guaranteed to be unique.
        """
        token = generate_token()
        generic_token_with_metadata = GenericTokenWithMetadata(
            content_object=content_object, app=app, token=token,
            created_datetime=_get_current_datetime(),
            expiration_datetime=expiration_datetime)
        if metadata:
            generic_token_with_metadata.metadata = metadata

        try:
            generic_token_with_metadata.full_clean()
        except ValidationError as e:
            if 'token' in e.error_dict and e.error_dict['token'][0].code == 'unique':
                return self.generate(
                    app=app, content_object=content_object,
                    expiration_datetime=expiration_datetime, metadata=metadata)
            else:
                raise

        try:
            generic_token_with_metadata.save()
        except IntegrityError:
            return self.generate(
                app=app, content_object=content_object,
                expiration_datetime=expiration_datetime, metadata=metadata)
        else:
            return generic_token_with_metadata

    def pop(self, app, token):
        """
        Get the :class:`.GenericTokenWithMetadata` matching the given
        `token` and `app`. Removes the GenericTokenWithMetadata from the database, and
        returns the `GenericTokenWithMetadata` object.

        Does not return expired tokens.

        Raises:
            GenericTokenWithMetadata.DoesNotExist: If no matching token is stored for the
                given app, or if the token is expired.
        """
        return self.filter_not_expired().unsafe_pop(app=app, token=token)

    def delete_expired(self):
        """
        Delete all expired tokens.
        """
        self.filter_has_expired().delete()

    def get_and_validate(self, app, token):
        """
        Get the given ``token`` for the given ``app``.

        Raises:
            GenericTokenWithMetadata.DoesNotExist: If the token does not exist.
            GenericTokenExpiredError: If the token has expired.
        """
        token = GenericTokenWithMetadata.objects.get(app=app, token=token)
        if token.is_expired():
            raise GenericTokenExpiredError('The token has expired.')
        return token

class GenericTokenWithMetadata(models.Model):
    """
    Provides a secure token with attached metadata suitable for
    email and sharing workflows like password reset, public share urls, etc.
    """
    objects = GenericTokenWithMetadataBaseManager.from_queryset(GenericTokenWithMetadataQuerySet)()

    #: The app that generated the token.
    #: You should set this to the name of the app the
    #: generated the token.
    app = models.CharField(db_index=True, max_length=255)

    #: A unique and random token, set it using :func:`.generate_token`.
    token = models.CharField(max_length=100, unique=True)

    #: Datetime when the token was created.
    created_datetime = models.DateTimeField(
        verbose_name=_('Created'))

    #: Datetime when the token expires.
    #: This can be `None`, which means that the token does not expire.
    expiration_datetime = models.DateTimeField(
        null=True, default=None, blank=True,
        verbose_name=_('Expires'))

    #: Single use?
    #: If this is `False`, the token can be used an unlimited number of
    #: times.
    single_use = models.BooleanField(default=True)

    #: JSON encoded metadata
    metadata_json = models.TextField(null=False, blank=True, default='')

    #: The content-type of the :obj:`~.GenericTokenWithMetadata.content_object`.
    #: Together with :obj:`~.GenericTokenWithMetadata.object_id` this creates a
    #: generic foreign key to any Django model.
    content_type = models.ForeignKey(ContentType, on_delete=CASCADE)

    #: The object ID of the :obj:`~.GenericTokenWithMetadata.content_object`.
    #: Together with :obj:`~.GenericTokenWithMetadata.content_type` this creates a
    #: generic foreign key to any Django model.
    object_id = models.PositiveIntegerField()

    #: A :class:`django.contrib.contenttypes.fields.GenericForeignKey` to
    #: the object this token is for.
    #:
    #: This generic relationship is used to associate the token
    #: with a specific object.
    #:
    #: Use cases:
    #:
    #: - Password reset: Use the content_object to link to a User object when you
    #:   create password reset tokens.
    #: - Invites: Use the content_object to link to the object that you
    #:   are inviting users to. This enables you to filter on the
    #:   content object to show pending shares.
    content_object = GenericForeignKey('content_type', 'object_id')

    def is_expired(self):
        """
        Returns `True` if :obj:`.GenericTokenWithMetadata.expiration_datetime` is in the past,
        and `False` if it is in the future or now.
        """
        return self.expiration_datetime is not None and self.expiration_datetime < _get_current_datetime()

    @property
    def metadata(self):
        """
        Decode :obj:`.GenericTokenWithMetadata.metadata_json` and return the result.

        Return `None` if metadata_json is empty.
        """
        if self.metadata_json:
            if not hasattr(self, '_metadata'):
                # Store the decoded metadata to avoid re-decoding the json for
                # each access. We invalidate this cache in the setter.
                self._metadata = json.loads(self.metadata_json)
            return self._metadata
        else:
            return None

    @metadata.setter
    def metadata(self, metadata):
        """
        Set :obj:`.GenericTokenWithMetadata.metadata_json`. Encodes the given
        metadata using `json.dumps`.
        """
        self.metadata_json = json.dumps(metadata)
        if hasattr(self, '_metadata'):
            delattr(self, '_metadata')


text:
package fake_authenticators

import (
	"regexp"
	"sync"

	"code.cloudfoundry.org/diego-ssh/authenticators"
	"golang.org/x/crypto/ssh"
)

type FakePasswordAuthenticator struct {
	AuthenticateStub        func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error)
	authenticateMutex       sync.RWMutex
	authenticateArgsForCall []struct {
		arg1 ssh.ConnMetadata
		arg2 []byte
	}
	authenticateReturns struct {
		result1 *ssh.Permissions
		result2 error
	}
	authenticateReturnsOnCall map[int]struct {
		result1 *ssh.Permissions
		result2 error
	}
	UserRegexpStub        func() *regexp.Regexp
	userRegexpMutex       sync.RWMutex
	userRegexpArgsForCall []struct {
	}
	userRegexpReturns struct {
		result1 *regexp.Regexp
	}
	userRegexpReturnsOnCall map[int]struct {
		result1 *regexp.Regexp
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakePasswordAuthenticator) Authenticate(arg1 ssh.ConnMetadata, arg2 []byte) (*ssh.Permissions, error) {
	var arg2Copy []byte
	if arg2 != nil {
		arg2Copy = make([]byte, len(arg2))
		copy(arg2Copy, arg2)
	}
	fake.authenticateMutex.Lock()
	ret, specificReturn := fake.authenticateReturnsOnCall[len(fake.authenticateArgsForCall)]
	fake.authenticateArgsForCall = append(fake.authenticateArgsForCall, struct {
		arg1 ssh.ConnMetadata
		arg2 []byte
	}{arg1, arg2Copy})
	fake.recordInvocation("Authenticate", []interface{}{arg1, arg2Copy})
	authenticateStubCopy := fake.AuthenticateStub
	fake.authenticateMutex.Unlock()
	if authenticateStubCopy != nil {
		return authenticateStubCopy(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.authenticateReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakePasswordAuthenticator) AuthenticateCallCount() int {
	fake.authenticateMutex.RLock()
	defer fake.authenticateMutex.RUnlock()
	return len(fake.authenticateArgsForCall)
}

func (fake *FakePasswordAuthenticator) AuthenticateCalls(stub func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error)) {
	fake.authenticateMutex.Lock()
	defer fake.authenticateMutex.Unlock()
	fake.AuthenticateStub = stub
}

func (fake *FakePasswordAuthenticator) AuthenticateArgsForCall(i int) (ssh.ConnMetadata, []byte) {
	fake.authenticateMutex.RLock()
	defer fake.authenticateMutex.RUnlock()
	argsForCall := fake.authenticateArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakePasswordAuthenticator) AuthenticateReturns(result1 *ssh.Permissions, result2 error) {
	fake.authenticateMutex.Lock()
	defer fake.authenticateMutex.Unlock()
	fake.AuthenticateStub = nil
	fake.authenticateReturns = struct {
		result1 *ssh.Permissions
		result2 error
	}{result1, result2}
}

func (fake *FakePasswordAuthenticator) AuthenticateReturnsOnCall(i int, result1 *ssh.Permissions, result2 error) {
	fake.authenticateMutex.Lock()
	defer fake.authenticateMutex.Unlock()
	fake.AuthenticateStub = nil
	if fake.authenticateReturnsOnCall == nil {
		fake.authenticateReturnsOnCall = make(map[int]struct {
			result1 *ssh.Permissions
			result2 error
		})
	}
	fake.authenticateReturnsOnCall[i] = struct {
		result1 *ssh.Permissions
		result2 error
	}{result1, result2}
}

func (fake *FakePasswordAuthenticator) UserRegexp() *regexp.Regexp {
	fake.userRegexpMutex.Lock()
	ret, specificReturn := fake.userRegexpReturnsOnCall[len(fake.userRegexpArgsForCall)]
	fake.userRegexpArgsForCall = append(fake.userRegexpArgsForCall, struct {
	}{})
	fake.recordInvocation("UserRegexp", []interface{}{})
	userRegexpStubCopy := fake.UserRegexpStub
	fake.userRegexpMutex.Unlock()
	if userRegexpStubCopy != nil {
		return userRegexpStubCopy()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.userRegexpReturns
	return fakeReturns.result1
}

func (fake *FakePasswordAuthenticator) UserRegexpCallCount() int {
	fake.userRegexpMutex.RLock()
	defer fake.userRegexpMutex.RUnlock()
	return len(fake.userRegexpArgsForCall)
}

func (fake *FakePasswordAuthenticator) UserRegexpCalls(stub func() *regexp.Regexp) {
	fake.userRegexpMutex.Lock()
	defer fake.userRegexpMutex.Unlock()
	fake.UserRegexpStub = stub
}

func (fake *FakePasswordAuthenticator) UserRegexpReturns(result1 *regexp.Regexp) {
	fake.userRegexpMutex.Lock()
	defer fake.userRegexpMutex.Unlock()
	fake.UserRegexpStub = nil
	fake.userRegexpReturns = struct {
		result1 *regexp.Regexp
	}{result1}
}

func (fake *FakePasswordAuthenticator) UserRegexpReturnsOnCall(i int, result1 *regexp.Regexp) {
	fake.userRegexpMutex.Lock()
	defer fake.userRegexpMutex.Unlock()
	fake.UserRegexpStub = nil
	if fake.userRegexpReturnsOnCall == nil {
		fake.userRegexpReturnsOnCall = make(map[int]struct {
			result1 *regexp.Regexp
		})
	}
	fake.userRegexpReturnsOnCall[i] = struct {
		result1 *regexp.Regexp
	}{result1}
}

func (fake *FakePasswordAuthenticator) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.authenticateMutex.RLock()
	defer fake.authenticateMutex.RUnlock()
	fake.userRegexpMutex.RLock()
	defer fake.userRegexpMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakePasswordAuthenticator) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ authenticators.PasswordAuthenticator = new(FakePasswordAuthenticator)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ControlRippleColorTheme" parent="translucentStatusBar">
        <item name="android:colorControlHighlight">@color/md_purple_500</item>
    </style>

    <style name="SelectableItemTheme">
        <item name="colorControlHighlight">@color/md_blue_500</item>
    </style>

    <style name="SelectableItemBackground">
        <item name="android:theme">@style/SelectableItemTheme</item>
        <item name="android:background">?attr/selectableItemBackground</item>
    </style>

    <!--21以上版本会到这里来找theme,可以添加一些api21以上特有的属性-->
    <style name="AppTheme" parent="AppThemeBase">

    </style>

    <style name="translucentStatusBar" parent="AppTheme">
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <!--<item name="android:windowTranslucentNavigation">true</item>-->
        <!--<item name="android:navigationBarColor">@android:color/transparent</item>-->
    </style>

</resources>


text:
package com.sms.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sms.dao.impl.AuthNodeDaoImpl;
import com.sms.dao.impl.AuthRoleDaoImpl;
import com.sms.service.AuthService;
import com.sms.vo.AuthNode;

public class AuthServiceImpl implements AuthService
{

	@Override
	public List<AuthNode> getAuth(int user_id)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<AuthNode> getAuth(String role)
	{
		AuthNodeDaoImpl ad = new AuthNodeDaoImpl();
		AuthRoleDaoImpl ar = new AuthRoleDaoImpl();
		int id = ar.getId(role);
		if(0 != id)
		{
			return ad.listByid(id);
		}
		return null;
	}

	@Override
	public boolean isAuth(int user_id, String url)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isAuth(String role, String url)
	{
		List<AuthNode> list =getAuth(role);
		if(list.size()>0)
		{
			for(int i=0; i<list.size() ;i++)
			{
				AuthNode an = list.get(i);
				if(an.getNode_name().equals(url))
				{
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public String getRoleName(int user_id)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean addAuth(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateAuth(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean delAuth(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean addrole(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updaterole(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean delrole(HttpServletRequest request, HttpServletResponse response)
	{
		// TODO Auto-generated method stub
		return false;
	}

}